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..80e08d55b --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1,11 @@ +module.exports = { + root: true, + parser: '@typescript-eslint/parser', + plugins: [ + '@typescript-eslint', + ], + extends: [ + 'eslint:recommended', + 'plugin:@typescript-eslint/recommended', + ], +}; 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/.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/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/__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/menu/menu.tsx b/components/menu/menu.tsx deleted file mode 100644 index afe830258..000000000 --- a/components/menu/menu.tsx +++ /dev/null @@ -1,123 +0,0 @@ -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, - MenuContent, - IconButton, - breakpoints, - 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' - -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') - -function Menu() { - return ( - - - - - - - - New Project - - {commandKey()} - N - - - - - Open... - - {commandKey()} - L - - - - - - Save - - {commandKey()} - S - - - - Save As... - - - {commandKey()} - S - - - - - - - Sign Out - - - - - - - - ) -} - -export default memo(Menu) - -function RecentFiles() { - return ( - - - Project A - - - Project B - - - Project C - - - ) -} - -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/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/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-color-select.tsx b/components/style-panel/quick-color-select.tsx deleted file mode 100644 index e1c9103d9..000000000 --- a/components/style-panel/quick-color-select.tsx +++ /dev/null @@ -1,45 +0,0 @@ -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' - -function handleColorChange(color: ColorStyle): void { - state.send('CHANGED_STYLE', { color }) -} - -export default function QuickColorSelect(): JSX.Element { - const color = useSelector((s) => s.values.selectedStyle.color) - const { theme } = useTheme() - - return ( - - - - - - - {Object.keys(strokes[theme]).map((colorStyle: ColorStyle) => ( - - - - ))} - - - - ) -} diff --git a/components/style-panel/quick-dash-select.tsx b/components/style-panel/quick-dash-select.tsx deleted file mode 100644 index 78da7e37f..000000000 --- a/components/style-panel/quick-dash-select.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import React, { memo } 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 { - DashDrawIcon, - DashDottedIcon, - DashSolidIcon, - DashDashedIcon, - StyleDropdownContent, - StyleDropdownItem, -} from './shared' - -const dashes = { - [DashStyle.Draw]: , - [DashStyle.Solid]: , - [DashStyle.Dashed]: , - [DashStyle.Dotted]: , -} - -function changeDashStyle(dash: DashStyle): void { - state.send('CHANGED_STYLE', { dash }) -} - -function QuickdashSelect(): JSX.Element { - const dash = useSelector((s) => s.values.selectedStyle.dash) - - return ( - - - {dashes[dash]} - - - - {Object.keys(DashStyle).map((dashStyle: DashStyle) => ( - - {dashes[dashStyle]} - - ))} - - - - ) -} - -export default memo(QuickdashSelect) 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/quick-size-select.tsx b/components/style-panel/quick-size-select.tsx deleted file mode 100644 index 535ac7ee9..000000000 --- a/components/style-panel/quick-size-select.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { memo } 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' - -const sizes = { - [SizeStyle.Small]: 6, - [SizeStyle.Medium]: 12, - [SizeStyle.Large]: 22, -} - -function changeSizeStyle(size: SizeStyle): void { - state.send('CHANGED_STYLE', { size }) -} - -function QuickSizeSelect(): JSX.Element { - const size = useSelector((s) => s.values.selectedStyle.size) - - return ( - - - - - - - {Object.keys(SizeStyle).map((sizeStyle: SizeStyle) => ( - - - - ))} - - - - ) -} - -export default memo(QuickSizeSelect) 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/tools-panel.tsx b/components/tools-panel/tools-panel.tsx deleted file mode 100644 index 21edd1de9..000000000 --- a/components/tools-panel/tools-panel.tsx +++ /dev/null @@ -1,200 +0,0 @@ -import { - ArrowTopRightIcon, - CircleIcon, - CursorArrowIcon, - LockClosedIcon, - LockOpen1Icon, - Pencil1Icon, - 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' - -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') - -export default function ToolsPanel(): JSX.Element { - const activeTool = useSelector((s) => s.data.activeTool) - - const isToolLocked = useSelector((s) => s.data.settings.isToolLocked) - - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {isToolLocked ? : } - - - - - - - - - ) -} - -const ToolsPanelContainer = styled('div', { - position: 'fixed', - bottom: 0, - left: 0, - right: 0, - width: '100%', - minWidth: 0, - maxWidth: '100%', - display: 'grid', - gridTemplateColumns: '1fr auto 1fr', - padding: '0', - alignItems: 'flex-end', - zIndex: 200, - gridGap: '$4', - gridRowGap: '$4', -}) - -const CenterWrap = styled('div', { - gridRow: 1, - gridColumn: 2, - display: 'flex', - width: 'fit-content', - alignItems: 'center', - justifyContent: 'center', - flexDirection: 'column', - gap: 12, -}) - -const LeftWrap = styled('div', { - gridRow: 1, - gridColumn: 1, - display: 'flex', - paddingLeft: '$3', - variants: { - size: { - mobile: { - flexDirection: 'column', - justifyContent: 'flex-end', - alignItems: 'flex-start', - '& > *:nth-of-type(1)': { - marginBottom: '8px', - }, - }, - small: { - flexDirection: 'row', - alignItems: 'flex-end', - justifyContent: 'space-between', - '& > *:nth-of-type(1)': { - marginBottom: '0px', - }, - }, - }, - }, -}) - -const RightWrap = styled('div', { - gridRow: 1, - gridColumn: 3, - display: 'flex', - paddingRight: '$3', - variants: { - size: { - mobile: { - flexDirection: 'column-reverse', - justifyContent: 'flex-end', - alignItems: 'flex-end', - '& > *:nth-of-type(2)': { - marginBottom: '8px', - }, - }, - small: { - flexDirection: 'row', - alignItems: 'flex-end', - justifyContent: 'space-between', - '& > *:nth-of-type(2)': { - marginBottom: '0px', - }, - }, - }, - }, -}) - -const StatusWrap = styled('div', { - gridRow: 2, - gridColumn: '1 / span 3', -}) 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/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..9bf40537f --- /dev/null +++ b/lerna.json @@ -0,0 +1,14 @@ +{ + "version": "0.0.41", + "registry": "https://registry.npmjs.org/", + "publishConfig": { + "access": "public" + }, + "npmClient": "yarn", + "useWorkspaces": true, + "packages": [ + "packages/core", + "packages/tldraw", + "packages/www" + ] +} 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..58895ddf4 100644 --- a/package.json +++ b/package.json @@ -1,99 +1,89 @@ { - "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", - "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: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" - }, + "version": "0.0.36", + "workspaces": [ + "packages/*" + ], "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/plugin-syntax-import-meta": "^7.10.4", + "@babel/preset-react": "^7.14.5", + "@babel/preset-typescript": "^7.15.0", + "@types/jest": "^26.0.24", + "@types/node": "^15.0.1", + "@types/react-dom": "^17.0.9", + "@types/react": "^17.0.16", + "@typescript-eslint/eslint-plugin": "^4.19.0", + "@typescript-eslint/parser": "^4.19.0", + "babel-jest": "^27.0.6", + "esbuild": "^0.11.11", + "jest": "^27.0.6", + "lerna": "^3.15.0", + "react-dom": "^17.0.2", + "react": "^17.0.2", + "ts-jest": "^27.0.4", + "tslib": "^2.3.0", + "typescript": "^4.3.5" + }, + "scripts": { + "test": "jest", + "lerna": "lerna", + "start": "lerna run dev --stream --parallel", + "build": "yarn build:packages && cd packages/www && yarn build", + "build:packages": "cd packages/core && yarn build && cd ../tldraw && yarn build" }, "prettier": { - "semi": false, + "trailingComma": "es5", "singleQuote": true, - "tabWidth": 2, - "useTabs": false + "semi": false, + "printWidth": 100 + }, + "dependencies": {}, + "jest": { + "preset": "ts-jest", + "transform": { + "^.+\\.(tsx|jsx|ts|js)?$": "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-react" + ], + "@babel/preset-typescript" + ], + "plugins": [ + "@babel/plugin-syntax-import-meta" + ] + } + } + }, + "testEnvironment": "jsdom", + "modulePathIgnorePatterns": [ + "/packages/core/build/", + "/packages/tldraw/build/" + ], + "moduleNameMapper": { + "@tldraw/core": "/packages/core/src", + "@tldraw/tldraw": "/packages/tldraw/src" + } } -} +} \ 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..ba4a97401 --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,54 @@ +{ + "name": "@tldraw/core", + "version": "0.0.41", + "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": [], + "files": [ + "README.md", + "dist" + ], + "main": "./dist/cjs/index.js", + "types": "./dist/types/index.d.ts", + "scripts": { + "dev": "node scripts/dev", + "build": "yarn clean && node scripts/build && tsc --emitDeclarationOnly --outDir dist/types", + "lint": "eslint src/ --ext .ts,.tsx", + "clean": "rm -rf dist", + "ts-node": "ts-node", + "docs": "typedoc --entryPoints src/index.ts" + }, + "devDependencies": { + "@types/node": "^15.0.1", + "@types/react": "^17.0.16", + "@types/react-dom": "^17.0.9", + "@typescript-eslint/eslint-plugin": "^4.19.0", + "@typescript-eslint/parser": "^4.19.0", + "babel-jest": "^27.0.6", + "esbuild": "^0.11.11", + "eslint": "^7.22.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "ts-node": "^9.1.1", + "tslib": "^2.3.0", + "typedoc": "^0.20.35", + "typescript": "^4.3.5" + }, + "peerDependencies": { + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "dependencies": { + "deepmerge": "^4.2.2", + "ismobilejs": "^1.1.1", + "react-error-boundary": "^3.1.3", + "react-use-gesture": "^9.1.3" + } +} \ No newline at end of file diff --git a/packages/core/scripts/build.js b/packages/core/scripts/build.js new file mode 100644 index 000000000..954c3dbc1 --- /dev/null +++ b/packages/core/scripts/build.js @@ -0,0 +1,33 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + try { + esbuild.buildSync({ + 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'], + }) + + fs.copyFile('./README.md', './dist/README.md', (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..cd9cf80cd --- /dev/null +++ b/packages/core/scripts/dev.js @@ -0,0 +1,33 @@ +/* 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: 'esnext', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.json', + external: ['react', 'react-dom'], + watch: { + onRebuild(error) { + if (error) { + console.log(`× ${name}: An error in prevented the rebuild.`) + return + } + console.log(`✔ ${name}: Rebuilt.`) + }, + }, + }) + + // result.stop(); +} + +main() diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 000000000..18579c25e --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,4 @@ +export * from './renderer' +export * from './types' +export * from './utils' +export * from './inputs' diff --git a/packages/core/src/inputs.tsx b/packages/core/src/inputs.tsx new file mode 100644 index 000000000..d0e6700e2 --- /dev/null +++ b/packages/core/src/inputs.tsx @@ -0,0 +1,348 @@ +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 + } + + canAccept = (_pointerId: PointerEvent['pointerId']): boolean => { + return true + // return ( + // this.activePointerId === undefined || this.activePointerId === pointerId + // ) + } + + 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/renderer/components/bounds/bounds-bg.tsx b/packages/core/src/renderer/components/bounds/bounds-bg.tsx new file mode 100644 index 000000000..cfbd3185a --- /dev/null +++ b/packages/core/src/renderer/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/useBoundsEvents' + +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/renderer/components/bounds/bounds.tsx b/packages/core/src/renderer/components/bounds/bounds.tsx new file mode 100644 index 000000000..5710125a4 --- /dev/null +++ b/packages/core/src/renderer/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.isMobile() ? 10 : 8) / zoom // Touch target size + const center = Utils.getBoundsCenter(bounds) + + return ( + + + {!isLocked && ( + <> + + + + + + + + + + + )} + + ) +} diff --git a/packages/core/src/renderer/components/bounds/center-handle.tsx b/packages/core/src/renderer/components/bounds/center-handle.tsx new file mode 100644 index 000000000..ccaf8951a --- /dev/null +++ b/packages/core/src/renderer/components/bounds/center-handle.tsx @@ -0,0 +1,22 @@ +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/renderer/components/bounds/corner-handle.tsx b/packages/core/src/renderer/components/bounds/corner-handle.tsx new file mode 100644 index 000000000..0de5aeb04 --- /dev/null +++ b/packages/core/src/renderer/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/renderer/components/bounds/edge-handle.tsx b/packages/core/src/renderer/components/bounds/edge-handle.tsx new file mode 100644 index 000000000..a8e0a448a --- /dev/null +++ b/packages/core/src/renderer/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/renderer/components/bounds/index.ts b/packages/core/src/renderer/components/bounds/index.ts new file mode 100644 index 000000000..3f5e39ea0 --- /dev/null +++ b/packages/core/src/renderer/components/bounds/index.ts @@ -0,0 +1 @@ +export * from './bounds' diff --git a/packages/core/src/renderer/components/bounds/rotate-handle.tsx b/packages/core/src/renderer/components/bounds/rotate-handle.tsx new file mode 100644 index 000000000..5f1a19338 --- /dev/null +++ b/packages/core/src/renderer/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/renderer/components/brush/BrushUpdater.ts b/packages/core/src/renderer/components/brush/BrushUpdater.ts new file mode 100644 index 000000000..558e8cf70 --- /dev/null +++ b/packages/core/src/renderer/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/renderer/components/brush/brush.tsx b/packages/core/src/renderer/components/brush/brush.tsx new file mode 100644 index 000000000..052f15edb --- /dev/null +++ b/packages/core/src/renderer/components/brush/brush.tsx @@ -0,0 +1,9 @@ +import * as React from 'react' +import { TLBounds } from '../../../types' +import { BrushUpdater } from './BrushUpdater' + +export const brushUpdater = new BrushUpdater() + +export const Brush = React.memo((): JSX.Element | null => { + return +}) diff --git a/packages/core/src/renderer/components/brush/index.ts b/packages/core/src/renderer/components/brush/index.ts new file mode 100644 index 000000000..6931dc407 --- /dev/null +++ b/packages/core/src/renderer/components/brush/index.ts @@ -0,0 +1,2 @@ +export * from './brush' +export * from './BrushUpdater' diff --git a/packages/core/src/renderer/components/canvas.tsx b/packages/core/src/renderer/components/canvas.tsx new file mode 100644 index 000000000..cfa196a16 --- /dev/null +++ b/packages/core/src/renderer/components/canvas.tsx @@ -0,0 +1,64 @@ +import * as React from 'react' +import { ErrorBoundary } from 'react-error-boundary' +import { + useZoomEvents, + useSafariFocusOutFix, + useCanvasEvents, + useCameraCss, +} from '../hooks' +import { ErrorFallback } from './error-fallback' +import type { TLPage, TLPageState, TLShape } from '../../types' + +import { Brush } from './brush' +import { Defs } from './defs' +import { Page } from './page' +import { usePreventNavigation } from '../hooks/usePreventNavigation' + +function resetError() { + void null +} + +interface CanvasProps { + page: TLPage + pageState: TLPageState + hideBounds?: boolean + hideIndicators?: boolean +} + +export const Canvas = React.memo(function Canvas({ + page, + pageState, + 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/renderer/components/defs.tsx b/packages/core/src/renderer/components/defs.tsx new file mode 100644 index 000000000..2f390b974 --- /dev/null +++ b/packages/core/src/renderer/components/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/renderer/components/error-fallback.tsx b/packages/core/src/renderer/components/error-fallback.tsx new file mode 100644 index 000000000..b5b9427f9 --- /dev/null +++ b/packages/core/src/renderer/components/error-fallback.tsx @@ -0,0 +1,18 @@ +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) + console.error(error) + }, [error, resetErrorBoundary, callbacks]) + + return null +}) diff --git a/packages/core/src/renderer/components/handles/handle.tsx b/packages/core/src/renderer/components/handles/handle.tsx new file mode 100644 index 000000000..0220fe612 --- /dev/null +++ b/packages/core/src/renderer/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/renderer/components/handles/handles.tsx b/packages/core/src/renderer/components/handles/handles.tsx new file mode 100644 index 000000000..6f669de8d --- /dev/null +++ b/packages/core/src/renderer/components/handles/handles.tsx @@ -0,0 +1,37 @@ +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/renderer/components/handles/index.ts b/packages/core/src/renderer/components/handles/index.ts new file mode 100644 index 000000000..43453ba8c --- /dev/null +++ b/packages/core/src/renderer/components/handles/index.ts @@ -0,0 +1 @@ +export * from './handles' diff --git a/packages/core/src/renderer/components/page.tsx b/packages/core/src/renderer/components/page.tsx new file mode 100644 index 000000000..e70915a69 --- /dev/null +++ b/packages/core/src/renderer/components/page.tsx @@ -0,0 +1,135 @@ +import * as React from 'react' +import { useShapeTree } from '../hooks/useShapeTree' +import type { IShapeTreeNode, TLPage, TLPageState, TLShape } from '../../types' +import { Shape as ShapeComponent } from './shape' +import { useHandles, useRenderOnResize, useTLContext } from '../hooks' +import { Bounds } from './bounds' +import { BoundsBg } from './bounds/bounds-bg' +import { useSelection } from '../hooks' +import { Handles } from './handles' + +interface PageProps { + page: TLPage + pageState: TLPageState + hideBounds: boolean + hideIndicators: boolean +} + +export function Page({ + page, + pageState, + hideBounds, + hideIndicators, +}: PageProps): JSX.Element { + const { callbacks, shapeUtils } = useTLContext() + + useRenderOnResize() + + const shapeTree = useShapeTree( + page, + pageState, + shapeUtils, + 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.length > 1 && + selectedIds + .filter(Boolean) + .map((id) => ( + + ))} + {!hideIndicators && hoveredId && ( + + )} + {shapeWithHandles && } + + ) +} + +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)} + + ) + } +) + +interface ShapeNodeProps extends IShapeTreeNode {} + +const ShapeNode = React.memo( + ({ + shape, + children, + isEditing, + isDarkMode, + isBinding, + isCurrentParent, + }: ShapeNodeProps) => { + return ( + <> + + {children && + children.map((childNode) => ( + + ))} + + ) + } +) diff --git a/packages/core/src/renderer/components/shape/editing-text-shape.tsx b/packages/core/src/renderer/components/shape/editing-text-shape.tsx new file mode 100644 index 000000000..9b1f23ccb --- /dev/null +++ b/packages/core/src/renderer/components/shape/editing-text-shape.tsx @@ -0,0 +1,42 @@ +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, + isDarkMode, + isCurrentParent, +}: EditingShapeProps) { + const { + callbacks: { + onTextChange, + onTextBlur, + onTextFocus, + onTextKeyDown, + onTextKeyUp, + }, + } = useTLContext() + + const ref = React.useRef(null) + + return utils.render(shape, { + ref, + isEditing, + isCurrentParent, + isBinding, + isDarkMode, + onTextChange, + onTextBlur, + onTextFocus, + onTextKeyDown, + onTextKeyUp, + }) +} diff --git a/packages/core/src/renderer/components/shape/index.ts b/packages/core/src/renderer/components/shape/index.ts new file mode 100644 index 000000000..16fad8320 --- /dev/null +++ b/packages/core/src/renderer/components/shape/index.ts @@ -0,0 +1 @@ +export * from './shape' diff --git a/packages/core/src/renderer/components/shape/rendered-shape.tsx b/packages/core/src/renderer/components/shape/rendered-shape.tsx new file mode 100644 index 000000000..b098ed3bd --- /dev/null +++ b/packages/core/src/renderer/components/shape/rendered-shape.tsx @@ -0,0 +1,41 @@ +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, + isDarkMode, + isCurrentParent, + }: RenderedShapeProps) { + return utils.render(shape, { + isEditing, + isBinding, + isDarkMode, + isCurrentParent, + }) + }, + (prev, next) => { + if ( + prev.isEditing !== next.isEditing || + prev.isDarkMode !== next.isDarkMode || + prev.isBinding !== next.isBinding || + prev.isCurrentParent !== next.isCurrentParent + ) { + return false + } + + if (next.shape !== prev.shape) { + return !next.utils.shouldRender(next.shape, prev.shape) + } + + return true + } +) diff --git a/packages/core/src/renderer/components/shape/shape.tsx b/packages/core/src/renderer/components/shape/shape.tsx new file mode 100644 index 000000000..69d9553e5 --- /dev/null +++ b/packages/core/src/renderer/components/shape/shape.tsx @@ -0,0 +1,56 @@ +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, + isDarkMode, + isCurrentParent, + }: 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/renderer/hooks/index.ts b/packages/core/src/renderer/hooks/index.ts new file mode 100644 index 000000000..1551bd3ec --- /dev/null +++ b/packages/core/src/renderer/hooks/index.ts @@ -0,0 +1,14 @@ +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' diff --git a/packages/core/src/renderer/hooks/useBoundsEvents.tsx b/packages/core/src/renderer/hooks/useBoundsEvents.tsx new file mode 100644 index 000000000..ea5b2a70c --- /dev/null +++ b/packages/core/src/renderer/hooks/useBoundsEvents.tsx @@ -0,0 +1,88 @@ +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) => { + e.stopPropagation() + + 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/renderer/hooks/useBoundsHandleEvents.tsx b/packages/core/src/renderer/hooks/useBoundsHandleEvents.tsx new file mode 100644 index 000000000..b32f15860 --- /dev/null +++ b/packages/core/src/renderer/hooks/useBoundsHandleEvents.tsx @@ -0,0 +1,88 @@ +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) => { + e.stopPropagation() + 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/renderer/hooks/useCameraCss.tsx b/packages/core/src/renderer/hooks/useCameraCss.tsx new file mode 100644 index 000000000..63748c85d --- /dev/null +++ b/packages/core/src/renderer/hooks/useCameraCss.tsx @@ -0,0 +1,28 @@ +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/renderer/hooks/useCanvasEvents.tsx b/packages/core/src/renderer/hooks/useCanvasEvents.tsx new file mode 100644 index 000000000..6d0946345 --- /dev/null +++ b/packages/core/src/renderer/hooks/useCanvasEvents.tsx @@ -0,0 +1,59 @@ +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) => { + e.stopPropagation() + 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/renderer/hooks/useHandleEvents.tsx b/packages/core/src/renderer/hooks/useHandleEvents.tsx new file mode 100644 index 000000000..10c12c40b --- /dev/null +++ b/packages/core/src/renderer/hooks/useHandleEvents.tsx @@ -0,0 +1,88 @@ +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, 'bounds') + + 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) => { + e.stopPropagation() + 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/renderer/hooks/useHandles.ts b/packages/core/src/renderer/hooks/useHandles.ts new file mode 100644 index 000000000..c99f19acf --- /dev/null +++ b/packages/core/src/renderer/hooks/useHandles.ts @@ -0,0 +1,22 @@ +import type { 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/renderer/hooks/usePreventNavigation.tsx b/packages/core/src/renderer/hooks/usePreventNavigation.tsx new file mode 100644 index 000000000..38b529dbe --- /dev/null +++ b/packages/core/src/renderer/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) { + 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 () => {} + + 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/renderer/hooks/useRenderOnResize.tsx b/packages/core/src/renderer/hooks/useRenderOnResize.tsx new file mode 100644 index 000000000..73caa4e97 --- /dev/null +++ b/packages/core/src/renderer/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/renderer/hooks/useSafariFocusOutFix.tsx b/packages/core/src/renderer/hooks/useSafariFocusOutFix.tsx new file mode 100644 index 000000000..dc6489b6d --- /dev/null +++ b/packages/core/src/renderer/hooks/useSafariFocusOutFix.tsx @@ -0,0 +1,22 @@ +import Utils from '../../utils' +import { useEffect } from 'react' +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.isMobile()) { + document.addEventListener('focusout', handleFocusOut) + return () => document.removeEventListener('focusout', handleFocusOut) + } + + return () => null + }, [callbacks]) +} diff --git a/packages/core/src/renderer/hooks/useSelection.tsx b/packages/core/src/renderer/hooks/useSelection.tsx new file mode 100644 index 000000000..f26f7c6d9 --- /dev/null +++ b/packages/core/src/renderer/hooks/useSelection.tsx @@ -0,0 +1,84 @@ +import type { + TLPage, + TLPageState, + TLShape, + TLBounds, + TLShapeUtils, +} from '../../types' +import Utils from '../../utils' +import { useTLContext } from '../hooks/useTLContext' + +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/renderer/hooks/useShapeEvents.tsx b/packages/core/src/renderer/hooks/useShapeEvents.tsx new file mode 100644 index 000000000..b9b13fe41 --- /dev/null +++ b/packages/core/src/renderer/hooks/useShapeEvents.tsx @@ -0,0 +1,113 @@ +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 (e.button !== 0) return + if (disable) 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 + e.stopPropagation() + + 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/renderer/hooks/useShapeTree.tsx b/packages/core/src/renderer/hooks/useShapeTree.tsx new file mode 100644 index 000000000..bc17c2bc8 --- /dev/null +++ b/packages/core/src/renderer/hooks/useShapeTree.tsx @@ -0,0 +1,113 @@ +import * as React from 'react' +import type { + IShapeTreeNode, + TLPage, + TLPageState, + TLShape, + TLShapeUtils, + TLCallbacks, +} from '../../types' +import Utils, { Vec } from '../../utils' + +function addToShapeTree( + shape: TLShape, + branch: IShapeTreeNode[], + shapes: TLPage['shapes'], + selectedIds: string[], + info: { + bindingId?: string + hoveredId?: string + currentParentId?: string + editingId?: string + editingBindingId?: string + isDarkMode?: boolean + } +) { + const node: IShapeTreeNode = { + shape, + isCurrentParent: info.currentParentId === shape.id, + isEditing: info.editingId === shape.id, + isBinding: info.bindingId === shape.id, + isDarkMode: info.isDarkMode || false, + } + + 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, selectedIds, info) + ) + } +} + +export function useShapeTree( + page: TLPage, + pageState: TLPageState, + shapeUtils: TLShapeUtils, + 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 + + 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 (pageState.selectedIds.includes(shape.id)) return true + + const shapeBounds = shapeUtils[shape.type as T['type']].getBounds(shape) + + return ( + // TODO: Some shapes should always render (lines, rays) + Utils.boundsContain(viewport, shapeBounds) || + Utils.boundsCollide(viewport, shapeBounds) + ) + }) + + // Call onChange callback when number of rendering shapes changes + + if (shapesToRender.length !== rPreviousCount.current) { + setTimeout(() => onChange?.(shapesToRender.map((shape) => shape.id)), 0) + rPreviousCount.current = shapesToRender.length + } + + // Populate the shape tree + + const tree: IShapeTreeNode[] = [] + + shapesToRender + .sort((a, b) => a.childIndex - b.childIndex) + .forEach((shape) => + addToShapeTree(shape, tree, page.shapes, selectedIds, pageState) + ) + + return tree +} diff --git a/packages/core/src/renderer/hooks/useStyle.tsx b/packages/core/src/renderer/hooks/useStyle.tsx new file mode 100644 index 000000000..cf9a5580c --- /dev/null +++ b/packages/core/src/renderer/hooks/useStyle.tsx @@ -0,0 +1,232 @@ +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 () => {} + } + + 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.12)', + background: 'rgb(248, 249, 250)', + foreground: 'rgb(51, 51, 51)', +} + +const tlcss = css` + :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: none; + 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; + } +` + +export function useTLTheme(theme?: Partial) { + const [tltheme] = React.useState(() => ({ + ...defaultTheme, + ...theme, + })) + + useTheme('tl', tltheme) + + useStyle('tl-canvas', tlcss) +} diff --git a/packages/core/src/renderer/hooks/useTLContext.tsx b/packages/core/src/renderer/hooks/useTLContext.tsx new file mode 100644 index 000000000..bfeab3785 --- /dev/null +++ b/packages/core/src/renderer/hooks/useTLContext.tsx @@ -0,0 +1,23 @@ +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/renderer/hooks/useZoomEvents.ts b/packages/core/src/renderer/hooks/useZoomEvents.ts new file mode 100644 index 000000000..45fa30636 --- /dev/null +++ b/packages/core/src/renderer/hooks/useZoomEvents.ts @@ -0,0 +1,78 @@ +/* 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 }) => { + 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 + } + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + 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/renderer/index.tsx b/packages/core/src/renderer/index.tsx new file mode 100644 index 000000000..2f1729af0 --- /dev/null +++ b/packages/core/src/renderer/index.tsx @@ -0,0 +1,2 @@ +export * from './renderer' +export { brushUpdater } from './components/brush' diff --git a/packages/core/src/renderer/renderer.tsx b/packages/core/src/renderer/renderer.tsx new file mode 100644 index 000000000..f5c46e91a --- /dev/null +++ b/packages/core/src/renderer/renderer.tsx @@ -0,0 +1,64 @@ +import * as React from 'react' +import type { + TLShape, + TLPage, + TLPageState, + TLSettings, + TLCallbacks, + TLShapeUtils, + TLTheme, + TLBounds, +} from '../types' +import { Canvas } from './components/canvas' +import { useTLTheme } from './hooks/useStyle' +import { TLContext } from './hooks/useTLContext' + +export interface RendererProps + extends Partial, + Partial { + shapeUtils: TLShapeUtils + page: TLPage + pageState: TLPageState + theme?: Partial + hideBounds?: boolean + hideIndicators?: boolean +} + +export function Renderer({ + shapeUtils, + page, + pageState, + theme, + hideIndicators = false, + hideBounds = false, + isDarkMode = false, + isDebugMode = false, + isPenMode = 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/shapes/example-shape.tsx b/packages/core/src/shapes/example-shape.tsx new file mode 100644 index 000000000..fe482d56b --- /dev/null +++ b/packages/core/src/shapes/example-shape.tsx @@ -0,0 +1,92 @@ +import * as React from 'react' +import { + TLShapeUtil, + TLShape, + TLBounds, + TLRenderInfo, + TLTransformInfo, +} from '../types' +import Utils, { Intersect } from '../utils' + +export class ExampleShape extends TLShapeUtil { + type = 'shape-type' + + defaultProps = { + id: 'example', + type: 'shape-type', + parentId: 'page', + childIndex: 0, + name: 'Example Shape', + point: [0, 0], + rotation: 0, + } + + create(props: Partial) { + return { ...this.defaultProps, ...props } + } + + render(shape: TLShape, info: TLRenderInfo): JSX.Element { + return + } + + renderIndicator(shape: TLShape) { + return + } + + shouldRender(prev: TLShape, next: TLShape): boolean { + return true + } + + getBounds(shape: TLShape): TLBounds { + return Utils.getFromCache(this.boundsCache, shape, () => ({ + minX: 0, + minY: 0, + maxX: 0, + maxY: 0, + width: 100, + height: 100, + })) + } + + getRotatedBounds(shape: TLShape) { + return Utils.getBoundsFromPoints( + Utils.getRotatedCorners(this.getBounds(shape), shape.rotation) + ) + } + + getCenter(shape: TLShape): number[] { + return Utils.getBoundsCenter(this.getBounds(shape)) + } + + hitTest(shape: TLShape, point: number[]) { + return Utils.pointInBounds(point, this.getBounds(shape)) + } + + hitTestBounds(shape: TLShape, 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: TLShape, + bounds: TLBounds, + _info: TLTransformInfo + ): TLShape { + return { ...shape, point: [bounds.minX, bounds.minY] } + } + + transformSingle( + shape: TLShape, + bounds: TLBounds, + info: TLTransformInfo + ): TLShape { + return this.transform(shape, bounds, info) + } +} diff --git a/packages/core/src/shapes/example.spec.tsx b/packages/core/src/shapes/example.spec.tsx new file mode 100644 index 000000000..36d5e6f4e --- /dev/null +++ b/packages/core/src/shapes/example.spec.tsx @@ -0,0 +1,7 @@ +import { ExampleShape } from './example-shape' + +describe('example shape', () => { + it('should create an instance', () => { + expect(new ExampleShape()).toBeTruthy() + }) +}) diff --git a/packages/core/src/types.tsx b/packages/core/src/types.tsx new file mode 100644 index 000000000..0f56e8cc2 --- /dev/null +++ b/packages/core/src/types.tsx @@ -0,0 +1,407 @@ +/* --------------------- Primary -------------------- */ + +export interface TLPage { + id: string; + name?: string; + childIndex?: number; + shapes: Record; + bindings: Record; + backgroundColor?: string; +} + +export interface TLPageState { + id: string; + brush?: TLBounds; + pointedId?: string; + hoveredId?: string; + editingId?: string; + editingBindingId?: string; + boundsRotation?: number; + currentParentId?: string; + selectedIds: string[]; + camera: { + point: number[]; + zoom: number; + }; +} + +export interface TLHandle { + id: string; + index: number; + point: number[]; +} + +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 { + isEditing: boolean; + isBinding: boolean; + isDarkMode: boolean; + isCurrentParent: boolean; + ref?: React.RefObject; + onTextChange?: TLCallbacks["onTextChange"]; + onTextBlur?: TLCallbacks["onTextBlur"]; + onTextFocus?: TLCallbacks["onTextFocus"]; + onTextKeyDown?: TLCallbacks["onTextKeyDown"]; + onTextKeyUp?: TLCallbacks["onTextKeyUp"]; +} + +export interface TLTool { + id: string; + name: string; +} + +export interface TLBinding { + id: string; + type: string; + toId: string; + fromId: string; +} + +export interface TLSettings { + isDebugMode: boolean; + isDarkMode: boolean; + isPenMode: boolean; +} + +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; + + abstract type: T["type"]; + + abstract defaultProps: T; + + abstract render(shape: T, info: TLRenderInfo): JSX.Element; + + 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]; + } + + 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 + ): Partial | void { + return; + } + + 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; + isDarkMode: boolean; + isCurrentParent: boolean; +} + +/* -------------------------------------------------- */ +/* Utility Types */ +/* -------------------------------------------------- */ + +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; +}; + +export type RequiredKeys = { + [K in keyof T]-?: Record extends Pick ? never : K; +}[keyof T]; + +export {}; diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts new file mode 100644 index 000000000..1b77fac02 --- /dev/null +++ b/packages/core/src/utils/index.ts @@ -0,0 +1,8 @@ +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..ada941eda --- /dev/null +++ b/packages/core/src/utils/intersect.ts @@ -0,0 +1,835 @@ +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[] + ): TLIntersection[] { + return Intersect.rectangle.ray(point, size, 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 + ): TLIntersection[] { + const { minX, minY, width, height } = bounds + return Intersect.ray.rectangle( + origin, + direction, + [minX, minY], + [width, height] + ) + }, + } + + 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[], + origin: number[], + direction: number[] + ): TLIntersection[] { + const sideIntersections = Utils.getRectangleSides(point, size).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< + TLIntersection[] + >((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< + TLIntersection[] + >((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< + TLIntersection[] + >((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< + TLIntersection[] + >((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< + TLIntersection[] + >((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< + TLIntersection[] + >((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( + _c1: number[], + _rx1: number, + _ry1: number, + _r1: number, + _c2: number[], + _rx2: number, + _ry2: number, + _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..9f4728697 --- /dev/null +++ b/packages/core/src/utils/polyfills.ts @@ -0,0 +1,23 @@ +/* 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) + } +} + +export {} 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..4e8514cbb 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,7 +40,7 @@ export default class Svg { r, r, 0, - getSweep(C, A, B) > 0 ? '1' : '0', + Utils.getSweep(C, A, B) > 0 ? '1' : '0', 0, B[0], B[1], @@ -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..d0a0e0ab5 --- /dev/null +++ b/packages/core/src/utils/utils.ts @@ -0,0 +1,1813 @@ +/* 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 isMobilePkg from 'ismobilejs' +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(a: T, b: DeepPartial): T { + return deepmerge>(a, b, { arrayMerge: (_a, b) => b }) as T + } + + /** + * 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[] + ): [string, number[][]][] { + const tl = point + const tr = vec.add(point, [size[0], 0]) + const br = vec.add(point, size) + const bl = vec.add(point, [0, size[1]]) + + 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] + ) + } + + /* --------------------- 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 isMobile() { + return isMobilePkg().any + } + + // 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): ReturnType { + const args = arguments + const context = this + + if (!inThrottle) { + inThrottle = true + + setTimeout(() => (inThrottle = false), limit) + + lastResult = func.apply(context, args as any) + } + + 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 + +export type DeepPartial = T extends Function + ? T + : T extends object + ? T extends unknown[] + ? DeepPartial[] + : { [P in keyof T]?: DeepPartial } + : T + +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 94% rename from utils/vec.ts rename to packages/core/src/utils/vec.tsx index 68bc9cecc..eeee8a7f6 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 @@ -241,10 +241,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 +292,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)) } @@ -351,7 +342,7 @@ export default class Vec { } static round = (a: number[], d = 5): number[] => { - return a.map((v) => +v.toPrecision(d)) + return a.map(v => +v.toPrecision(d)) } /** @@ -402,11 +393,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 +404,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 +447,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)) } @@ -515,6 +493,8 @@ export default class Vec { const t = i / steps return t * t * t }) - .map((t) => Vec.round([...Vec.lrp(a, b, t), (1 - t) / 2])) + .map(t => Vec.round([...Vec.lrp(a, b, t), (1 - t) / 2])) } } + +export default Vec diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 000000000..5f180a19e --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src"], + "exclude": ["node_modules", "**/*.test.ts", "dist"], + "compilerOptions": { + "jsx": "preserve", + "lib": ["dom", "esnext"], + "module": "esnext", + "outDir": "./dist/types" + } +} diff --git a/packages/tldraw/README.md b/packages/tldraw/README.md new file mode 100644 index 000000000..5cda592dc --- /dev/null +++ b/packages/tldraw/README.md @@ -0,0 +1,142 @@ +# @tldraw/tldraw + +This package contains the [tldraw](https://tldraw.com) editor as a standalone React component. + +## Installation + +```bash +yarn add @tldraw/tldraw --peer +``` + +## 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..f1e02073c --- /dev/null +++ b/packages/tldraw/package.json @@ -0,0 +1,63 @@ +{ + "name": "@tldraw/tldraw", + "version": "0.0.41", + "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": [], + "files": [ + "README.md", + "dist" + ], + "main": "./dist/cjs/index.js", + "types": "./dist/types/index.d.ts", + "scripts": { + "dev": "node scripts/dev", + "build": "yarn clean && node scripts/build && tsc --emitDeclarationOnly --outDir dist/types", + "lint": "eslint src/ --ext .ts,.tsx", + "clean": "rm -rf dist", + "ts-node": "ts-node", + "docs": "typedoc --entryPoints src/index.ts" + }, + "devDependencies": { + "@tldraw/core": "*", + "@types/node": "^15.0.1", + "@types/react": "^17.0.16", + "@types/react-dom": "^17.0.9", + "@typescript-eslint/eslint-plugin": "^4.19.0", + "@typescript-eslint/parser": "^4.19.0", + "esbuild": "^0.11.11", + "eslint": "^7.22.0", + "react": "^17.0.2", + "react-dom": "^17.0.2", + "ts-node": "^9.1.1", + "tslib": "^2.3.0", + "typedoc": "^0.20.35", + "typescript": "^4.3.5" + }, + "peerDependencies": { + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "dependencies": { + "@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": "^0.2.3", + "@tldraw/core": "^0.0.41", + "ismobilejs": "^1.1.1", + "perfect-freehand": "^0.4.10", + "react-hotkeys-hook": "^3.4.0", + "zustand": "^3.5.7" + } +} \ No newline at end of file diff --git a/packages/tldraw/scripts/build.js b/packages/tldraw/scripts/build.js new file mode 100644 index 000000000..00f497bcb --- /dev/null +++ b/packages/tldraw/scripts/build.js @@ -0,0 +1,36 @@ +/* eslint-disable */ +const fs = require('fs') +const esbuild = require('esbuild') + +const name = process.env.npm_package_name || '' + +async function main() { + try { + esbuild.buildSync({ + 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'], + }) + + fs.copyFile('package.json', 'dist/package.json', (err) => { + if (err) throw err + }) + fs.copyFile('README.md', 'dist/README.md', (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..cd9cf80cd --- /dev/null +++ b/packages/tldraw/scripts/dev.js @@ -0,0 +1,33 @@ +/* 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: 'esnext', + jsxFactory: 'React.createElement', + jsxFragment: 'React.Fragment', + tsconfig: './tsconfig.json', + external: ['react', 'react-dom'], + watch: { + onRebuild(error) { + if (error) { + console.log(`× ${name}: An error in prevented the rebuild.`) + return + } + console.log(`✔ ${name}: Rebuilt.`) + }, + }, + }) + + // result.stop(); +} + +main() 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..ac40c0747 --- /dev/null +++ b/packages/tldraw/src/components/context-menu/context-menu.tsx @@ -0,0 +1,372 @@ +import * as React from 'react' +import { Utils } from '@tldraw/core' +import * as RadixContextMenu from '@radix-ui/react-context-menu' +import styled from '../../styles' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state/state-types' +import { Kbd } from '../kbd' +import { + IconWrapper, + breakpoints, + RowButton, + ContextMenuArrow, + ContextMenuDivider, + ContextMenuButton, + ContextMenuSubMenu, + ContextMenuIconButton, + ContextMenuRoot, + MenuContent, +} from '../shared' +import { AlignType, DistributeType, StretchType } from '../../types' +import { + ChevronRightIcon, + AlignBottomIcon, + AlignCenterHorizontallyIcon, + AlignCenterVerticallyIcon, + AlignLeftIcon, + AlignRightIcon, + AlignTopIcon, + SpaceEvenlyHorizontallyIcon, + SpaceEvenlyVerticallyIcon, + StretchHorizontallyIcon, + StretchVerticallyIcon, +} from '@radix-ui/react-icons' + +const has1SelectedIdsSelector = (s: Data) => { + return s.pageState.selectedIds.length > 0 +} +const has2SelectedIdsSelector = (s: Data) => { + return s.pageState.selectedIds.length > 1 +} +const has3SelectedIdsSelector = (s: Data) => { + return s.pageState.selectedIds.length > 2 +} + +const isDebugModeSelector = (s: Data) => { + return s.settings.isDebugMode +} + +const hasGroupSelectedSelector = (s: Data) => { + return s.pageState.selectedIds.some( + (id) => s.page.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 handleCopyAsJson = React.useCallback(() => { + tlstate.copyAsJson() + }, [tlstate]) + + const handleCopyAsSvg = React.useCallback(() => { + tlstate.copyAsSvg() + }, [tlstate]) + + const handleUndo = React.useCallback(() => { + tlstate.undo() + }, [tlstate]) + + const handleRedo = React.useCallback(() => { + tlstate.redo() + }, [tlstate]) + + if (Utils.isMobile()) { + return <>{children} + } + + 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 && ( + + )} + {/* */} + {isDebugMode && ( + + Copy Data + # ⇧ C + + )} + + Copy to SVG + # ⇧ C + + + + Delete + + + + ) : ( + <> + + 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)', + }, + }, + }, +}) + +// 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/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/Redo.svg b/packages/tldraw/src/components/icons/Redo.svg similarity index 100% rename from components/icons/Redo.svg rename to packages/tldraw/src/components/icons/Redo.svg diff --git a/components/icons/Trash.svg b/packages/tldraw/src/components/icons/Trash.svg similarity index 100% rename from components/icons/Trash.svg rename to packages/tldraw/src/components/icons/Trash.svg diff --git a/components/icons/Undo.svg b/packages/tldraw/src/components/icons/Undo.svg similarity index 100% rename from components/icons/Undo.svg rename to packages/tldraw/src/components/icons/Undo.svg 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 ( - + ): JSX.Element { return ( - + ): JSX.Element { return ( - + ): JSX.Element { 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/components/shared.tsx b/packages/tldraw/src/components/shared.tsx similarity index 81% rename from components/shared.tsx rename to packages/tldraw/src/components/shared.tsx index d310028c1..a83670afc 100644 --- a/components/shared.tsx +++ b/packages/tldraw/src/components/shared.tsx @@ -1,12 +1,30 @@ -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' +/* eslint-disable @typescript-eslint/no-explicit-any */ +import * as React from 'react' +import { Tooltip } from './tooltip' +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 { + 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 { Root as RGRoot } from '@radix-ui/react-radio-group' import { CheckIcon, ChevronRightIcon } from '@radix-ui/react-icons' -import { isMobile } from 'utils' +import styled from '../styles' export const breakpoints: any = { '@initial': 'mobile', '@sm': 'small' } @@ -185,28 +203,7 @@ export const RowButton = styled('button', { }, }) -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, { +export const Group = styled(RGRoot, { display: 'flex', }) @@ -321,23 +318,6 @@ export const FloatingContainer = styled('div', { }, }) -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 */ /* -------------------------------------------------- */ @@ -465,9 +445,9 @@ export function DropdownMenuRoot({ children: React.ReactNode }): JSX.Element { return ( - + {children} - + ) } @@ -481,26 +461,22 @@ export function DropdownMenuSubMenu({ children: React.ReactNode }): JSX.Element { return ( - - + + {label} - - + + {children} - - + + ) } -export const DropdownMenuDivider = styled(DropdownMenu.Separator, { +export const DropdownMenuDivider = styled(DMSeparator, { backgroundColor: '$hover', height: 1, marginTop: '$2', @@ -509,7 +485,7 @@ export const DropdownMenuDivider = styled(DropdownMenu.Separator, { marginLeft: '-$2', }) -export const DropdownMenuArrow = styled(DropdownMenu.Arrow, { +export const DropdownMenuArrow = styled(DMArrow, { fill: '$panel', }) @@ -523,14 +499,14 @@ export function DropdownMenuButton({ children: React.ReactNode }): JSX.Element { return ( - {children} - + ) } @@ -546,14 +522,14 @@ export function DropdownMenuIconButton({ disabled = false, }: DropdownMenuIconButtonProps): JSX.Element { return ( - {children} - + ) } @@ -570,11 +546,11 @@ export function DropdownMenuIconTriggerButton({ disabled = false, }: DropdownMenuIconTriggerButtonProps): JSX.Element { return ( - + {children} - + ) } @@ -592,7 +568,7 @@ export function DropdownMenuCheckboxItem({ children, }: MenuCheckboxItemProps): JSX.Element { return ( - {children} - + - - + + ) } @@ -621,9 +597,9 @@ export function ContextMenuRoot({ children: React.ReactNode }): JSX.Element { return ( - + {children} - + ) } @@ -635,28 +611,28 @@ export function ContextMenuSubMenu({ children: React.ReactNode }): JSX.Element { return ( - - + + {label} - - + + {children} - - + + ) } -export const ContextMenuDivider = styled(ContextMenu.Separator, { +export const ContextMenuDivider = styled(CMSeparator, { backgroundColor: '$hover', height: 1, margin: '$2 -$2', }) -export const ContextMenuArrow = styled(ContextMenu.Arrow, { +export const ContextMenuArrow = styled(CMArrow, { fill: '$panel', }) @@ -671,7 +647,7 @@ export function ContextMenuButton({ }): JSX.Element { return ( {children} - + ) } @@ -709,7 +685,7 @@ export function ContextMenuCheckboxItem({ children, }: MenuCheckboxItemProps): JSX.Element { return ( - {children} - + - - + + + ) +} + +export function CircleIcon( + props: Pick, 'stroke' | 'fill'> & { + size: number + } +) { + const { size = 16, ...rest } = props + return ( + + + ) } diff --git a/packages/tldraw/src/components/status-bar.tsx b/packages/tldraw/src/components/status-bar.tsx new file mode 100644 index 000000000..c9a1a3d78 --- /dev/null +++ b/packages/tldraw/src/components/status-bar.tsx @@ -0,0 +1,47 @@ +import * as React from 'react' +import { useTLDrawContext } from '../hooks' +import type { Data } from '../state' +import styled from '../styles' + +const activeToolSelector = (s: Data) => s.appState.activeTool + +export function StatusBar(): JSX.Element | null { + const { useSelector } = useTLDrawContext() + const activeTool = useSelector(activeToolSelector) + + return ( + +
{activeTool}
+ {/*
{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, + fontFamily: '$ui', + fontSize: '$0', + padding: '0 16px', + + variants: { + size: { + small: { + fontSize: '$1', + }, + }, + }, +}) + +const Section = styled('div', { + whiteSpace: 'nowrap', + overflow: 'hidden', +}) 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..fd3911f78 --- /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 { breakpoints, ButtonsRow, IconButton } from '../shared' +import { useTLDrawContext } from '../../hooks' + +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/packages/tldraw/src/components/style-panel/quick-color-select.tsx b/packages/tldraw/src/components/style-panel/quick-color-select.tsx new file mode 100644 index 000000000..23edbd3c9 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/quick-color-select.tsx @@ -0,0 +1,57 @@ +import * as React from 'react' +import * as DropdownMenu from '@radix-ui/react-dropdown-menu' +import { BoxIcon, StyleDropdownItem, StyleDropdownContent } from './shared' +import { DropdownMenuIconTriggerButton } from '../shared' +import { ColorStyle, strokes } from '../../shape' +import { useTheme } from '../../hooks/useTheme' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state' + +const selectColor = (data: Data) => data.appState.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 ( + + + + + + + {Object.keys(strokes[theme]).map((colorStyle: string) => ( + + + + ))} + + + + ) + } +) diff --git a/packages/tldraw/src/components/style-panel/quick-dash-select.tsx b/packages/tldraw/src/components/style-panel/quick-dash-select.tsx new file mode 100644 index 000000000..1a8abdd53 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/quick-dash-select.tsx @@ -0,0 +1,64 @@ +import * as React from 'react' +import * as DropdownMenu from '@radix-ui/react-dropdown-menu' +import { DropdownMenuIconTriggerButton } from '../shared' +import { + DashDrawIcon, + DashDottedIcon, + DashSolidIcon, + DashDashedIcon, + StyleDropdownContent, + StyleDropdownItem, +} from './shared' +import { DashStyle } from '../../shape' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state' + +const dashes = { + [DashStyle.Draw]: , + [DashStyle.Solid]: , + [DashStyle.Dashed]: , + [DashStyle.Dotted]: , +} + +const selectDash = (data: Data) => data.appState.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]} + + + + {Object.keys(DashStyle).map((dashStyle: string) => ( + + {dashes[dashStyle as DashStyle]} + + ))} + + + + ) + } +) 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..809b0bb1a --- /dev/null +++ b/packages/tldraw/src/components/style-panel/quick-fill-select.tsx @@ -0,0 +1,43 @@ +import * as React from 'react' +import * as Checkbox from '@radix-ui/react-checkbox' +import { breakpoints, IconButton, IconWrapper } from '../shared' +import { BoxIcon, IsFilledFillIcon } from './shared' +import { Tooltip } from '../tooltip' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state' + +const isFilledSelector = (data: Data) => data.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/packages/tldraw/src/components/style-panel/quick-size-select.tsx b/packages/tldraw/src/components/style-panel/quick-size-select.tsx new file mode 100644 index 000000000..e1c2d4114 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/quick-size-select.tsx @@ -0,0 +1,57 @@ +import * as React from 'react' +import * as DropdownMenu from '@radix-ui/react-dropdown-menu' +import { DropdownMenuIconTriggerButton, CircleIcon } from '../shared' +import { StyleDropdownContent, StyleDropdownItem } from './shared' +import { SizeStyle } from '../../shape' +import type { Data } from '../../state' +import { useTLDrawContext } from '../../hooks' + +const sizes = { + [SizeStyle.Small]: 6, + [SizeStyle.Medium]: 12, + [SizeStyle.Large]: 22, +} + +const selectSize = (data: Data) => data.appState.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: string) => ( + + + + ))} + + + + ) + } +) 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..39ad79288 --- /dev/null +++ b/packages/tldraw/src/components/style-panel/shapes-functions.tsx @@ -0,0 +1,213 @@ +import * as React from 'react' +import { IconButton, ButtonsRow, breakpoints } from '../shared' +import { Trash } from '../icons' +import { Tooltip } from '../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 '../../state' + +const isAllLockedSelector = (s: Data) => { + const { selectedIds } = s.pageState + return selectedIds.every((id) => s.page.shapes[id].isLocked) +} + +const isAllAspectLockedSelector = (s: Data) => { + const { selectedIds } = s.pageState + return selectedIds.every((id) => s.page.shapes[id].isAspectRatioLocked) +} + +const isAllGroupedSelector = (s: Data) => { + const selectedShapes = s.pageState.selectedIds.map((id) => s.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) => s.pageState.selectedIds.length > 0 + +const hasMultipleSelectionSelector = (s: Data) => + s.pageState.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/components/style-panel/shared.tsx b/packages/tldraw/src/components/style-panel/shared.tsx similarity index 95% rename from components/style-panel/shared.tsx rename to packages/tldraw/src/components/style-panel/shared.tsx index 5e60e082c..ca5fede6a 100644 --- a/components/style-panel/shared.tsx +++ b/packages/tldraw/src/components/style-panel/shared.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 ( - + + s.appState.isStyleOpen + +export function StylePanel(): JSX.Element { + const { tlstate, useSelector } = useTLDrawContext() + const isOpen = useSelector(isStyleOpenSelector) + + return ( + + + + + + + + + {isOpen ? : } + + + + {isOpen && } + + ) +} + +const showKbds = !Utils.isMobile() +const selectedShapesCountSelector = (s: Data) => s.pageState.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 handleCopyAsSvg = React.useCallback(() => { + tlstate.copyAsSvg() + }, [tlstate]) + + return ( + <> + + + + 1} + hasThreeOrMore={selectedShapesCount > 2} + /> + + + Copy + {showKbds && #C} +
+ + Paste + {showKbds && #V} + + + Copy to SVG + {showKbds && ⇧#C} + + + ) +} diff --git a/packages/tldraw/src/components/tldraw.tsx b/packages/tldraw/src/components/tldraw.tsx new file mode 100644 index 000000000..d78bd834a --- /dev/null +++ b/packages/tldraw/src/components/tldraw.tsx @@ -0,0 +1,167 @@ +import * as React from 'react' +import { IdProvider } from '@radix-ui/react-id' +import { Renderer } from '@tldraw/core' +import { tldrawShapeUtils } from '../shape' +import type { TLDrawDocument } from '../types' +import { useKeyboardShortcuts } from '../hooks' +import styled from '../styles' +import { ContextMenu } from './context-menu' +import { StylePanel } from './style-panel' +import { ToolsPanel } from './tools-panel' +import { Data, TLDrawState } from '../state' +import { TLDrawContext } from '../hooks' + +export interface TLDrawProps { + document?: TLDrawDocument + currentPageId?: string + onMount?: (state: TLDrawState) => void + onChange?: TLDrawState['_onChange'] +} + +const hideBoundsSelector = (s: Data) => + s.appState.activeTool !== 'select' || + (s.pageState.selectedIds.length === 1 && + s.pageState.selectedIds.every( + (id) => s.page.shapes[id].handles !== undefined + )) +const pageSelector = (s: Data) => s.page +const pageStateSelector = (s: Data) => s.pageState + +export function TLDraw({ + document, + currentPageId, + onMount, + onChange: _onChange, +}: TLDrawProps) { + const [tlstate] = React.useState(() => new TLDrawState()) + const [context] = React.useState(() => { + return { tlstate, useSelector: tlstate.store } + }) + + useKeyboardShortcuts(tlstate) + + const hideBounds = context.useSelector(hideBoundsSelector) + const page = context.useSelector(pageSelector) + const pageState = context.useSelector(pageStateSelector) + + React.useEffect(() => { + if (!document) return + tlstate.loadDocument(document, _onChange) + }, [document, tlstate]) + + React.useEffect(() => { + if (!currentPageId) return + tlstate.setCurrentPageId(currentPageId) + }, [currentPageId, tlstate]) + + React.useEffect(() => { + onMount?.(tlstate) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []) + + 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..06609ad34 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/back-to-content.tsx @@ -0,0 +1,30 @@ +import * as React from 'react' +import { FloatingContainer, RowButton } from '../shared' +import styled from '../../styles' +import type { Data } from '../../state' +import { useTLDrawContext } from '../../hooks' + +const isEmptyCanvasSelector = (s: Data) => + Object.keys(s.page.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/components/tools-panel/shared.tsx b/packages/tldraw/src/components/tools-panel/shared.tsx similarity index 96% rename from components/tools-panel/shared.tsx rename to packages/tldraw/src/components/tools-panel/shared.tsx index 4161d7def..8ea06d097 100644 --- a/components/tools-panel/shared.tsx +++ b/packages/tldraw/src/components/tools-panel/shared.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 '../tooltip' +import styled from '../../styles' export const ToolButton = styled('button', { position: 'relative', diff --git a/packages/tldraw/src/components/tools-panel/tools-panel.tsx b/packages/tldraw/src/components/tools-panel/tools-panel.tsx new file mode 100644 index 000000000..0f9babd87 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/tools-panel.tsx @@ -0,0 +1,229 @@ +import { + ArrowTopRightIcon, + CircleIcon, + CursorArrowIcon, + LockClosedIcon, + LockOpen1Icon, + Pencil1Icon, + SquareIcon, + TextIcon, +} from '@radix-ui/react-icons' +import * as React from 'react' +import { StatusBar } from '../status-bar' +import { FloatingContainer } from '../shared' +import { PrimaryButton, SecondaryButton } from './shared' +import styled from '../../styles' +import { UndoRedo } from './undo-redo' +import { Zoom } from './zoom' +import { BackToContent } from './back-to-content' +import { TLDrawShapeType } from '../../shape' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state' + +const activeToolSelector = (s: Data) => s.appState.activeTool +const isToolLockedSelector = (s: Data) => s.appState.isToolLocked +const isDebugModeSelector = (s: Data) => s.settings.isDebugMode + +export const ToolsPanel = React.memo( + (): JSX.Element => { + const { tlstate, useSelector } = useTLDrawContext() + + 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 ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {isToolLocked ? : } + + + + + {isDebugMode && } + + ) + } +) + +const ToolsPanelContainer = styled('div', { + position: 'fixed', + bottom: 0, + left: 0, + right: 0, + width: '100%', + minWidth: 0, + maxWidth: '100%', + display: 'grid', + gridTemplateColumns: '1fr auto 1fr', + padding: '0', + alignItems: 'flex-end', + zIndex: 200, + gridGap: '$4', + gridRowGap: '$4', + pointerEvents: 'none', + '& > div > *': { + pointerEvents: 'all', + }, +}) + +const CenterWrap = styled('div', { + gridRow: 1, + gridColumn: 2, + display: 'flex', + width: 'fit-content', + alignItems: 'center', + justifyContent: 'center', + flexDirection: 'column', + gap: 12, +}) + +const LeftWrap = styled('div', { + gridRow: 1, + gridColumn: 1, + display: 'flex', + paddingLeft: '$3', + variants: { + size: { + mobile: { + flexDirection: 'column', + justifyContent: 'flex-end', + alignItems: 'flex-start', + '& > *:nth-of-type(1)': { + marginBottom: '8px', + }, + }, + small: { + flexDirection: 'row', + alignItems: 'flex-end', + justifyContent: 'space-between', + '& > *:nth-of-type(1)': { + marginBottom: '0px', + }, + }, + }, + }, +}) + +const RightWrap = styled('div', { + gridRow: 1, + gridColumn: 3, + display: 'flex', + paddingRight: '$3', + variants: { + size: { + mobile: { + flexDirection: 'column-reverse', + justifyContent: 'flex-end', + alignItems: 'flex-end', + '& > *:nth-of-type(2)': { + marginBottom: '8px', + }, + }, + small: { + flexDirection: 'row', + alignItems: 'flex-end', + justifyContent: 'space-between', + '& > *:nth-of-type(2)': { + marginBottom: '0px', + }, + }, + }, + }, +}) + +const StatusWrap = styled('div', { + gridRow: 2, + gridColumn: '1 / span 3', +}) 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..0f5b89e25 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/undo-redo.tsx @@ -0,0 +1,32 @@ +import * as React from 'react' +import { TertiaryButton, TertiaryButtonsContainer } from './shared' +import { Undo, Redo, Trash } from '../icons' +import { useTLDrawContext } from '../../hooks' + +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..5aabf71d8 --- /dev/null +++ b/packages/tldraw/src/components/tools-panel/zoom.tsx @@ -0,0 +1,41 @@ +import * as React from 'react' +import { ZoomInIcon, ZoomOutIcon } from '@radix-ui/react-icons' +import { TertiaryButton, TertiaryButtonsContainer } from './shared' +import { useTLDrawContext } from '../../hooks' +import type { Data } from '../../state' + +export const Zoom = React.memo( + (): JSX.Element => { + const { tlstate } = useTLDrawContext() + + return ( + + + + + + + + + + ) + } +) + +const zoomSelector = (s: Data) => s.pageState.camera.zoom + +function ZoomCounter() { + const { tlstate, useSelector } = useTLDrawContext() + const zoom = useSelector(zoomSelector) + + return ( + + {Math.round(zoom * 100)}% + + ) +} diff --git a/packages/tldraw/src/components/tooltip.tsx b/packages/tldraw/src/components/tooltip.tsx new file mode 100644 index 000000000..a8bfc48b9 --- /dev/null +++ b/packages/tldraw/src/components/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' + +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', +}) + +const StyledArrow = styled(RadixTooltip.Arrow, { + fill: '$tooltipBg', + margin: '0 8px', +}) diff --git a/packages/tldraw/src/hooks/index.ts b/packages/tldraw/src/hooks/index.ts new file mode 100644 index 000000000..37f885098 --- /dev/null +++ b/packages/tldraw/src/hooks/index.ts @@ -0,0 +1,3 @@ +export * from './useKeyboardShortcuts' +export * from './useTLDrawContext' +export * from './useTheme' diff --git a/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx b/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx new file mode 100644 index 000000000..bd1ffc140 --- /dev/null +++ b/packages/tldraw/src/hooks/useKeyboardShortcuts.tsx @@ -0,0 +1,229 @@ +import * as React from 'react' +import { inputs } from '@tldraw/core' +import { useHotkeys } from 'react-hotkeys-hook' +import { TLDrawShapeType } from '../shape' +import type { TLDrawState } from '../state' + +export function useKeyboardShortcuts(tlstate: TLDrawState) { + 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', (e) => { + tlstate.selectTool('select') + e.preventDefault() + }) + + useHotkeys('d,2', (e) => { + tlstate.selectTool(TLDrawShapeType.Draw) + e.preventDefault() + }) + + useHotkeys('r,3', (e) => { + tlstate.selectTool(TLDrawShapeType.Rectangle) + e.preventDefault() + }) + + useHotkeys('e,4', (e) => { + tlstate.selectTool(TLDrawShapeType.Ellipse) + e.preventDefault() + }) + + useHotkeys('a,5', (e) => { + tlstate.selectTool(TLDrawShapeType.Arrow) + e.preventDefault() + }) + + useHotkeys('t,6', (e) => { + tlstate.selectTool(TLDrawShapeType.Text) + e.preventDefault() + }) + + /* ---------------------- Misc ---------------------- */ + + // Save + + useHotkeys('ctrl+s,command+s', (e) => { + tlstate.save() + e.preventDefault() + }) + + // Undo Redo + + useHotkeys('command+z', (e) => { + tlstate.undo() + e.preventDefault() + }) + + useHotkeys('ctrl+shift-z,command+shift+z', (e) => { + tlstate.redo() + e.preventDefault() + }) + + /* -------------------- Commands -------------------- */ + + // Camera + + useHotkeys('ctrl+=,command+=', (e) => { + tlstate.zoomIn() + e.preventDefault() + }) + + useHotkeys('ctrl+-,command+-', (e) => { + tlstate.zoomOut() + e.preventDefault() + }) + + useHotkeys('shift+1', (e) => { + tlstate.zoomToFit() + e.preventDefault() + }) + + useHotkeys('shift+2', (e) => { + tlstate.zoomToSelection() + e.preventDefault() + }) + + useHotkeys('shift+0', (e) => { + tlstate.zoomToActual() + e.preventDefault() + }) + + // Duplicate + + useHotkeys('ctrl+d,command+d', (e) => { + tlstate.duplicate() + e.preventDefault() + }) + + // Flip + + useHotkeys('shift+h', (e) => { + tlstate.flipHorizontal() + e.preventDefault() + }) + + useHotkeys('shift+v', (e) => { + tlstate.flipVertical() + e.preventDefault() + }) + + // Cancel + + useHotkeys('escape', (e) => { + tlstate.cancel() + e.preventDefault() + }) + + // Delete + + useHotkeys('backspace', (e) => { + tlstate.delete() + e.preventDefault() + }) + + // Select All + + useHotkeys('command+a,ctrl+a', (e) => { + tlstate.selectAll() + e.preventDefault() + }) + + // Nudge + + useHotkeys('up', (e) => { + tlstate.nudge([0, -1], false) + e.preventDefault() + }) + + useHotkeys('right', (e) => { + tlstate.nudge([1, 0], false) + e.preventDefault() + }) + + useHotkeys('down', (e) => { + tlstate.nudge([0, 1], false) + e.preventDefault() + }) + + useHotkeys('left', (e) => { + tlstate.nudge([-1, 0], false) + e.preventDefault() + }) + + useHotkeys('shift+up', (e) => { + tlstate.nudge([0, -1], true) + e.preventDefault() + }) + + useHotkeys('shift+right', (e) => { + tlstate.nudge([1, 0], true) + e.preventDefault() + }) + + useHotkeys('shift+down', (e) => { + tlstate.nudge([0, 1], true) + e.preventDefault() + }) + + useHotkeys('shift+left', (e) => { + tlstate.nudge([-1, 0], true) + e.preventDefault() + }) + + // Copy & Paste + + useHotkeys('command+c,ctrl+c', (e) => { + tlstate.copy() + e.preventDefault() + }) + + useHotkeys('command+v,ctrl+v', (e) => { + tlstate.paste() + e.preventDefault() + }) + + // Move + + useHotkeys('[', (e) => { + tlstate.moveBackward() + e.preventDefault() + }) + + useHotkeys(']', (e) => { + tlstate.moveForward() + e.preventDefault() + }) + + useHotkeys('shift+[', (e) => { + tlstate.moveToBack() + e.preventDefault() + }) + + useHotkeys('shift+]', (e) => { + tlstate.moveToFront() + e.preventDefault() + }) + + useHotkeys('command+shift+backspace', (e) => { + tlstate.reset() + e.preventDefault() + }) +} diff --git a/packages/tldraw/src/hooks/useTLDrawContext.tsx b/packages/tldraw/src/hooks/useTLDrawContext.tsx new file mode 100644 index 000000000..2daba50dc --- /dev/null +++ b/packages/tldraw/src/hooks/useTLDrawContext.tsx @@ -0,0 +1,19 @@ +import * as React from 'react' +import type { Data } from '../state/state-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..373ed96de --- /dev/null +++ b/packages/tldraw/src/hooks/useTheme.ts @@ -0,0 +1,8 @@ +import type { Theme } from '../shape' + +export function useTheme() { + return { + theme: 'light' as Theme, + toggle: () => null, + } +} 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..44fe55198 --- /dev/null +++ b/packages/tldraw/src/shape/index.ts @@ -0,0 +1,3 @@ +export * from './shape-utils' +export * from './shape-types' +export * from './shape-styles' diff --git a/state/shape-styles.ts b/packages/tldraw/src/shape/shape-styles.ts similarity index 55% rename from state/shape-styles.ts rename to packages/tldraw/src/shape/shape-styles.ts index 565cf78e5..186271e2b 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 './shape-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,8 +65,9 @@ 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` } @@ -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-types.ts b/packages/tldraw/src/shape/shape-types.ts new file mode 100644 index 000000000..8e675b9bd --- /dev/null +++ b/packages/tldraw/src/shape/shape-types.ts @@ -0,0 +1,160 @@ +import { TLShape, TLShapeUtil, TLHandle } from '@tldraw/core' + +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', +} + +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 type TLDrawShape = + | RectangleShape + | EllipseShape + | DrawShape + | ArrowShape + | TextShape + +export abstract class TLDrawShapeUtil< + T extends TLDrawShape +> extends TLShapeUtil { + abstract toolType: TLDrawToolType +} + +export type TLDrawShapeUtils = Record< + TLDrawShapeType, + TLDrawShapeUtil +> + +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 +> + +export {} diff --git a/packages/tldraw/src/shape/shape-utils.tsx b/packages/tldraw/src/shape/shape-utils.tsx new file mode 100644 index 000000000..5e09dff7a --- /dev/null +++ b/packages/tldraw/src/shape/shape-utils.tsx @@ -0,0 +1,24 @@ +import { Rectangle, Ellipse, Arrow, Draw, Text } from './shapes' +import { TLDrawShapeType, TLDrawShape, TLDrawShapeUtil, TLDrawShapeUtils } from './shape-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(), +} + +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..8606f1a6a --- /dev/null +++ b/packages/tldraw/src/shape/shapes/arrow/arrow.tsx @@ -0,0 +1,755 @@ +import * as React from 'react' +import { + TLBounds, + Utils, + Vec, + TLTransformInfo, + TLRenderInfo, + Intersect, + TLHandle, + TLPointerInfo, +} from '@tldraw/core' +import getStroke from 'perfect-freehand' +import { defaultStyle, getPerfectDashProps, getShapeStyle } from '../../shape-styles' +import { + ArrowShape, + Decoration, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, + DashStyle, +} from '../../shape-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, { isDarkMode }: TLRenderInfo) => { + const { bend, handles, style } = shape + const { start, end, bend: _bend } = handles + + const isStraightLine = Vec.dist(_bend.point, Vec.round(Vec.med(start.point, end.point))) < 1 + + const isDraw = shape.style.dash === DashStyle.Draw + + const styles = getShapeStyle(style, isDarkMode) + + const { strokeWidth } = styles + + const arrowDist = Vec.dist(start.point, end.point) + + const arrowHeadlength = Math.min(arrowDist / 3, strokeWidth * 8) + + let shaftPath: JSX.Element + let insetStart: number[] + let insetEnd: number[] + + if (isStraightLine) { + const sw = strokeWidth * (isDraw ? 0.618 : 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 + ) + + insetStart = Vec.nudge(start.point, end.point, arrowHeadlength) + insetEnd = Vec.nudge(end.point, start.point, arrowHeadlength) + + // Straight arrow path + shaftPath = ( + <> + + + + ) + } else { + const circle = getCtp(shape) + + const sw = strokeWidth * (isDraw ? 0.618 : 1.618) + + const path = Utils.getFromCache(this.pathCache, shape, () => + isDraw + ? renderCurvedFreehandArrowShaft(shape, circle) + : getArrowArcPath(start, end, circle, bend) + ) + + const arcLength = Utils.getArcLength( + [circle[0], circle[1]], + circle[2], + start.point, + end.point + ) + + const { strokeDasharray, strokeDashoffset } = getPerfectDashProps( + arcLength - 1, + sw, + shape.style.dash, + 2 + ) + + const center = [circle[0], circle[1]] + const radius = circle[2] + const sa = Vec.angle(center, start.point) + const ea = Vec.angle(center, end.point) + const t = arrowHeadlength / Math.abs(arcLength) + + insetStart = Vec.nudgeAtAngle(center, Utils.lerpAngles(sa, ea, t), radius) + insetEnd = Vec.nudgeAtAngle(center, Utils.lerpAngles(ea, sa, t), radius) + + // Curved arrow path + shaftPath = ( + <> + + + + ) + } + + const sw = strokeWidth * 1.618 + + return ( + + {shaftPath} + {shape.decorations?.start === Decoration.Arrow && ( + + )} + {shape.decorations?.end === Decoration.Arrow && ( + + )} + + ) + } + + renderIndicator(shape: ArrowShape) { + const { + handles: { start, end }, + bend, + style, + } = shape + + const circle = getCtp(shape) + + const path = Utils.getFromCache(this.simplePathCache, shape, () => + getArrowArcPath(start, end, getCtp(shape), bend) + ) + const styles = getShapeStyle(style, false) + + const { strokeWidth } = styles + + const arrowDist = Vec.dist(start.point, end.point) + + const arrowHeadlength = Math.min(arrowDist / 3, strokeWidth * 8) + + const arcLength = Utils.getArcLength([circle[0], circle[1]], circle[2], start.point, end.point) + + const center = [circle[0], circle[1]] + const radius = circle[2] + const sa = Vec.angle(center, start.point) + const ea = Vec.angle(center, end.point) + const t = arrowHeadlength / Math.abs(arcLength) + + const insetStart = Vec.nudgeAtAngle(center, Utils.lerpAngles(sa, ea, t), radius) + const insetEnd = Vec.nudgeAtAngle(center, Utils.lerpAngles(ea, sa, t), radius) + + return ( + + + {shape.decorations?.start === Decoration.Arrow && ( + + )} + {shape.decorations?.end === Decoration.Arrow && ( + + )} + + ) + } + + // rotateBy(shape, delta) { + // const { start, end, bend } = shape.handles + // const mp = Vec.med(start.point, end.point) + // start.point = Vec.rotWith(start.point, mp, delta) + // end.point = Vec.rotWith(end.point, mp, delta) + // bend.point = Vec.rotWith(bend.point, mp, delta) + + // this.onHandleChange(shape, shape.handles, { + // delta: [0, 0], + // shiftKey: false, + // }) + + // return this + // } + + // rotateTo(shape, rotation, delta) { + // const { start, end, bend } = shape.handles + // const mp = Vec.med(start.point, end.point) + // start.point = Vec.rotWith(start.point, mp, delta) + // end.point = Vec.rotWith(end.point, mp, delta) + // bend.point = Vec.rotWith(bend.point, mp, delta) + + // this.onHandleChange(shape, shape.handles, { + // delta: [0, 0], + // shiftKey: false, + // }) + + // return this + // } + + 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, binding, target, bounds, expandDistance) { + // const handle = shape.handles[binding.fromHandleId] + + // if (!handle) { + // throw Error('Could not find a handle with the binding id: ' + binding.fromHandleId) + // } + + // const expandedBounds = expandBounds(bounds, expandDistance) + + // const anchor = Vec.sub( + // Vec.add( + // [expandedBounds.minX, expandedBounds.minY], + // Vec.mulV([expandedBounds.width, expandedBounds.height], binding.point) + // ), + // shape.point + // ) + + // let point: number[] + + // if (binding.distance) { + // const origin = Vec.add( + // shape.point, + // shape.handles[binding.fromHandleId === 'start' ? 'end' : 'start'].point + // ) + + // const direction = Vec.uni(Vec.sub(Vec.add(anchor, shape.point), origin)) + + // // TODO: Abstract this part onto individual shape utils + + // switch (target.type) { + // case ShapeType.Text: + // case ShapeType.Rectangle: { + // const intersectBounds = expandBounds(bounds, binding.distance) + + // let hits = Intersect.ray + // .bounds(origin, direction, intersectBounds) + // .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 + // } + + // point = Vec.sub(hits[0], shape.point) + + // break + // } + // case ShapeType.Ellipse: { + // const center = getShapeUtils(target).getCenter(target) + + // point = Vec.nudge( + // Vec.sub( + // Intersect.ray + // .ellipse(origin, direction, center, target.radiusX, target.radiusY, target.rotation) + // .points.sort((a, b) => Vec.dist(a, origin) - Vec.dist(b, origin))[0], + // shape.point + // ), + // origin, + // binding.distance + // ) + // } + // } + // } else { + // point = anchor + // } + + // this.onHandleChange( + // shape, + // { + // [handle.id]: { + // ...shape.handles[handle.id], + // point: Vec.round(point), + // }, + // }, + // { shiftKey: false } + // ) + + // return this + // } + + onHandleChange = ( + shape: ArrowShape, + handles: ArrowShape['handles'], + { 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 + for (const id in handles) { + if ((id === 'start' || id === 'end') && shiftKey) { + const point = handles[id].point + const other = 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) + + nextHandles = { + ...nextHandles, + [id]: { + ...nextHandles[id], + point: Vec.nudgeAtAngle(other.point, newAngle, distance), + }, + } + } + } + + // 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 (Utils.isAngleBetween(angle, angle + Math.PI, angleToBend)) { + nextBend *= -1 + } + } + + nextHandles = { + ...nextHandles, + start: { + ...nextHandles.start, + point: Vec.round(nextHandles.start.point), + }, + end: { + ...nextHandles.end, + point: Vec.round(nextHandles.end.point), + }, + } + + return { + bend: nextBend, + handles: { + ...nextHandles, + bend: { + ...nextHandles.bend, + point: getBendPoint(nextHandles, nextBend), + }, + }, + } + } + + onSessionComplete = (shape: ArrowShape) => { + const bounds = this.getBounds(shape) + const offset = Vec.sub([bounds.minX, bounds.minY], shape.point) + const { start, end, bend } = shape.handles + + return { + point: Vec.round(Vec.add(shape.point, offset)), + handles: { + start: { + ...start, + point: Vec.round(Vec.sub(start.point, offset)), + }, + end: { + ...end, + point: Vec.round(Vec.sub(end.point, offset)), + }, + bend: { + ...bend, + point: Vec.round(Vec.sub(bend.point, offset)), + }, + }, + } + } +} + +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 st = Math.abs(getRandom()) + + const stroke = getStroke( + [...Vec.pointsBetween(start.point, end.point), end.point, end.point, end.point, end.point], + { + size: strokeWidth / 2, + thinning: 0.5 + getRandom() * 0.3, + easing: t => t * t, + end: { taper: 1 }, + start: { taper: 1 + 32 * (st * st * st) }, + 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 st = Math.abs(getRandom()) + + 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], { + size: strokeWidth / 2, + thinning: 0.5 + getRandom() * 0.3, + easing: t => t * t, + end: { + taper: shape.decorations?.end ? 1 : 1 + strokeWidth * 5 * (st * st * st), + }, + start: { + taper: shape.decorations?.start ? 1 : 1 + strokeWidth * 5 * (st * st * st), + }, + simulatePressure: true, + streamline: 0.01, + last: true, + }) + + const path = Utils.getSvgPathFromStroke(stroke) + + return path +} + +function getArrowHeadPath(shape: ArrowShape, point: number[], inset: number[]) { + const { left, right } = getArrowHeadPoints(shape, point, inset) + return ['M', left, 'L', point, right].join(' ') +} + +function getArrowHeadPoints(shape: ArrowShape, point: number[], inset: number[]) { + // Use the shape's random seed to create minor offsets for the angles + const getRandom = Utils.rng(shape.id) + + return { + left: Vec.rotWith(inset, point, Math.PI / 6 + (Math.PI / 12) * getRandom()), + right: Vec.rotWith(inset, point, -Math.PI / 6 + (Math.PI / 12) * getRandom()), + } +} + +function getCtp(shape: ArrowShape) { + const { start, end, bend } = shape.handles + return Utils.circleFromThreePoints(start.point, end.point, bend.point) +} 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..a1c8b67c1 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/draw/draw.tsx @@ -0,0 +1,344 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, TLRenderInfo, Intersect } from '@tldraw/core' +import getStroke, { getStrokePoints } from 'perfect-freehand' +import { defaultStyle, getShapeStyle } from '../../shape-styles' +import { + DrawShape, + DashStyle, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, +} from '../../shape-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: [[0, 0, 0.5]], + rotation: 0, + style: defaultStyle, + } + + shouldRender(prev: DrawShape, next: DrawShape): boolean { + return next.points !== prev.points || next.style !== prev.style + } + + render(shape: DrawShape, { isDarkMode }: TLRenderInfo): JSX.Element { + const { points, style } = shape + + const styles = getShapeStyle(style, isDarkMode) + + const strokeWidth = +styles.strokeWidth + + const shouldFill = + style.isFilled && + points.length > 3 && + Vec.dist(points[0], points[points.length - 1]) < +styles.strokeWidth * 2 + + // For very short lines, draw a point instead of a line + + if (points.length > 0 && points.length < 3) { + const sw = strokeWidth * 0.618 + + return ( + + ) + } + + // 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 = Utils.getFromCache(this.drawPathCache, points, () => + getDrawStrokePath(shape) + ) + + 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 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.sub([bounds.minX, bounds.minY], shape.point) + + return { + points: shape.points.map(([x0, y0, p]) => [x0 - x1, y0 - y1, p]), + 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 * 20 }, + start: { taper: +styles.strokeWidth * 20 }, + }).map((pt) => pt.point) + ) +} + +function getDrawStrokePath(shape: DrawShape) { + 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, { + size: 1 + +styles.strokeWidth * 2, + thinning: 0.85, + end: { taper: +styles.strokeWidth * 10 }, + start: { taper: +styles.strokeWidth * 10 }, + ...options, + }) + + return Utils.getSvgPathFromStroke(stroke) +} + +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..930c24834 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/ellipse/ellipse.tsx @@ -0,0 +1,252 @@ +import * as React from 'react' +import { Utils, TLTransformInfo, TLBounds, Intersect, Vec, TLRenderInfo } from '@tldraw/core' +import { + DashStyle, + EllipseShape, + TLDrawShapeType, + TLDrawShapeUtil, + TLDrawToolType, +} from '../../shape-types' +import { defaultStyle, getPerfectDashProps, getShapeStyle } from '../../shape-styles' +import getStroke from 'perfect-freehand' + +export class Ellipse extends TLDrawShapeUtil { + type = TLDrawShapeType.Ellipse as const + toolType = TLDrawToolType.Bounds + pathCache = new WeakMap([]) + + 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, { isDarkMode, isBinding }: TLRenderInfo) { + const { + radius: [radiusX, radiusY], + style, + } = shape + + const styles = getShapeStyle(style, 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 Utils.getBoundsCenter(this.getBounds(shape)) + } + + 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 + ) + } + + 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/index.ts b/packages/tldraw/src/shape/shapes/index.ts new file mode 100644 index 000000000..a79537ffc --- /dev/null +++ b/packages/tldraw/src/shape/shapes/index.ts @@ -0,0 +1,5 @@ +export * from './draw' +export * from './arrow' +export * from './rectangle' +export * from './ellipse' +export * from './text' 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..50cd5a171 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/rectangle/rectangle.tsx @@ -0,0 +1,316 @@ +import * as React from 'react' +import { + TLBounds, + Utils, + Vec, + TLTransformInfo, + TLRenderInfo, + Intersect, +} from '@tldraw/core' +import getStroke from 'perfect-freehand' +import { + getPerfectDashProps, + defaultStyle, + getShapeStyle, +} from '../../shape-styles' +import { + RectangleShape, + DashStyle, + TLDrawShapeUtil, + TLDrawShapeType, + TLDrawToolType, +} from '../../shape-types' + +export class Rectangle extends TLDrawShapeUtil { + type = TLDrawShapeType.Rectangle as const + toolType = TLDrawToolType.Bounds + + 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, isDarkMode }: TLRenderInfo) { + const { id, size, style } = shape + const styles = getShapeStyle(style, 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)) + } + + 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, + info: TLTransformInfo + ) { + 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(2), ...lines[0], ...lines[0].slice(4)], + { + size: 1 + +styles.strokeWidth, + thinning: 0.6, + easing: t => t * t * t * t, + end: { taper: +styles.strokeWidth * 20 }, + start: { taper: +styles.strokeWidth * 20 }, + simulatePressure: false, + } + ) + + 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..979ff2b52 --- /dev/null +++ b/packages/tldraw/src/shape/shapes/text/text.tsx @@ -0,0 +1,440 @@ +import * as React from 'react' +import { TLBounds, Utils, Vec, TLTransformInfo, TLRenderInfo, Intersect } from '@tldraw/core' +import { defaultStyle, getShapeStyle, getFontSize, getFontStyle } from '../../shape-styles' +import { TextShape, TLDrawShapeUtil, TLDrawShapeType, TLDrawToolType } from '../../shape-types' +import styled from '../../../styles' +import TextAreaUtils from './text-utils' + +function normalizeText(text: string) { + return text.replace(/\r?\n|\r/g, '\n') +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let mdiv: any + +function getMeasurementDiv() { + // A div used for measurement + document.getElementById('__textMeasure')?.remove() + + const mdiv = document.createElement('pre') + mdiv.id = '__textMeasure' + + Object.assign(mdiv.style, { + whiteSpace: 'pre', + width: 'auto', + border: '1px solid red', + padding: '4px', + margin: '0px', + opacity: '0', + position: 'absolute', + top: '-500px', + left: '0px', + zIndex: '9999', + pointerEvents: 'none', + userSelect: 'none', + alignmentBaseline: 'mathematical', + dominantBaseline: 'mathematical', + }) + + mdiv.tabIndex = -1 + + document.body.appendChild(mdiv) + return mdiv +} + +if (typeof window !== 'undefined') { + getMeasurementDiv() +} + +export class Text extends TLDrawShapeUtil { + type = TLDrawShapeType.Text as const + toolType = TLDrawToolType.Text + canChangeAspectRatio = false + canBind = true + isEditableText = true + + pathCache = new WeakMap([]) + + defaultProps = { + id: 'id', + type: TLDrawShapeType.Text as const, + name: 'Text', + parentId: 'page', + childIndex: 1, + point: [0, 0], + rotation: 0, + text: 'hi', + style: defaultStyle, + } + + 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, + isEditing, + isDarkMode, + onTextBlur, + onTextChange, + onTextFocus, + onTextKeyDown, + onTextKeyUp, + }: TLRenderInfo + ): JSX.Element { + const { id, text, style } = shape + const styles = getShapeStyle(style, 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) { + 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.4 + + 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 (!mdiv) { + // We're in SSR + return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 } + } + + mdiv.innerHTML = `${shape.text}‍` + mdiv.style.font = getFontStyle(shape.style) + + const [width, height] = [mdiv.offsetWidth, mdiv.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 }: TLTransformInfo + ): Partial { + const { + isAspectRatioLocked, + rotation = 0, + style: { scale = 1 }, + } = initialShape + + if (!rotation && !isAspectRatioLocked) { + return { + point: [bounds.minX, bounds.minY], + style: { + ...initialShape.style, + scale: scale * Math.abs(scaleX), + }, + } + } + + return { + point: [bounds.minX, bounds.minY], + rotation: + (scaleX < 0 && scaleY >= 0) || (scaleY < 0 && scaleX >= 0) ? -(rotation || 0) : rotation, + style: { + ...initialShape.style, + scale: scale * Math.abs(Math.min(scaleX, scaleY)), + }, + } + } + + transformSingle( + _shape: TextShape, + bounds: TLBounds, + { initialShape, scaleX }: TLTransformInfo + ): Partial { + const { + style: { scale = 1 }, + } = initialShape + + return { + point: Vec.round([bounds.minX, bounds.minY]), + style: { + ...initialShape.style, + scale: scale * 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.length === 0 + } + + // 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, + 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/command/align/align.command.spec.ts b/packages/tldraw/src/state/command/align/align.command.spec.ts new file mode 100644 index 000000000..7101046c9 --- /dev/null +++ b/packages/tldraw/src/state/command/align/align.command.spec.ts @@ -0,0 +1,73 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' +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 left', () => { + 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..3040d4e24 --- /dev/null +++ b/packages/tldraw/src/state/command/align/align.command.ts @@ -0,0 +1,65 @@ +import { Utils } from '@tldraw/core' +import { AlignType } from '../../../types' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function align(data: Data, ids: string[], type: AlignType): Command { + const initialShapes = ids.map((id) => TLDR.getShape(data, id)) + + 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 } + }) + + return { + id: 'align_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + }, + after: { + page: { + 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/create/create.command.spec.ts b/packages/tldraw/src/state/command/create/create.command.spec.ts new file mode 100644 index 000000000..bbff42655 --- /dev/null +++ b/packages/tldraw/src/state/command/create/create.command.spec.ts @@ -0,0 +1,22 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +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..ee48e7069 --- /dev/null +++ b/packages/tldraw/src/state/command/create/create.command.ts @@ -0,0 +1,26 @@ +import type { TLDrawShape } from '../../../shape' +import type { Data, Command } from '../../state-types' + +export function create(data: Data, shapes: TLDrawShape[]): Command { + return { + id: 'toggle_shapes', + before: { + page: { + shapes: Object.fromEntries( + shapes.map((shape) => [shape.id, undefined]) + ), + }, + pageState: { + selectedIds: [...data.pageState.selectedIds], + }, + }, + after: { + page: { + shapes: Object.fromEntries(shapes.map((shape) => [shape.id, shape])), + }, + pageState: { + 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/delete.command.spec.ts b/packages/tldraw/src/state/command/delete/delete.command.spec.ts new file mode 100644 index 000000000..6e000c86e --- /dev/null +++ b/packages/tldraw/src/state/command/delete/delete.command.spec.ts @@ -0,0 +1,44 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +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) + }) +}) 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..3ea84c361 --- /dev/null +++ b/packages/tldraw/src/state/command/delete/delete.command.ts @@ -0,0 +1,25 @@ +import type { Data, Command } from '../../state-types' + +export function deleteShapes(data: Data, ids: string[]): Command { + return { + id: 'toggle_shapes', + before: { + page: { + shapes: Object.fromEntries(ids.map((id) => [id, data.page.shapes[id]])), + }, + pageState: { + selectedIds: [...data.pageState.selectedIds], + hoveredId: undefined + }, + }, + after: { + page: { + shapes: Object.fromEntries(ids.map((id) => [id, undefined])), + }, + pageState: { + selectedIds: [], + hoveredId: undefined + }, + }, + } +} 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..e61dd0083 --- /dev/null +++ b/packages/tldraw/src/state/command/distribute/distribute.command.spec.ts @@ -0,0 +1,30 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' +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..8b5a79ed2 --- /dev/null +++ b/packages/tldraw/src/state/command/distribute/distribute.command.ts @@ -0,0 +1,136 @@ +import { Utils } from '@tldraw/core' +import type { TLDrawShape } from '../../../shape' +import { DistributeType } from '../../../types' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function distribute( + data: Data, + ids: string[], + type: DistributeType +): Command { + const initialShapes = ids.map((id) => data.page.shapes[id]) + 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 } + }) + + return { + id: 'distribute_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + }, + after: { + page: { + 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 }, i) => { + 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 }, i) => { + 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/duplicate.command.spec.ts b/packages/tldraw/src/state/command/duplicate/duplicate.command.spec.ts new file mode 100644 index 000000000..3691552d5 --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate/duplicate.command.spec.ts @@ -0,0 +1,25 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +describe('Duplicate command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.reset() + 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) + }) +}) 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..9db706784 --- /dev/null +++ b/packages/tldraw/src/state/command/duplicate/duplicate.command.ts @@ -0,0 +1,53 @@ +import { Utils, Vec } from '@tldraw/core' +import { TLDR } from '../../tldr' +import type { Data, Command } from '../../state-types' + +export function duplicate(data: Data, ids: string[]): Command { + const delta = Vec.div([16, 16], data.pageState.camera.zoom) + + const after = Object.fromEntries( + TLDR.getSelectedIds(data) + .map((id) => data.page.shapes[id]) + .map((shape) => { + const id = Utils.uniqueId() + return [ + id, + { + ...Utils.deepClone(shape), + id, + point: Vec.round(Vec.add(shape.point, delta)), + }, + ] + }) + ) + + const before = Object.fromEntries( + Object.keys(after).map((id) => [id, undefined]) + ) + + return { + id: 'duplicate', + before: { + page: { + shapes: { + ...before, + }, + }, + pageState: { + ...data.pageState, + selectedIds: ids, + }, + }, + after: { + page: { + shapes: { + ...after, + }, + }, + pageState: { + ...data.pageState, + selectedIds: Object.keys(after), + }, + }, + } +} 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..0feac6ae1 --- /dev/null +++ b/packages/tldraw/src/state/command/flip/flip.command.spec.ts @@ -0,0 +1,54 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' +import type { RectangleShape } from '../../../shape' + +describe('Stretch 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('distributes 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..53c9e65d8 --- /dev/null +++ b/packages/tldraw/src/state/command/flip/flip.command.ts @@ -0,0 +1,71 @@ +import { FlipType } from './../../../types' +import { TLBoundsCorner, Utils } from '@tldraw/core' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function flip(data: Data, ids: string[], type: FlipType): Command { + const initialShapes = ids.map((id) => data.page.shapes[id]) + + 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], + }) + } + } + }) + + return { + id: 'flip_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + }, + after: { + page: { + 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/index.ts b/packages/tldraw/src/state/command/index.ts new file mode 100644 index 000000000..f2d141b21 --- /dev/null +++ b/packages/tldraw/src/state/command/index.ts @@ -0,0 +1,12 @@ +export * from './align' +export * from './create' +export * from './delete' +export * from './distribute' +export * from './duplicate' +export * from './move' +export * from './rotate' +export * from './stretch' +export * from './style' +export * from './toggle' +export * from './translate' +export * from './flip' 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..8cca7025e --- /dev/null +++ b/packages/tldraw/src/state/command/move/move.command.spec.ts @@ -0,0 +1,183 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' +import { Utils } from '@tldraw/core' +import type { Data } from '../../state-types' + +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 Object.values(data.page.shapes) + .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.setSelectedIds(['b']) + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.getState())).toBe('bacd') + tlstate.undo() + expect(getSortedShapeIds(tlstate.getState())).toBe('abcd') + tlstate.redo() + expect(getSortedShapeIds(tlstate.getState())).toBe('bacd') + }) + + describe('to back', () => { + it('moves a shape to back', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b']) + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.getState())).toBe('bacd') + }) + + it('moves two adjacent siblings to back', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b', 'c']) + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.getState())).toBe('bcad') + }) + + it('moves two non-adjacent siblings to back', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b', 'd']) + tlstate.moveToBack() + expect(getSortedShapeIds(tlstate.getState())).toBe('bdac') + }) + }) + + describe('backward', () => { + it('moves a shape backward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['c']) + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.getState())).toBe('acbd') + }) + + it('moves a shape at first index backward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a']) + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.getState())).toBe('abcd') + }) + + it('moves two adjacent siblings backward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['c', 'd']) + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.getState())).toBe('acdb') + }) + + it('moves two non-adjacent siblings backward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b', 'd']) + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.getState())).toBe('badc') + }) + + it('moves two adjacent siblings backward at zero index', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a', 'b']) + tlstate.moveBackward() + expect(getSortedShapeIds(tlstate.getState())).toBe('abcd') + }) + }) + + describe('forward', () => { + it('moves a shape forward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['c']) + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.getState())).toBe('abdc') + }) + + it('moves a shape forward at the top index', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b']) + tlstate.moveForward() + tlstate.moveForward() + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.getState())).toBe('acdb') + }) + + it('moves two adjacent siblings forward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a', 'b']) + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.getState())).toBe('cabd') + }) + + it('moves two non-adjacent siblings forward', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a', 'c']) + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.getState())).toBe('badc') + }) + + it('moves two adjacent siblings forward at top index', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['c', 'd']) + tlstate.moveForward() + expect(getSortedShapeIds(tlstate.getState())).toBe('abcd') + }) + }) + + describe('to front', () => { + it('moves a shape to front', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['b']) + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.getState())).toBe('acdb') + }) + + it('moves two adjacent siblings to front', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a', 'b']) + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.getState())).toBe('cdab') + }) + + it('moves two non-adjacent siblings to front', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['a', 'c']) + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.getState())).toBe('bdac') + }) + + it('moves siblings already at front to front', () => { + tlstate.loadDocument(doc) + tlstate.setSelectedIds(['c', 'd']) + tlstate.moveToFront() + expect(getSortedShapeIds(tlstate.getState())).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..19b9e84ce --- /dev/null +++ b/packages/tldraw/src/state/command/move/move.command.ts @@ -0,0 +1,217 @@ +import type { TLDrawShape } from '../../../shape' +import { MoveType } from '../../../types' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function move(data: Data, ids: string[], type: MoveType): Command { + // Get the unique parent ids for the selected elements + const parentIds = new Set(ids.map((id) => data.page.shapes[id].parentId)) + + let result: { + before: Record> + after: Record> + } = { before: {}, after: {} } + let startIndex: number + let startChildIndex: number + let step: number + + // Collect shapes with common parents into a table under their parent id + Array.from(parentIds.values()).forEach((parentId) => { + const sortedChildren = + parentId === data.page.id + ? Object.values(data.page.shapes).sort( + (a, b) => a.childIndex - b.childIndex + ) + : data.page.shapes[parentId] + .children!.map((childId) => data.page.shapes[childId]) + .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, + }) + ) + + 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), + }) + ) + + 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], + }) + ) + } + + 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], + }) + ) + } + + break + } + } + }) + + return { + id: 'move_shapes', + before: { + page: { + ...data.page, + shapes: result?.before || {}, + }, + }, + after: { + page: { + ...data.page, + shapes: result?.after || {}, + }, + }, + } +} 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..7bc8d4c88 --- /dev/null +++ b/packages/tldraw/src/state/command/rotate/rotate.command.spec.ts @@ -0,0 +1,24 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +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..f8f1a007d --- /dev/null +++ b/packages/tldraw/src/state/command/rotate/rotate.command.ts @@ -0,0 +1,72 @@ +import { Utils, Vec } from '@tldraw/core' +import type { Command, Data } from '../../state-types' +import { TLDR } from '../../tldr' + +const PI2 = Math.PI * 2 + +export function rotate(data: Data, ids: string[], delta = -PI2 / 4): Command { + const initialShapes = ids.map((id) => data.page.shapes[id]) + + 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 prevBoundsRotation = data.pageState.boundsRotation + const nextBoundsRotation = + (PI2 + ((data.pageState.boundsRotation || 0) + delta)) % PI2 + + const { before, after } = TLDR.mutateShapes( + data, + ids, + (shape) => rotations[shape.id] + ) + + return { + id: 'toggle_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + pageState: { + boundsRotation: prevBoundsRotation, + }, + }, + after: { + page: { + shapes: { + ...after, + }, + }, + pageState: { + 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..3ccf181ba --- /dev/null +++ b/packages/tldraw/src/state/command/stretch/stretch.command.spec.ts @@ -0,0 +1,115 @@ +import { StretchType } from '../../../types' +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' +import type { RectangleShape } from '../../../shape' + +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('distributes 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('distributes 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..80ceece23 --- /dev/null +++ b/packages/tldraw/src/state/command/stretch/stretch.command.ts @@ -0,0 +1,69 @@ +import { TLBoundsCorner, Utils } from '@tldraw/core' +import { StretchType } from '../../../types' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function stretch(data: Data, ids: string[], type: StretchType): Command { + const initialShapes = ids.map((id) => data.page.shapes[id]) + + 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], + }) + } + } + }) + + return { + id: 'stretch_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + }, + after: { + page: { + 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..06bd60ccc --- /dev/null +++ b/packages/tldraw/src/state/command/style/style.command.spec.ts @@ -0,0 +1,26 @@ +import { SizeStyle } from '../../../shape' +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +describe('Style command', () => { + const tlstate = new TLDrawState() + tlstate.loadDocument(mockDocument) + tlstate.reset() + tlstate.setSelectedIds(['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) + }) +}) 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..4af64a919 --- /dev/null +++ b/packages/tldraw/src/state/command/style/style.command.ts @@ -0,0 +1,37 @@ +import type { ShapeStyles } from '../../../shape' +import type { Command, Data } from '../../state-types' +import { TLDR } from '../../tldr' + +export function style( + data: Data, + ids: string[], + changes: Partial +): Command { + const { before, after } = TLDR.mutateShapes(data, ids, (shape) => { + return { style: { ...shape.style, ...changes } } + }) + + return { + id: 'style_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + appState: { + currentStyle: { ...data.appState.currentStyle }, + }, + }, + after: { + page: { + shapes: { + ...after, + }, + }, + appState: { + currentStyle: { ...data.appState.currentStyle, ...changes }, + }, + }, + } +} 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..ff7ff4265 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle/toggle.command.spec.ts @@ -0,0 +1,59 @@ +import type { RectangleShape } from './../../../shape/shape-types' +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +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.setSelectedIds(['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..191baca23 --- /dev/null +++ b/packages/tldraw/src/state/command/toggle/toggle.command.ts @@ -0,0 +1,38 @@ +import type { TLDrawShape } from '../../../shape' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function toggle( + data: Data, + ids: string[], + prop: keyof TLDrawShape +): Command { + const initialShapes = ids.map((id) => data.page.shapes[id]) + const isAllToggled = initialShapes.every((shape) => shape[prop]) + + const { before, after } = TLDR.mutateShapes( + data, + TLDR.getSelectedIds(data), + () => ({ + [prop]: !isAllToggled, + }) + ) + + return { + id: 'toggle_shapes', + before: { + page: { + shapes: { + ...before, + }, + }, + }, + after: { + page: { + 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..18556bc2b --- /dev/null +++ b/packages/tldraw/src/state/command/translate/translate.command.spec.ts @@ -0,0 +1,29 @@ +import { TLDrawState } from '../../tlstate' +import { mockDocument } from '../../test-helpers' + +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]) + }) +}) 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..1666e9137 --- /dev/null +++ b/packages/tldraw/src/state/command/translate/translate.command.ts @@ -0,0 +1,29 @@ +import { Vec } from '@tldraw/core' +import type { Data, Command } from '../../state-types' +import { TLDR } from '../../tldr' + +export function translate(data: Data, ids: string[], delta: number[]): Command { + const { before, after } = TLDR.mutateShapes(data, ids, (shape) => ({ + point: Vec.round(Vec.add(shape.point, delta)), + })) + + return { + id: 'translate_shapes', + before: { + page: { + ...data.page, + shapes: { + ...before, + }, + }, + }, + after: { + page: { + ...data.page, + shapes: { + ...after, + }, + }, + }, + } +} diff --git a/packages/tldraw/src/state/index.ts b/packages/tldraw/src/state/index.ts new file mode 100644 index 000000000..152e084ba --- /dev/null +++ b/packages/tldraw/src/state/index.ts @@ -0,0 +1,2 @@ +export * from './tlstate' +export * from './state-types' diff --git a/packages/tldraw/src/state/notes.md b/packages/tldraw/src/state/notes.md new file mode 100644 index 000000000..d7ce1ecbb --- /dev/null +++ b/packages/tldraw/src/state/notes.md @@ -0,0 +1,35 @@ +# Notes + +- [ ] Remap style panel +- [ ] Remap zoom panel +- [ ] Remap undo / redo panel +- [ ] Remap tool panel +- [ ] Migrate commands +- [ ] 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`. 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/brush/brush.session.spec.ts b/packages/tldraw/src/state/session/sessions/brush/brush.session.spec.ts new file mode 100644 index 000000000..42d5e3f8d --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/brush/brush.session.spec.ts @@ -0,0 +1,50 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' + +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.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..e96ba0a15 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/brush/brush.session.ts @@ -0,0 +1,124 @@ +import { brushUpdater, Utils, Vec } from '@tldraw/core' +import type { Session } from '../../../state-types' +import { getShapeUtils } from '../../../../shape' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class BrushSession implements Session { + id = 'brush' + origin: number[] + snapshot: BrushSnapshot + + constructor(data: Data, point: number[]) { + this.origin = Vec.round(point) + this.snapshot = getBrushSnapshot(data) + } + + start = (data: Data) => { + return data + } + + update = (data: Data, point: number[], containMode = false) => { + const { snapshot, origin } = this + + // 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) + + snapshot.shapesToTest.forEach(({ id, util, selectId }) => { + if (selectedIds.has(id)) return + + const shape = data.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 === data.pageState.selectedIds.length && + data.pageState.selectedIds.every((id) => selectedIds.has(id)) + ) { + return data + } + + return { + ...data, + pageState: { + ...data.pageState, + selectedIds: Array.from(selectedIds.values()), + }, + } + } + + cancel(data: Data) { + return { + ...data, + pageState: { + ...data.pageState, + selectedIds: this.snapshot.selectedIds, + }, + } + } + + complete(data: Data) { + return { + ...data, + pageState: { + ...data.pageState, + selectedIds: [...data.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 selectedIds = [...data.pageState.selectedIds] + + const shapesToTest = TLDR.getShapes(data) + .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), + })) + + 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..f777d1c5b --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/draw/draw.session.spec.ts @@ -0,0 +1,45 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' +import { ColorStyle, DashStyle, SizeStyle, TLDrawShapeType } from '../../../../shape' + +describe('Transform 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() + }) + + 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/state/sessions/draw-session.ts b/packages/tldraw/src/state/session/sessions/draw/draw.session.ts similarity index 54% rename from state/sessions/draw-session.ts rename to packages/tldraw/src/state/session/sessions/draw/draw.session.ts index fd3ee97c1..b4201f255 100644 --- a/state/sessions/draw-session.ts +++ b/packages/tldraw/src/state/session/sessions/draw/draw.session.ts @@ -1,45 +1,40 @@ -import { Data, DrawShape } from 'types' -import BaseSession from './base-session' -import { getShapeUtils } from 'state/shape-utils' -import { deepClone, getBoundsFromPoints } from 'utils' -import tld from 'utils/tld' -import vec from 'utils/vec' -import commands from 'state/commands' +import { Utils, Vec } from '@tldraw/core' +import type { DrawShape } from '../../../../shape/shape-types' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' -export default class DrawSession extends BaseSession { +export class DrawSession implements Session { + id = 'draw' origin: number[] previous: number[] last: number[] points: number[][] snapshot: DrawSnapshot - isLocked: boolean - lockedDirection: 'horizontal' | 'vertical' + isLocked?: boolean + lockedDirection?: 'horizontal' | 'vertical' constructor(data: Data, id: string, point: number[]) { - super(data) 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 = [[0, 0, 0.5]] - - const shape = tld.getPage(data).shapes[id] - - getShapeUtils(shape).translateTo(shape, point) - - tld.updateParents(data, [shape.id]) } + start = (data: Data) => data + update = ( data: Data, point: number[], pressure: number, isLocked = false - ): void => { + ) => { const { snapshot } = this // Drawing while holding shift will "lock" the pen to either the @@ -48,7 +43,7 @@ export default class DrawSession extends BaseSession { // the pen to the axis. if (isLocked) { if (!this.isLocked && this.points.length > 1) { - const bounds = getBoundsFromPoints(this.points) + const bounds = Utils.getBoundsFromPoints(this.points) if (bounds.width > 8 || bounds.height > 8) { this.isLocked = true const returning = [...this.previous] @@ -64,7 +59,7 @@ export default class DrawSession extends BaseSession { } this.previous = returning - this.points.push(vec.sub(returning, this.origin)) + this.points.push(Vec.sub(returning, this.origin)) } } } else if (this.isLocked) { @@ -80,19 +75,19 @@ export default class DrawSession extends BaseSession { } // Low pass the current input point against the previous one - const nextPrev = vec.med(this.previous, point) + const nextPrev = Vec.med(this.previous, point) this.previous = nextPrev // Don't add duplicate points. It's important to test against the // adjusted (low-passed) point rather than the input point. - const newPoint = vec.round([ - ...vec.sub(this.previous, this.origin), + const newPoint = Vec.round([ + ...Vec.sub(this.previous, this.origin), pressure, ]) - if (vec.isEqual(this.last, newPoint)) return + if (Vec.isEqual(this.last, newPoint)) return data this.last = newPoint @@ -100,49 +95,81 @@ export default class DrawSession extends BaseSession { // We draw a dot when the number of points is 1 or 2, so this guard // prevents a "flash" of a dot when a user begins drawing a line. - if (this.points.length <= 2) return + if (this.points.length <= 2) return data - // Update the points and update the shape's parents. - const shape = tld.getShape(data, snapshot.id) as DrawShape - - // Note: Normally we would want to spread the points to create a new - // array, however we create the new array in hacks/fastDrawUpdate. - getShapeUtils(shape).setProperty(shape, 'points', this.points) - - tld.updateParents(data, [shape.id]) - } - - cancel = (data: Data): void => { - const { snapshot } = this - const shape = tld.getShape(data, snapshot.id) as DrawShape - getShapeUtils(shape).translateTo(shape, snapshot.point) - getShapeUtils(shape).setProperty(shape, 'points', snapshot.points) - tld.updateParents(data, [shape.id]) - } - - complete = (data: Data): void => { - const { snapshot } = this - const page = tld.getPage(data) - const shape = page.shapes[snapshot.id] as DrawShape - - if (vec.dist(this.points[0], this.points[this.points.length - 1]) < 8) { - this.points.push(this.points[0]) + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [snapshot.id]: { + ...data.page.shapes[snapshot.id], + points: [...this.points], + }, + }, + }, + pageState: { + ...data.pageState, + selectedIds: [snapshot.id], + }, } + } - getShapeUtils(shape) - .setProperty(shape, 'points', this.points) - .onSessionComplete(shape) + cancel = (data: Data): Data => { + const { snapshot } = this + return { + ...data, + page: { + ...data.page, + // @ts-ignore + shapes: { + ...data.page.shapes, + [snapshot.id]: undefined, + }, + }, + pageState: { + ...data.pageState, + selectedIds: [], + }, + } + } - tld.updateParents(data, [shape.id]) - - commands.draw(data, this.snapshot.id) + complete = (data: Data) => { + const { snapshot } = this + return { + id: 'create_draw', + before: { + page: { + shapes: { + [snapshot.id]: undefined, + }, + }, + pageState: { + selectedIds: [], + }, + }, + after: { + page: { + shapes: { + [snapshot.id]: TLDR.onSessionComplete( + data, + data.page.shapes[snapshot.id] + ), + }, + }, + pageState: { + selectedIds: [], + }, + }, + } } } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export function getDrawSnapshot(data: Data, shapeId: string) { - const page = tld.getPage(data) - const { points, point } = deepClone(page.shapes[shapeId]) as DrawShape + const { page } = data + const { points, point } = Utils.deepClone(page.shapes[shapeId]) as DrawShape return { id: shapeId, 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..099c27ce0 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/handle/handle.session.spec.ts @@ -0,0 +1,41 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' +import { TLDR } from '../../../tldr' +import type { TLDrawShape } from '../../../../shape' + +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() + .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..4176a402d --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/handle/handle.session.ts @@ -0,0 +1,117 @@ +import { Vec } from '@tldraw/core' +import type { TLDrawShape } from '../../../../shape' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class HandleSession implements Session { + id = 'transform_single' + commandId: string + delta = [0, 0] + origin: number[] + shiftKey = false + initialShape: TLDrawShape + handleId: string + + constructor( + data: Data, + handleId: string, + point: number[], + commandId = 'move_handle' + ) { + const shapeId = data.pageState.selectedIds[0] + this.origin = point + this.handleId = handleId + this.initialShape = TLDR.getShape(data, shapeId) + this.commandId = commandId + } + + start = (data: Data) => data + + update = ( + data: Data, + point: number[], + shiftKey: boolean, + altKey: boolean, + metaKey: boolean + ): Data => { + const { initialShape, origin } = this + + const shape = TLDR.getShape(data, initialShape.id) + + TLDR.assertShapeHasProperty(shape, 'handles') + + this.shiftKey = shiftKey + + const delta = Vec.vec(origin, point) + + const handles = initialShape.handles! + + const handleId = this.handleId as keyof typeof handles + + const change = TLDR.getShapeUtils(shape).onHandleChange( + shape, + { + [handleId]: { + ...shape.handles[handleId], + point: Vec.round(Vec.add(handles[handleId].point, delta)), // Vec.rot(delta, shape.rotation)), + }, + }, + { delta, shiftKey, altKey, metaKey } + ) + + if (!change) return data + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [shape.id]: { + ...shape, + ...change, + }, + }, + }, + } + } + + cancel = (data: Data) => { + const { initialShape } = this + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [initialShape.id]: initialShape, + }, + }, + } + } + + complete(data: Data) { + return { + id: this.commandId, + before: { + page: { + shapes: { + [this.initialShape.id]: this.initialShape, + }, + }, + }, + after: { + page: { + shapes: { + [this.initialShape.id]: TLDR.onSessionComplete( + data, + data.page.shapes[this.initialShape.id] + ), + }, + }, + }, + } + } +} 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..2390891e9 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/index.ts @@ -0,0 +1,8 @@ +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' 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..cebdfa5e0 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.spec.ts @@ -0,0 +1,56 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' + +describe('Brush 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() + + 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..3f5830f20 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/rotate/rotate.session.ts @@ -0,0 +1,188 @@ +import { Utils, Vec } from '@tldraw/core' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +const PI2 = Math.PI * 2 + +export class RotateSession implements Session { + id = 'rotate' + delta = [0, 0] + origin: number[] + snapshot: RotateSnapshot + prev = 0 + + constructor(data: Data, point: number[]) { + this.origin = point + this.snapshot = getRotateSnapshot(data) + } + + start = (data: Data) => data + + update = (data: Data, point: number[], isLocked = false): Data => { + const { commonBoundsCenter, initialShapes } = this.snapshot + + const next = { + ...data, + page: { + ...data.page, + }, + pageState: { + ...data.pageState, + }, + } + + const { page, pageState } = next + + 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 + + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + initialShapes.map(({ 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 + ) + + return [ + id, + { + ...next.page.shapes[id], + ...TLDR.mutate(data, shape, { + point: nextPoint, + rotation: (PI2 + nextRotation) % PI2, + }), + }, + ] + }) + ), + } + + return next + } + + cancel = (data: Data) => { + const { initialShapes } = this.snapshot + + for (const { id, shape } of initialShapes) { + data.page.shapes[id] = { ...shape } + } + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + ...Object.fromEntries( + initialShapes.map(({ id, shape }) => [ + id, + TLDR.onSessionComplete(data, shape), + ]) + ), + }, + }, + } + } + + complete(data: Data) { + const { hasUnlockedShapes, initialShapes } = this.snapshot + + if (!hasUnlockedShapes) return data + + return { + id: 'rotate', + before: { + page: { + shapes: Object.fromEntries( + initialShapes.map( + ({ shape: { id, point, rotation = undefined } }) => { + return [id, { point, rotation }] + } + ) + ), + }, + }, + after: { + page: { + shapes: Object.fromEntries( + this.snapshot.initialShapes.map(({ shape }) => { + const { point, rotation } = data.page.shapes[shape.id] + return [shape.id, { point, rotation }] + }) + ), + }, + }, + } + } +} + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function getRotateSnapshot(data: Data) { + const initialShapes = TLDR.getSelectedBranchSnapshot(data) + + 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: data.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..b4832bcc4 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/text/text.session.spec.ts @@ -0,0 +1,44 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' +import { TLDR } from '../../../tldr' +import { TextShape, TLDrawShape, TLDrawShapeType } from '../../../../shape' + +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() + .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() + .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..3c9ad443b --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/text/text.session.ts @@ -0,0 +1,106 @@ +import type { TextShape } from '../../../../shape' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class TextSession implements Session { + id = 'text' + initialShape: TextShape + + constructor(data: Data, id?: string) { + this.initialShape = TLDR.getShape(data, id || TLDR.getSelectedIds(data)[0]) + } + + start = (data: Data) => { + return { + ...data, + pageState: { + ...data.pageState, + editingId: this.initialShape.id, + }, + } + } + + update = (data: Data, text: string): Data => { + const { + initialShape: { id }, + } = this + + let nextShape: TextShape = { + ...(data.page.shapes[id] as TextShape), + text, + } + + nextShape = { + ...nextShape, + ...TLDR.getShapeUtils(nextShape).onStyleChange(nextShape), + } as TextShape + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [id]: nextShape, + }, + }, + } + } + + cancel = (data: Data) => { + const { + initialShape: { id }, + } = this + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [id]: TLDR.onSessionComplete(data, data.page.shapes[id]), + }, + }, + pageState: { + ...data.pageState, + editingId: undefined, + }, + } + } + + complete(data: Data) { + const { initialShape } = this + + const shape = data.page.shapes[initialShape.id] as TextShape + + if (shape.text === initialShape.text) return data + + return { + id: 'text', + before: { + page: { + shapes: { + [initialShape.id]: initialShape, + }, + }, + pageState: { + editingId: undefined, + }, + }, + after: { + page: { + shapes: { + [initialShape.id]: TLDR.onSessionComplete( + data, + data.page.shapes[initialShape.id] + ), + }, + }, + pageState: { + editingId: undefined, + }, + }, + } + } +} 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..c4fe99c8c --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.spec.ts @@ -0,0 +1,29 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' +import { TLBoundsCorner } from '@tldraw/core' + +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() + .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..29b700b5a --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform-single/transform-single.session.ts @@ -0,0 +1,135 @@ +import { TLBoundsCorner, TLBoundsEdge, Utils, Vec } from '@tldraw/core' +import type { TLDrawShape } from '../../../../shape' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class TransformSingleSession implements Session { + id = 'transform_single' + 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 = (data: Data) => data + + update = (data: Data, point: number[], isAspectRatioLocked = false): Data => { + const { transformType } = this + + const { initialShapeBounds, initialShape, id } = this.snapshot + + const shape = data.page.shapes[id] + + const utils = TLDR.getShapeUtils(shape) + + const newBounds = Utils.getTransformedBoundingBox( + initialShapeBounds, + transformType, + Vec.sub(point, this.origin), + shape.rotation, + isAspectRatioLocked || + shape.isAspectRatioLocked || + utils.isAspectRatioLocked + ) + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [shape.id]: { + ...initialShape, + ...TLDR.getShapeUtils(shape).transformSingle(shape, newBounds, { + initialShape, + type: this.transformType, + scaleX: newBounds.scaleX, + scaleY: newBounds.scaleY, + transformOrigin: [0.5, 0.5], + }), + } as TLDrawShape, + }, + }, + } + } + + cancel = (data: Data) => { + const { id, initialShape } = this.snapshot + data.page.shapes[id] = initialShape + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [id]: initialShape, + }, + }, + } + } + + complete(data: Data) { + if (!this.snapshot.hasUnlockedShape) return data + + return { + id: this.commandId, + before: { + page: { + shapes: { + [this.snapshot.id]: this.snapshot.initialShape, + }, + }, + }, + after: { + page: { + shapes: { + [this.snapshot.id]: TLDR.onSessionComplete( + data, + data.page.shapes[this.snapshot.id] + ), + }, + }, + }, + } + } +} + +export function getTransformSingleSnapshot( + data: Data, + transformType: TLBoundsEdge | TLBoundsCorner +) { + const shape = data.page.shapes[data.pageState.selectedIds[0]] + + 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< + typeof getTransformSingleSnapshot +> 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..98a5f12ef --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform/transform.session.spec.ts @@ -0,0 +1,186 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' +import { TLBoundsCorner, Utils } from '@tldraw/core' +import { TLDR } from '../../../tldr' + +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(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 + }) +}) 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..645f58673 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/transform/transform.session.ts @@ -0,0 +1,200 @@ +import { TLBoundsCorner, TLBoundsEdge, Utils, Vec } from '@tldraw/core' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class TransformSession implements Session { + id = 'transform' + 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 = (data: Data) => data + + update = ( + data: Data, + point: number[], + isAspectRatioLocked = false, + _altKey = false + ): Data => { + const { + transformType, + snapshot: { shapeBounds, initialBounds, isAllAspectRatioLocked }, + } = this + + const next = { + ...data, + page: { + ...data.page, + }, + } + + const { shapes } = next.page + + const newBoundingBox = Utils.getTransformedBoundingBox( + initialBounds, + transformType, + Vec.vec(this.origin, point), + data.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 + + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + Object.entries(shapeBounds).map( + ([id, { initialShape, initialShapeBounds, transformOrigin }]) => { + const newShapeBounds = Utils.getRelativeTransformedBoundingBox( + newBoundingBox, + initialBounds, + initialShapeBounds, + this.scaleX < 0, + this.scaleY < 0 + ) + + const shape = shapes[id] + + return [ + id, + { + ...initialShape, + ...TLDR.transform(next, shape, newShapeBounds, { + type: this.transformType, + initialShape, + scaleX: this.scaleX, + scaleY: this.scaleY, + transformOrigin, + }), + }, + ] + } + ) + ), + } + + return next + } + + cancel = (data: Data) => { + const { shapeBounds } = this.snapshot + + return { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + ...Object.fromEntries( + Object.entries(shapeBounds).map(([id, { initialShape }]) => [ + id, + initialShape, + ]) + ), + }, + }, + } + } + + complete(data: Data) { + const { hasUnlockedShapes, shapeBounds } = this.snapshot + + if (!hasUnlockedShapes) return data + + return { + id: 'transform', + before: { + page: { + shapes: Object.fromEntries( + Object.entries(shapeBounds).map(([id, { initialShape }]) => [ + id, + initialShape, + ]) + ), + }, + }, + after: { + page: { + shapes: Object.fromEntries( + this.snapshot.initialShapes.map((shape) => [ + shape.id, + TLDR.onSessionComplete(data, data.page.shapes[shape.id]), + ]) + ), + }, + }, + } + } +} + +export function getTransformSnapshot( + data: Data, + transformType: TLBoundsEdge | TLBoundsCorner +) { + const initialShapes = TLDR.getSelectedBranchSnapshot(data) + + 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: Object.fromEntries( + 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 [ + 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..fb3440bda --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/translate/translate.session.spec.ts @@ -0,0 +1,135 @@ +import { TLDrawState } from '../../../tlstate' +import { mockDocument } from '../../../test-helpers' + +describe('Brush 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.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 + .loadDocument(mockDocument) + .select('rect1', 'rect2') + .startTranslateSession([10, 10]) + .updateTranslateSession([20, 20], false, true) + .updateTranslateSession([30, 30]) + .completeSession() + + // Original position + delta + expect(tlstate.getShape('rect1').point).toStrictEqual([30, 30]) + expect(tlstate.getShape('rect2').point).toStrictEqual([130, 130]) + + expect(Object.keys(tlstate.getPage().shapes).length).toBe(3) + }) + + // it('clones a shape with a parent shape', () => { + // tlstate.loadDocument(mockDocument) + // // TODO + // }) + + // it('clones a shape with children', () => { + // tlstate.loadDocument(mockDocument) + // // TODO + // }) +}) 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..f639b3858 --- /dev/null +++ b/packages/tldraw/src/state/session/sessions/translate/translate.session.ts @@ -0,0 +1,273 @@ +import { Utils, Vec } from '@tldraw/core' +import type { TLDrawShape } from '../../../../shape' +import type { Session } from '../../../state-types' +import type { Data } from '../../../state-types' +import { TLDR } from '../../../tldr' + +export class TranslateSession implements Session { + id = 'translate' + 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) => { + return data + } + + update = ( + data: Data, + point: number[], + isAligned = false, + isCloning = false + ) => { + const { clones, initialShapes } = this.snapshot + + const next = { + ...data, + page: { ...data.page }, + shapes: { ...data.page.shapes }, + pageState: { ...data.pageState }, + } + + 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 + + // Move original shapes back to start + + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + initialShapes.map((shape) => [ + shape.id, + { ...next.page.shapes[shape.id], point: shape.point }, + ]) + ), + } + + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + clones.map((clone) => [ + clone.id, + { ...clone, point: Vec.round(Vec.add(clone.point, delta)) }, + ]) + ), + } + + next.pageState.selectedIds = clones.map((c) => c.id) + } + + // Either way, move the clones + + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + clones.map((clone) => [ + clone.id, + { + ...clone, + point: Vec.round( + Vec.add(next.page.shapes[clone.id].point, trueDelta) + ), + }, + ]) + ), + } + + return next + } + + // If not cloning... + + // Cloning -> Not Cloning + if (this.isCloning) { + this.isCloning = false + + // Delete the clones + clones.forEach((clone) => delete next.page.shapes[clone.id]) + + // Move the original shapes back to the cursor position + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + initialShapes.map((shape) => [ + shape.id, + { + ...next.page.shapes[shape.id], + point: Vec.round(Vec.add(shape.point, delta)), + }, + ]) + ), + } + + // Set selected ids + next.pageState.selectedIds = initialShapes.map((c) => c.id) + } + + // Move the shapes by the delta + next.page.shapes = { + ...next.page.shapes, + ...Object.fromEntries( + initialShapes.map((shape) => [ + shape.id, + { + ...next.page.shapes[shape.id], + point: Vec.round( + Vec.add(next.page.shapes[shape.id].point, trueDelta) + ), + }, + ]) + ), + } + + return next + } + + cancel = (data: Data): Data => { + return { + ...data, + page: { + ...data.page, + // @ts-ignore - We need to set deleted shapes to undefined in order to correctly deep merge them away. + shapes: { + ...data.page.shapes, + ...Object.fromEntries( + this.snapshot.clones.map((clone) => [clone.id, undefined]) + ), + ...Object.fromEntries( + this.snapshot.initialShapes.map((shape) => [ + shape.id, + { ...data.page.shapes[shape.id], point: shape.point }, + ]) + ), + }, + }, + pageState: { + ...data.pageState, + selectedIds: this.snapshot.selectedIds, + }, + } + } + + complete(data: Data) { + return { + id: 'translate', + before: { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + ...Object.fromEntries( + this.snapshot.clones.map((clone) => [clone.id, undefined]) + ), + ...Object.fromEntries( + this.snapshot.initialShapes.map((shape) => [ + shape.id, + { point: shape.point }, + ]) + ), + }, + }, + pageState: { + ...data.pageState, + selectedIds: this.snapshot.selectedIds, + }, + }, + after: { + ...data, + page: { + ...data.page, + shapes: { + ...data.page.shapes, + ...Object.fromEntries( + this.snapshot.clones.map((clone) => [ + clone.id, + data.page.shapes[clone.id], + ]) + ), + ...Object.fromEntries( + this.snapshot.initialShapes.map((shape) => [ + shape.id, + { point: data.page.shapes[shape.id].point }, + ]) + ), + }, + }, + pageState: { + ...data.pageState, + selectedIds: [...data.pageState.selectedIds], + }, + }, + } + } +} + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +export function getTranslateSnapshot(data: Data) { + const selectedShapes = TLDR.getSelectedShapeSnapshot(data) + + const hasUnlockedShapes = selectedShapes.length > 0 + + const initialParents = Array.from( + new Set(selectedShapes.map((s) => s.parentId)).values() + ) + .filter((id) => id !== data.page.id) + .map((id) => { + const shape = TLDR.getShape(data, id) + return { + id, + children: shape.children, + } + }) + + return { + selectedIds: TLDR.getSelectedIds(data), + hasUnlockedShapes, + initialParents, + initialShapes: selectedShapes.map(({ id, point, parentId }) => ({ + id, + point, + parentId, + })), + clones: selectedShapes + .filter((shape) => shape.children === undefined) + .flatMap((shape) => { + const clone: TLDrawShape = { + ...shape, + id: Utils.uniqueId(), + parentId: shape.parentId, + childIndex: TLDR.getChildIndexAbove(data, shape.id), + } + + return clone + }), + } +} + +export type TranslateSnapshot = ReturnType diff --git a/packages/tldraw/src/state/state-types.ts b/packages/tldraw/src/state/state-types.ts new file mode 100644 index 000000000..7a8e37be5 --- /dev/null +++ b/packages/tldraw/src/state/state-types.ts @@ -0,0 +1,82 @@ +/* eslint-disable @typescript-eslint/ban-types */ +import type { TLPage, TLPageState } from '@tldraw/core' +import type { + ShapeStyles, + TLDrawShape, + TLDrawShapeType, + TLDrawToolType, +} from '../shape' +import type { TLDrawSettings } from '../types' +import type { StoreApi } from 'zustand' + +export type TLStore = StoreApi +export type TLChange = Data + +export interface Data { + page: TLPage + pageState: TLPageState + 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 + } +} + +export type DeepPartial = T extends Function + ? T + : T extends object + ? T extends unknown[] + ? DeepPartial[] + : { [P in keyof T]?: DeepPartial } + : T + +export interface Command { + id: string + before: DeepPartial + after: DeepPartial +} + +export interface History { + pointer: number + stack: Command[] +} + +export interface Session { + id: string + start: (data: Readonly, ...args: any[]) => Data + update: (data: Readonly, ...args: any[]) => Data + complete: (data: Readonly, ...args: any[]) => Data | Command + cancel: (data: Readonly, ...args: any[]) => Data +} + +export type TLDrawStatus = + | 'idle' + | 'pointingHandle' + | 'pointingBounds' + | 'pointingBoundsHandle' + | 'translatingHandle' + | 'translating' + | 'transforming' + | 'rotating' + | 'pinching' + | 'brushing' + | 'creating' + | '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 {} diff --git a/packages/tldraw/src/state/test-helpers.ts b/packages/tldraw/src/state/test-helpers.ts new file mode 100644 index 000000000..dc28a7ac1 --- /dev/null +++ b/packages/tldraw/src/state/test-helpers.ts @@ -0,0 +1,67 @@ +import { ColorStyle, DashStyle, SizeStyle, TLDrawShapeType } from '../shape' +import type { TLDrawDocument } 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/state/tldr.ts b/packages/tldraw/src/state/tldr.ts new file mode 100644 index 000000000..4667c3223 --- /dev/null +++ b/packages/tldraw/src/state/tldr.ts @@ -0,0 +1,705 @@ +import { TLBinding, TLBounds, TLTransformInfo, Vec, Utils } from '@tldraw/core' +import { + getShapeUtils, + ShapeStyles, + ShapesWithProp, + TLDrawShape, + TLDrawShapeUtil, +} from '../shape' +import type { Data } from './state-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) { + return data.pageState.selectedIds.map((id) => data.page.shapes[id]) + } + + static screenToWorld(data: Data, point: number[]) { + const { camera } = data.pageState + 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 getCurrentCamera(data: Data) { + return data.pageState.camera + } + + static getPage(data: Data) { + return data.page + } + + static getPageState(data: Data) { + return data.pageState + } + + static getSelectedIds(data: Data) { + return data.pageState.selectedIds + } + + static getShapes(data: Data) { + return Object.values(data.page.shapes) + } + + static getCamera(data: Data) { + return data.pageState.camera + } + + static getShape( + data: Data, + shapeId: string + ): T { + return data.page.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).map((shape) => + getShapeUtils(shape).getBounds(shape) + ) + ) + } + + static getParentId(data: Data, id: string) { + const shape = data.page.shapes[id] + return shape.parentId + } + + static getPointedId(data: Data, id: string): string { + const shape = data.page.shapes[id] + if (!shape) return id + + return shape.parentId === data.pageState.currentParentId || + shape.parentId === data.page.id + ? id + : this.getPointedId(data, shape.parentId) + } + + static getDrilledPointedId(data: Data, id: string): string { + const shape = data.page.shapes[id] + const { currentParentId, pointedId } = data.pageState + + return shape.parentId === data.page.id || + shape.parentId === pointedId || + shape.parentId === currentParentId + ? id + : this.getDrilledPointedId(data, shape.parentId) + } + + static getTopParentId(data: Data, id: string): string { + const shape = data.page.shapes[id] + + if (shape.parentId === shape.id) { + throw Error(`Shape has the same id as its parent! ${shape.id}`) + } + + return shape.parentId === data.page.id || + shape.parentId === data.pageState.currentParentId + ? id + : this.getTopParentId(data, shape.parentId) + } + + // Get an array of a shape id and its descendant shapes' ids + static getDocumentBranch(data: Data, id: string): string[] { + const shape = data.page.shapes[id] + + if (shape.children === undefined) return [id] + + return [ + id, + ...shape.children.flatMap((childId) => + this.getDocumentBranch(data, childId) + ), + ] + } + + // Get a deep array of unproxied shapes and their descendants + static getSelectedBranchSnapshot( + data: Data, + fn: (shape: TLDrawShape) => K + ): ({ id: string } & K)[] + static getSelectedBranchSnapshot(data: Data): TLDrawShape[] + static getSelectedBranchSnapshot( + data: Data, + fn?: (shape: TLDrawShape) => K + ): (TLDrawShape | K)[] { + const page = this.getPage(data) + + const copies = this.getSelectedIds(data) + .flatMap((id) => + this.getDocumentBranch(data, id).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): TLDrawShape[] + static getSelectedShapeSnapshot( + data: Data, + fn?: (shape: TLDrawShape) => K + ): ({ id: string } & K)[] + static getSelectedShapeSnapshot( + data: Data, + fn?: (shape: TLDrawShape) => K + ): (TLDrawShape | K)[] { + const copies = this.getSelectedShapes(data) + .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[]): string[] { + const visited = new Set(ids) + + ids.forEach((id) => { + const shape = data.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(data.page.shapes[childId]) + }) + } + + collectDescendants(shape) + + // Add asecendant shapes + function collectAscendants(shape: TLDrawShape): void { + const parentId = shape.parentId + if (parentId === data.page.id) return + if (visited.has(parentId)) return + visited.add(parentId) + collectAscendants(data.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(data.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> = {} + ): Data { + const shape = data.page.shapes[id] as T + + if (shape.children !== undefined) { + const deltas = this.getShapeUtils(shape).updateChildren( + shape, + shape.children.map((childId) => data.page.shapes[childId]) + ) + + if (deltas) { + return deltas.reduce((cData, delta) => { + const deltaShape = cData.page.shapes[delta.id!] + + if (!beforeShapes[deltaShape.id]) { + beforeShapes[deltaShape.id] = deltaShape + } + cData.page.shapes[deltaShape.id] = this.getShapeUtils( + deltaShape + ).mutate(deltaShape, delta) + afterShapes[deltaShape.id] = cData.page.shapes[deltaShape.id] + + if (deltaShape.children !== undefined) { + this.recursivelyUpdateChildren( + cData, + deltaShape.id, + beforeShapes, + afterShapes + ) + } + + return cData + }, data) + } + } + + return data + } + + static recursivelyUpdateParents( + data: Data, + id: string, + beforeShapes: Record> = {}, + afterShapes: Record> = {} + ): Data { + const shape = data.page.shapes[id] as T + + if (shape.parentId !== data.page.id) { + const parent = data.page.shapes[shape.parentId] as T + + const delta = this.getShapeUtils(shape).onChildrenChange( + parent, + parent.children!.map((childId) => data.page.shapes[childId]) + ) + + if (delta) { + if (!beforeShapes[parent.id]) { + beforeShapes[parent.id] = parent + } + data.page.shapes[parent.id] = this.getShapeUtils(parent).mutate( + parent, + delta + ) + afterShapes[parent.id] = data.page.shapes[parent.id] + } + + if (parent.parentId !== data.page.id) { + return this.recursivelyUpdateParents( + data, + parent.parentId, + beforeShapes, + afterShapes + ) + } + } + + return data + } + + static updateBindings( + data: Data, + id: string, + beforeShapes: Record> = {}, + afterShapes: Record> = {} + ): Data { + return Object.values(data.page.bindings) + .filter((binding) => binding.fromId === id || binding.toId === id) + .reduce((cData, binding) => { + if (!beforeShapes[binding.id]) { + beforeShapes[binding.fromId] = Utils.deepClone( + cData.page.shapes[binding.fromId] + ) + } + + if (!beforeShapes[binding.toId]) { + beforeShapes[binding.toId] = Utils.deepClone( + cData.page.shapes[binding.toId] + ) + } + + this.onBindingChange( + cData, + cData.page.shapes[binding.fromId], + binding, + cData.page.shapes[binding.toId] + ) + + afterShapes[binding.fromId] = Utils.deepClone( + cData.page.shapes[binding.fromId] + ) + afterShapes[binding.toId] = Utils.deepClone( + cData.page.shapes[binding.toId] + ) + + return cData + }, data) + } + + static getChildIndexAbove(data: Data, id: string): number { + const page = this.getPage(data) + + const shape = page.shapes[id] + + const siblings = (shape.parentId === page.id + ? Object.values(page.shapes) + : page.shapes[shape.parentId].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 setSelectedIds(data: Data, ids: string[]) { + data.pageState.selectedIds = ids + } + + static deselectAll(data: Data) { + this.setSelectedIds(data, []) + } + + static mutateShapes( + data: Data, + ids: string[], + fn: (shape: TLDrawShape, i: number) => Partial + ): { + before: Record> + after: Record> + data: Data + } { + const beforeShapes: Record> = {} + const afterShapes: Record> = {} + + ids.forEach((id, i) => { + const shape = data.page.shapes[id] + const change = fn(shape, i) + beforeShapes[id] = Object.fromEntries( + Object.keys(change).map((key) => [key, shape[key as keyof TLDrawShape]]) + ) as Partial + afterShapes[id] = change + data.page.shapes[id] = this.getShapeUtils(shape).mutate( + shape as TLDrawShape, + change as Partial + ) + }) + + const dataWithChildrenChanges = ids.reduce((cData, id) => { + return this.recursivelyUpdateChildren( + cData, + id, + beforeShapes, + afterShapes + ) + }, data) + + const dataWithParentChanges = ids.reduce((cData, id) => { + return this.recursivelyUpdateParents(cData, id, beforeShapes, afterShapes) + }, dataWithChildrenChanges) + + const dataWithBindingChanges = ids.reduce((cData, id) => { + return this.updateBindings(cData, id, beforeShapes, afterShapes) + }, dataWithParentChanges) + + return { + before: beforeShapes, + after: afterShapes, + data: dataWithBindingChanges, + } + } + + static createShapes(data: Data, shapes: TLDrawShape[]): void { + const page = this.getPage(data) + const shapeIds = shapes.map((shape) => shape.id) + + // Update selected ids + this.setSelectedIds(data, shapeIds) + + // Restore deleted shapes + shapes.forEach((shape) => { + const newShape = { ...shape } + page.shapes[shape.id] = newShape + }) + + // Update parents + shapes.forEach((shape) => { + if (shape.parentId === data.page.id) return + + const parent = page.shapes[shape.parentId] + + this.mutate(data, parent, { + children: parent.children!.includes(shape.id) + ? parent.children + : [...parent.children!, shape.id], + }) + }) + } + + static onSessionComplete(data: Data, shape: T) { + const delta = getShapeUtils(shape).onSessionComplete(shape) + if (!delta) return shape + return this.mutate(data, shape, delta) + } + + static onChildrenChange(data: Data, shape: T) { + const delta = getShapeUtils(shape).onChildrenChange( + shape, + shape.children!.map((id) => data.page.shapes[id]) + ) + if (!delta) return shape + return this.mutate(data, shape, delta) + } + + static onBindingChange( + data: Data, + shape: T, + binding: TLBinding, + otherShape: TLDrawShape + ) { + const delta = getShapeUtils(shape).onBindingChange( + shape, + binding, + otherShape, + getShapeUtils(otherShape).getBounds(otherShape) + ) + if (!delta) return shape + return this.mutate(data, shape, delta) + } + + static transform( + data: Data, + shape: T, + bounds: TLBounds, + info: TLTransformInfo + ) { + return this.mutate( + data, + shape, + getShapeUtils(shape).transform(shape, bounds, info) + ) + } + + static transformSingle( + data: Data, + shape: T, + bounds: TLBounds, + info: TLTransformInfo + ) { + return this.mutate( + data, + shape, + getShapeUtils(shape).transformSingle(shape, bounds, info) + ) + } + + static mutate( + data: Data, + shape: T, + props: Partial + ) { + let next = getShapeUtils(shape).mutate(shape, props) + + if ('children' in props) { + next = this.onChildrenChange(data, next) + } + + data.page.shapes[next.id] = next + + return next + } + + /* -------------------------------------------------- */ + /* Parents */ + /* -------------------------------------------------- */ + + static updateParents(data: Data, changedShapeIds: string[]): void { + if (changedShapeIds.length === 0) return + + const { shapes } = this.getPage(data) + + const parentToUpdateIds = Array.from( + new Set(changedShapeIds.map((id) => shapes[id].parentId).values()) + ).filter((id) => id !== data.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) + } + + this.updateParents(data, parentToUpdateIds) + } + + static getSelectedStyle(data: Data): ShapeStyles | false { + const { + page, + pageState, + appState: { currentStyle }, + } = data + + if (pageState.selectedIds.length === 0) { + return currentStyle + } + + const shapeStyles = data.pageState.selectedIds.map( + (id) => page.shapes[id].style + ) + + const commonStyle: ShapeStyles = {} as ShapeStyles + + const overrides = new Set([]) + + for (const shapeStyle of shapeStyles) { + ;(Object.keys(currentStyle) as (keyof ShapeStyles)[]).forEach((key) => { + if (overrides.has(key)) return + if (commonStyle[key] === undefined) { + // @ts-ignore + commonStyle[key] = shapeStyle[key] + } else { + if (commonStyle[key] === shapeStyle[key]) return + // @ts-ignore + commonStyle[key] = currentStyle[key] + overrides.add(key) + } + }) + } + + return commonStyle + } + + /* -------------------------------------------------- */ + /* Bindings */ + /* -------------------------------------------------- */ + + static getBinding(data: Data, id: string): TLBinding { + return this.getPage(data).bindings[id] + } + + static getBindings(data: Data): TLBinding[] { + const page = this.getPage(data) + return Object.values(page.bindings) + } + + static getBindingsWithShapeIds(data: Data, ids: string[]): TLBinding[] { + return Array.from( + new Set( + this.getBindings(data).filter((binding) => { + return ids.includes(binding.toId) || ids.includes(binding.fromId) + }) + ).values() + ) + } + + static createBindings(data: Data, bindings: TLBinding[]): void { + const page = this.getPage(data) + bindings.forEach((binding) => (page.bindings[binding.id] = binding)) + } + + static deleteBindings(data: Data, ids: string[]): void { + if (ids.length === 0) return + + const page = this.getPage(data) + + ids.forEach((id) => delete page.bindings[id]) + } + + /* -------------------------------------------------- */ + /* Assertions */ + /* -------------------------------------------------- */ + + static assertShapeHasProperty

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

{ + if (shape[prop] === undefined) { + throw new Error() + } + } + + // static updateBindings(data: Data, changedShapeIds: string[]): void { + // if (changedShapeIds.length === 0) return + + // // First gather all bindings that are directly affected by the change + // const firstPassBindings = this.getBindingsWithShapeIds(data, changedShapeIds) + + // // Gather all shapes that will be effected by the binding changes + // const effectedShapeIds = Array.from( + // new Set(firstPassBindings.flatMap((binding) => [binding.toId, binding.fromId])).values(), + // ) + + // // Now get all bindings that are affected by those shapes + // const bindingsToUpdate = this.getBindingsWithShapeIds(data, effectedShapeIds) + + // // Populate a map of { [shapeId]: BindingsThatWillEffectTheShape[] } + // // Note that this will include both to and from bindings, and so will + // // likely include ids other than the changedShapeIds provided. + + // const shapeIdToBindingsMap = new Map() + + // bindingsToUpdate.forEach((binding) => { + // const { toId, fromId } = binding + + // for (const id of [toId, fromId]) { + // if (!shapeIdToBindingsMap.has(id)) { + // shapeIdToBindingsMap.set(id, [binding]) + // } else { + // const bindings = shapeIdToBindingsMap.get(id) + // bindings.push(binding) + // } + // } + // }) + + // // Update each effected shape with the binding that effects it. + // Array.from(shapeIdToBindingsMap.entries()).forEach(([id, bindings]) => { + // const shape = this.getShape(data, id) + // bindings.forEach((binding) => { + // const otherShape = + // binding.toId === id + // ? this.getShape(data, binding.fromId) + // : this.getShape(data, binding.toId) + + // this.onBindingChange(data, shape, binding, otherShape) + // }) + // }) + // } +} diff --git a/packages/tldraw/src/state/tlstate.spec.ts b/packages/tldraw/src/state/tlstate.spec.ts new file mode 100644 index 000000000..281a82728 --- /dev/null +++ b/packages/tldraw/src/state/tlstate.spec.ts @@ -0,0 +1,240 @@ +import type { TLBoundsEdge, TLBoundsCorner } from '@tldraw/core' +import { inputs } from '@tldraw/core' +import { TLDrawState } from './tlstate' +import { mockDocument } from './test-helpers' + +interface PointerOptions { + id?: number + x?: number + y?: number + shiftKey?: boolean + altKey?: boolean + ctrlKey?: boolean +} + +class TLStateUtils { + tlstate: TLDrawState + + constructor(tlstate: TLDrawState) { + this.tlstate = tlstate + } + + pointCanvas = (options: PointerOptions = {}) => { + this.tlstate.onPointCanvas( + inputs.pointerDown(this.getPoint(options), 'canvas'), + {} as React.PointerEvent + ) + } + + pointShape = (id: string, options: PointerOptions = {}) => { + this.tlstate.onPointShape( + inputs.pointerDown(this.getPoint(options), id), + {} as React.PointerEvent + ) + } + + doubleClickShape = (id: string, options: PointerOptions = {}) => { + this.tlstate.onDoubleClickShape( + inputs.pointerDown(this.getPoint(options), id), + {} as React.PointerEvent + ) + } + + pointBounds = (options: PointerOptions = {}) => { + this.tlstate.onPointBounds( + inputs.pointerDown(this.getPoint(options), 'bounds'), + {} as React.PointerEvent + ) + } + + pointBoundsHandle = ( + id: TLBoundsCorner | TLBoundsEdge | 'rotate', + options: PointerOptions = {} + ) => { + this.tlstate.onPointBounds( + inputs.pointerDown(this.getPoint(options), 'bounds'), + {} as React.PointerEvent + ) + } + + stopPointing = (target = 'canvas', options: PointerOptions = {}) => { + this.tlstate.onPointerUp( + inputs.pointerDown(this.getPoint(options), target), + {} as React.PointerEvent + ) + } + + clickCanvas = (options: PointerOptions = {}) => { + this.pointCanvas(options) + this.stopPointing() + } + + clickShape = (id: string, options: PointerOptions = {}) => { + this.pointShape(id, options) + this.stopPointing(id, options) + } + + clickBounds = (options: PointerOptions = {}) => { + this.pointBounds(options) + this.stopPointing() + } + + clickBoundsHandle = ( + id: TLBoundsCorner | TLBoundsEdge | 'rotate', + options: PointerOptions = {} + ) => { + this.pointBoundsHandle(id, options) + this.stopPointing(id) + } + + 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 + } +} + +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) + }) + }) + + describe('Selection', () => { + it('selects a shape', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + expect(tlstate.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.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.status.current).toBe('idle') + }) + + it('shift-selects to deselect shapes', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1') + tlu.clickShape('rect2', { shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + tlu.clickShape('rect2', { shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual(['rect1']) + expect(tlstate.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('does not select selected shape when single-clicked', () => { + tlstate.loadDocument(mockDocument).selectAll() + tlu.clickShape('rect2') + expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2', 'rect3']) + }) + + 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.status.current).toBe('idle') + }) + + it('does not select on meta-shift-click', () => { + tlstate.loadDocument(mockDocument).deselectAll() + tlu.clickShape('rect1', { ctrlKey: true, shiftKey: true }) + expect(tlstate.selectedIds).toStrictEqual([]) + expect(tlstate.status.current).toBe('idle') + }) + + // Single click on a selected shape to select just that shape + + // it('single-selects shape in selection on click', () => { + // tlstate.deselectAll() + // clickShape('rect1') + // clickShape('rect2', { shiftKey: true }) + // clickShape('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect2']) + // expect(tlstate.status.current).toBe('idle') + // }) + + // it('single-selects shape in selection on pointerup only', () => { + // tlstate.deselectAll() + // clickShape('rect1') + // clickShape('rect2', { shiftKey: true }) + // pointShape('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect1', 'rect2']) + // stopPointing('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect2']) + // expect(tlstate.status.current).toBe('idle') + // }) + + // it('selects shapes if shift key is lifted before pointerup', () => { + // tlstate.deselectAll() + // clickShape('rect1') + // pointShape('rect2', { shiftKey: true }) + // expect(tlstate.status.current).toBe('pointingBounds') + // stopPointing('rect2') + // expect(tlstate.selectedIds).toStrictEqual(['rect2']) + // expect(tlstate.status.current).toBe('idle') + // }) + }) +}) diff --git a/packages/tldraw/src/state/tlstate.ts b/packages/tldraw/src/state/tlstate.ts new file mode 100644 index 000000000..ae3fe5bc6 --- /dev/null +++ b/packages/tldraw/src/state/tlstate.ts @@ -0,0 +1,1736 @@ +import type { TextShape } from './../shape/shape-types' +import { FlipType } from './../types' +import createReact, { PartialState } from 'zustand' +import { + TLBoundsCorner, + TLBoundsEdge, + TLBoundsEventHandler, + TLBoundsHandleEventHandler, + TLCallbacks, + TLCanvasEventHandler, + TLKeyboardInfo, + TLPage, + TLPageState, + TLPinchEventHandler, + TLPointerEventHandler, + TLWheelEventHandler, + Utils, + Vec, +} from '@tldraw/core' +import { brushUpdater } from '@tldraw/core' +import { + defaultStyle, + ShapeStyles, + TLDrawShape, + TLDrawShapeType, + TLDrawToolType, +} from '../shape' +import type { + Data, + Session, + Command, + History, + TLDrawStatus, + ParametersExceptFirst, +} from './state-types' +import * as commands from './command' +import { + BrushSession, + TransformSingleSession, + RotateSession, + DrawSession, + TranslateSession, + TransformSession, + HandleSession, + TextSession, +} from './session' +import { TLDR } from './tldr' +import { + TLDrawDocument, + MoveType, + AlignType, + StretchType, + DistributeType, +} from '../types' + +const initialData: Data = { + settings: { + isPenMode: false, + isDarkMode: false, + isDebugMode: false, + isReadonlyMode: false, + nudgeDistanceLarge: 10, + nudgeDistanceSmall: 1, + }, + appState: { + activeToolType: undefined, + activeTool: 'select', + hoveredId: undefined, + currentPageId: 'page', + pages: [{ id: 'page' }], + currentStyle: defaultStyle, + selectedStyle: defaultStyle, + isToolLocked: false, + isStyleOpen: false, + isEmptyCanvas: false, + }, + page: { + id: 'page', + childIndex: 1, + shapes: {}, + bindings: {}, + }, + pageState: { + id: 'page', + selectedIds: [], + camera: { + point: [0, 0], + zoom: 1, + }, + }, +} + +export class TLDrawState implements TLCallbacks { + store = createReact(() => initialData) + history: History = { + stack: [], + pointer: -1, + } + clipboard?: TLDrawShape[] + session?: Session + status: { current: TLDrawStatus; previous: TLDrawStatus } = { + current: 'idle', + previous: 'idle', + } + pointedId?: string + pointedHandle?: string + editingId?: string + pointedBoundsHandle?: TLBoundsCorner | TLBoundsEdge | 'rotate' + currentDocumentId = 'doc' + currentPageId = 'page' + pages: Record> = { page: initialData.page } + pageStates: Record = { page: initialData.pageState } + _onChange?: (state: TLDrawState, reason: string) => void + + // Low API + getState = this.store.getState + + setState = ( + data: Partial | ((data: Data) => Partial) + ) => { + const current = this.getState() + + // Apply incoming change + let result = typeof data === 'function' ? data(current) : data + + let next = { ...current, ...result } + + if ('page' in result) { + next.page = { + ...next.page, + shapes: Object.fromEntries( + Object.entries(next.page.shapes).filter(([_, shape]) => { + return ( + shape && + (shape.parentId === next.page.id || + next.page.shapes[shape.parentId]) + ) + }) + ), + } + } + + // Apply selected style change, if any + const newSelectedStyle = TLDR.getSelectedStyle(next as Data) + + if (newSelectedStyle) { + next = { + ...next, + appState: { + ...current.appState, + ...next.appState, + selectedStyle: newSelectedStyle, + }, + } + } + + this.store.setState(next as PartialState) + this.pages[next.page.id] = next.page + this.pageStates[next.page.id] = next.pageState + + return this + } + + getShape = (id: string): T => { + return this.getState().page.shapes[id] as T + } + + getPage = (id = this.currentPageId) => { + return this.pages[id] + } + + getPageState = (id = this.currentPageId) => { + return this.pageStates[id] + } + + getAppState = (id = this.currentPageId) => { + return this.getState().appState + } + + getPagePoint = (point: number[]) => { + const { camera } = this.getPageState() + return Vec.sub(Vec.div(point, camera.zoom), camera.point) + } + + /* ----------------------- UI ----------------------- */ + toggleStylePanel = () => { + this.setState((data) => ({ + appState: { + ...data.appState, + isStyleOpen: !data.appState.isStyleOpen, + }, + })) + return this + } + + /* -------------------- Settings -------------------- */ + togglePenMode = () => { + this.setState((data) => ({ + settings: { + ...data.settings, + isPenMode: !data.settings.isPenMode, + }, + })) + return this + } + toggleDarkMode = () => { + this.setState((data) => ({ + settings: { + ...data.settings, + isDarkMode: !data.settings.isDarkMode, + }, + })) + return this + } + /* --------------------- Status --------------------- */ + setStatus(status: TLDrawStatus) { + this.status.previous = this.status.current + this.status.current = status + // console.log(this.status.previous, ' -> ', this.status.current) + return this + } + /* -------------------- App State ------------------- */ + reset = () => { + this.setState((data) => ({ + appState: { + ...data.appState, + ...initialData.appState, + }, + settings: { + ...data.appState, + ...initialData.settings, + }, + })) + this._onChange?.(this, `reset`) + return this + } + + selectTool = (tool: TLDrawShapeType | 'select') => { + this.setState((data) => ({ + appState: { + ...data.appState, + activeTool: tool, + activeToolType: + tool === 'select' + ? 'select' + : TLDR.getShapeUtils({ type: tool } as TLDrawShape).toolType, + }, + })) + return this + } + + toggleToolLock = () => { + this.setState((data) => ({ + appState: { + ...data.appState, + isToolLocked: true, + }, + })) + return this + } + + /* --------------------- Camera --------------------- */ + zoomIn = () => { + const i = Math.round( + (this.store.getState().pageState.camera.zoom * 100) / 25 + ) + const nextZoom = TLDR.getCameraZoom((i + 1) * 0.25) + this.zoomTo(nextZoom) + return this + } + + zoomOut = () => { + const i = Math.round( + (this.store.getState().pageState.camera.zoom * 100) / 25 + ) + const nextZoom = TLDR.getCameraZoom((i - 1) * 0.25) + this.zoomTo(nextZoom) + return this + } + + zoomToFit = () => { + this.setState((data) => { + const shapes = Object.values(data.page.shapes) + + if (shapes.length === 0) return { pageState: data.pageState } + + const bounds = Utils.getCommonBounds( + Object.values(shapes).map(TLDR.getBounds) + ) + + const zoom = TLDR.getCameraZoom( + bounds.width > bounds.height + ? (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 { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + zoom, + }, + }, + } + }) + return this + } + + zoomToSelection = () => { + this.setState((data) => { + if (TLDR.getSelectedIds(data).length === 0) + return { pageState: data.pageState } + + const bounds = TLDR.getSelectedBounds(data) + + const zoom = TLDR.getCameraZoom( + bounds.width > bounds.height + ? (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 { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + zoom, + }, + }, + } + }) + return this + } + + resetCamera = () => { + this.setState((data) => ({ + pageState: { + ...data.pageState, + camera: { + zoom: 1, + point: Vec.round([window.innerWidth / 2, window.innerHeight / 2]), + }, + }, + })) + return this + } + + zoomToContent = () => { + this.setState((data) => { + const shapes = Object.values(data.page.shapes) + + if (shapes.length === 0) return { pageState: data.pageState } + + const bounds = Utils.getCommonBounds( + Object.values(shapes).map(TLDR.getBounds) + ) + + const { zoom } = data.pageState.camera + const mx = (window.innerWidth - bounds.width * zoom) / 2 / zoom + const my = (window.innerHeight - bounds.height * zoom) / 2 / zoom + + return { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.add([-bounds.minX, -bounds.minY], [mx, my])), + }, + }, + } + }) + return this + } + + zoomToActual = () => { + this.zoomTo(1) + return this + } + + zoomTo(next: number) { + this.setState((data) => { + const { zoom, point } = TLDR.getCurrentCamera(data) + const center = [window.innerWidth / 2, window.innerHeight / 2] + const p0 = Vec.sub(Vec.div(center, zoom), point) + const p1 = Vec.sub(Vec.div(center, next), point) + + return { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.add(point, Vec.sub(p1, p0))), + zoom: next, + }, + }, + } + }) + return this + } + + zoom = Utils.throttle((delta: number) => { + const { zoom } = this.store.getState().pageState.camera + const nextZoom = TLDR.getCameraZoom(zoom - delta * zoom) + this.zoomTo(nextZoom) + return this + }, 16) + + pan = (delta: number[]) => { + this.setState((data) => { + return { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.sub(data.pageState.camera.point, delta)), + }, + }, + } + }) + return this + } + + pinchZoom = (point: number[], delta: number[], zoomDelta: number) => { + this.setState((data) => { + const { camera } = data.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 { + pageState: { + ...data.pageState, + camera: { + ...data.pageState.camera, + point: Vec.round(Vec.add(nextPoint, Vec.sub(p1, p0))), + zoom: nextZoom, + }, + }, + } + }) + return this + } + + /* ---------------------- Document --------------------- */ + loadDocument = ( + document: TLDrawDocument, + onChange?: TLDrawState['_onChange'] + ) => { + this._onChange = onChange + this.currentDocumentId = document.id + this.pages = Utils.deepClone(document.pages) + this.pageStates = Utils.deepClone(document.pageStates) + this.currentPageId = Object.values(this.pages)[0].id + + this.setState((data) => ({ + page: this.pages[this.currentPageId], + pageState: this.pageStates[this.currentPageId], + appState: { + ...data.appState, + pageIds: Object.values(this.pages) + .sort((a, b) => (a.childIndex || 0) - (b.childIndex || 0)) + .map((page) => page.id), + }, + })) + + return this + } + + setCurrentPageId(pageId: string) { + if (pageId === this.currentPageId) return this + + this.currentPageId = pageId + + this.setState({ + page: this.pages[pageId], + pageState: this.pageStates[pageId], + }) + return this + } + + /* -------------------- Sessions -------------------- */ + startSession( + session: T, + ...args: ParametersExceptFirst + ) { + this.session = session + this.setState((data) => session.start(data, ...args)) + this._onChange?.(this, `session:start_${session.id}`) + return this + } + + updateSession( + ...args: ParametersExceptFirst + ) { + const { session } = this + if (!session) return this + this.setState((data) => session.update(data, ...args)) + this._onChange?.(this, `session:update:${session.id}`) + return this + } + + cancelSession( + ...args: ParametersExceptFirst + ) { + const { session } = this + if (!session) return this + + this.setState((data) => session.cancel(data, ...args)) + this.setStatus('idle') + this.session = undefined + this._onChange?.(this, `session:cancel:${session.id}`) + return this + } + + completeSession( + ...args: ParametersExceptFirst + ) { + const { session } = this + if (!session) return this + + this.setStatus('idle') + + const result = session.complete(this.store.getState(), ...args) + + if ('after' in result) { + this.do(result) + } else { + this.setState((data) => Utils.deepMerge(data, result)) + this._onChange?.(this, `session:complete:${session.id}`) + } + + const { isToolLocked, activeTool } = this.appState + + if (!isToolLocked && activeTool !== 'draw') { + this.selectTool('select') + } + + this.session = undefined + return this + } + + /* -------------------- Commands -------------------- */ + do(command: Command) { + const { history } = this + if (history.pointer !== history.stack.length - 1) { + history.stack = history.stack.slice(0, history.pointer + 1) + } + + history.stack.push(command) + + history.pointer = history.stack.length - 1 + + this.setState((data) => + Utils.deepMerge(data, history.stack[history.pointer].after) + ) + + this._onChange?.(this, `command:${command.id}`) + + return this + } + + undo = () => { + const { history } = this + + if (history.pointer <= -1) return this + + const command = history.stack[history.pointer] + + this.setState((data) => Utils.deepMerge(data, command.before)) + + history.pointer-- + + this._onChange?.(this, `undo:${command.id}`) + + return this + } + + redo = () => { + const { history } = this + + if (history.pointer >= history.stack.length - 1) return this + + history.pointer++ + + const command = history.stack[history.pointer] + + this.setState((data) => Utils.deepMerge(data, command.after)) + + this._onChange?.(this, `redo:${command.id}`) + + return this + } + + /* -------------------- Selection ------------------- */ + setSelectedIds(ids: string[], push = false) { + this.setState((data) => { + return { + pageState: { + ...data.pageState, + selectedIds: push + ? [...data.pageState.selectedIds, ...ids] + : [...ids], + }, + } + }) + return this + } + + select = (...ids: string[]) => { + this.setSelectedIds(ids) + return this + } + + selectAll = () => { + this.setState((data) => ({ + appState: { + ...data.appState, + activeTool: 'select', + activeToolType: 'select', + }, + pageState: { + ...data.pageState, + selectedIds: Object.keys(data.page.shapes), + }, + })) + return this + } + + deselectAll = () => { + this.setSelectedIds([]) + return this + } + + /* ----------------- Shape Functions ---------------- */ + style = (style: Partial, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.style(data, idsToMutate, style)) + return this + } + + align = (type: AlignType, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.align(data, idsToMutate, type)) + return this + } + + distribute = (type: DistributeType, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.distribute(data, idsToMutate, type)) + return this + } + + stretch = (type: StretchType, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.stretch(data, idsToMutate, type)) + return this + } + + flipHorizontal = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.flip(data, idsToMutate, FlipType.Horizontal)) + return this + } + + flipVertical = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.flip(data, idsToMutate, FlipType.Vertical)) + return this + } + + moveToBack = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.move(data, idsToMutate, MoveType.ToBack)) + return this + } + + moveBackward = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.move(data, idsToMutate, MoveType.Backward)) + return this + } + + moveForward = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.move(data, idsToMutate, MoveType.Forward)) + return this + } + + moveToFront = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.move(data, idsToMutate, MoveType.ToFront)) + return this + } + + nudge = (delta: number[], isMajor = false, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do( + commands.translate(data, idsToMutate, Vec.mul(delta, isMajor ? 10 : 1)) + ) + return this + } + + duplicate = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.duplicate(data, idsToMutate)) + return this + } + + toggleHidden = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.toggle(data, idsToMutate, 'isHidden')) + return this + } + + toggleLocked = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.toggle(data, idsToMutate, 'isLocked')) + return this + } + + toggleAspectRatioLocked = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.toggle(data, idsToMutate, 'isAspectRatioLocked')) + return this + } + + rotate = (delta = Math.PI * -0.5, ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + this.do(commands.rotate(data, idsToMutate, delta)) + return this + } + + group = (ids?: string[]) => { + // TODO + // const data = this.store.getState() + // const idsToMutate = ids ? ids : data.pageState.selectedIds + // this.do(commands.toggle(data, idsToMutate, 'isAspectRatioLocked')) + return this + } + + create = (...shapes: TLDrawShape[]) => { + const data = this.store.getState() + this.do(commands.create(data, shapes)) + return this + } + + delete = (ids?: string[]) => { + const data = this.store.getState() + const idsToMutate = ids ? ids : data.pageState.selectedIds + + if (idsToMutate.length === 0) return this + + this.do(commands.deleteShapes(data, idsToMutate)) + return this + } + + clear = () => { + this.selectAll() + this.delete() + return this + } + + cancel = () => { + switch (this.status.current) { + case 'idle': { + this.deselectAll() + this.selectTool('select') + break + } + case 'brushing': { + this.cancelSession() + brushUpdater.clear() + break + } + case 'translating': { + this.cancelSession() + break + } + case 'transforming': { + this.cancelSession() + break + } + case 'rotating': { + this.cancelSession() + break + } + case 'creating': { + this.cancelSession() + this.delete() + break + } + } + + return this + } + + copy = (ids?: string[]) => { + const data = this.store.getState() + const idsToCopy = ids ? ids : data.pageState.selectedIds + + this.clipboard = idsToCopy.map((id) => { + const shape = data.page.shapes[id] + + return { + ...shape, + id: Utils.uniqueId(), + childIndex: TLDR.getChildIndexAbove(data, id), + } + }) + + return this + } + + paste = (string?: string) => { + const { data } = this + if (string) { + try { + const jsonShapes = JSON.parse(string) + this.create(...jsonShapes) + } catch (e) { + // Create a text shape from the given string + const childIndex = + Object.values(data.page.shapes).sort( + (a, b) => b.childIndex - a.childIndex + )[0].childIndex + 1 + + const shape = TLDR.getShapeUtils( + TLDrawShapeType.Text + ).create({ + id: Utils.uniqueId(), + parentId: data.page.id, + childIndex, + point: this.getPagePoint([ + window.innerWidth / 2, + window.innerHeight / 2, + ]), + style: { ...data.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: data.page.id, + childIndex, + point: [boundsCenter.minX, boundsCenter.minY], + }) + ) + } + } + + if (!this.clipboard) return this + + const shapesToPaste = this.clipboard.map((shape) => { + return { + ...shape, + id: Utils.uniqueId(), + } + }) + + const commonBounds = Utils.getCommonBounds( + shapesToPaste.map(TLDR.getBounds) + ) + + const centeredBounds = Utils.centerBounds( + commonBounds, + this.getPagePoint([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 + } + + copyAsSvg = () => { + // TODO + return '' + } + + copyAsJson = () => { + // TODO + return {} + } + + save = () => { + // TODO + return this + } + /* -------------------- Sessions -------------------- */ + startBrushSession = (point: number[]) => { + this.setStatus('brushing') + this.startSession(new BrushSession(this.store.getState(), point)) + return this + } + + updateBrushSession = (point: number[], metaKey = false) => { + this.updateSession(point, metaKey) + return this + } + + startTranslateSession = (point: number[]) => { + this.setStatus('translating') + this.startSession(new TranslateSession(this.store.getState(), point)) + return this + } + + updateTranslateSession = ( + point: number[], + shiftKey = false, + altKey = false + ) => { + this.updateSession(point, shiftKey, altKey) + return this + } + + startTransformSession = ( + point: number[], + handle: TLBoundsCorner | TLBoundsEdge | 'rotate', + commandId?: string + ) => { + const { selectedIds } = this + + if (selectedIds.length === 0) return this + + this.setStatus('transforming') + + this.pointedBoundsHandle = handle + + if (this.pointedBoundsHandle === 'rotate') { + this.startSession(new RotateSession(this.store.getState(), point)) + } else if (this.selectedIds.length === 1) { + this.startSession( + new TransformSingleSession( + this.store.getState(), + point, + this.pointedBoundsHandle, + commandId + ) + ) + } else { + this.startSession( + new TransformSession( + this.store.getState(), + point, + this.pointedBoundsHandle + ) + ) + } + return this + } + + updateTransformSession = ( + point: number[], + shiftKey = false, + altKey = false + ) => { + this.updateSession( + point, + shiftKey, + altKey + ) + return this + } + + startTextSession = (id?: string) => { + this.editingId = id + this.setStatus('editing-text') + this.startSession(new TextSession(this.store.getState(), id)) + return this + } + + updateTextSession = (text: string) => { + this.updateSession(text) + return this + } + + startDrawSession = (id: string, point: number[]) => { + this.setStatus('creating') + this.startSession(new DrawSession(this.store.getState(), id, point)) + return this + } + + updateDrawSession = (point: number[], pressure: number, shiftKey = false) => { + this.updateSession(point, pressure, shiftKey) + return this + } + + startHandleSession = ( + point: number[], + handleId: string, + commandId?: string + ) => { + this.startSession( + new HandleSession(this.store.getState(), handleId, point, commandId) + ) + return this + } + + updateHandleSession = ( + point: number[], + shiftKey = false, + altKey = false, + metaKey = false + ) => { + this.updateSession(point, shiftKey, altKey, metaKey) + return this + } + + updateSessionsOnPointerMove: TLPointerEventHandler = (info) => { + switch (this.status.current) { + case 'pointingBoundsHandle': { + if (Vec.dist(info.origin, info.point) > 4) { + this.setStatus('transforming') + this.startTransformSession( + this.getPagePoint(info.origin), + this.pointedBoundsHandle! + ) + } + break + } + case 'pointingHandle': { + if (Vec.dist(info.origin, info.point) > 4) { + this.setStatus('translatingHandle') + this.startHandleSession( + this.getPagePoint(info.origin), + this.pointedHandle! + ) + } + break + } + case 'pointingBounds': { + if (Vec.dist(info.origin, info.point) > 4) { + this.setStatus('translating') + this.startTranslateSession(this.getPagePoint(info.origin)) + } + break + } + case 'brushing': { + this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + break + } + case 'translating': { + this.updateTranslateSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + break + } + case 'transforming': { + this.updateTransformSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + break + } + case 'translatingHandle': { + this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + break + } + case 'creating': { + switch (this.appState.activeToolType) { + case 'draw': { + this.updateDrawSession( + this.getPagePoint(info.point), + info.pressure, + info.shiftKey + ) + break + } + case 'bounds': { + this.updateTransformSession( + this.getPagePoint(info.point), + info.shiftKey + ) + break + } + case 'handle': { + this.updateHandleSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + break + } + case 'point': { + break + } + case 'points': { + break + } + } + break + } + } + } + + createActiveToolShape(point: number[]) { + const id = Utils.uniqueId() + const pagePoint = Vec.round(this.getPagePoint(point)) + + this.setState((data) => { + const { activeTool, activeToolType } = data.appState + + if (activeTool === 'select') return data + + if (!activeToolType) throw Error + + const utils = TLDR.getShapeUtils({ type: activeTool } as TLDrawShape) + + const shapes = Object.values(data.page.shapes) + + const childIndex = + shapes.length === 0 + ? 1 + : shapes.sort((a, b) => b.childIndex - a.childIndex)[0].childIndex + 1 + + return { + page: { + ...data.page, + shapes: { + ...data.page.shapes, + [id]: utils.create({ + id, + parentId: data.page.id, + childIndex, + point: pagePoint, + style: { ...data.appState.currentStyle }, + }), + }, + }, + pageState: { + ...data.pageState, + selectedIds: [id], + }, + } + }) + + const { activeTool, activeToolType } = this.getAppState() + + switch (activeToolType) { + case TLDrawToolType.Draw: { + this.startDrawSession(id, pagePoint) + break + } + case TLDrawToolType.Bounds: { + this.startTransformSession( + pagePoint, + TLBoundsCorner.BottomRight, + `create_${activeTool}` + ) + break + } + case TLDrawToolType.Handle: { + this.startHandleSession(pagePoint, 'end', `create_${activeTool}`) + break + } + case TLDrawToolType.Text: { + this.startTextSession() + break + } + case TLDrawToolType.Point: { + break + } + case TLDrawToolType.Points: { + break + } + } + } + + /* --------------------- Events --------------------- */ + onKeyDown = (key: string, info: TLKeyboardInfo) => { + if (key === 'Escape') { + this.cancel() + return + } + + switch (this.status.current) { + case 'idle': { + break + } + case 'brushing': { + if (key === 'Meta' || key === 'Control') { + this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + return + } + + break + } + case '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 '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 + } + } + } + + onKeyUp = (key: string, info: TLKeyboardInfo) => { + switch (this.status.current) { + case 'brushing': { + if (key === 'Meta' || key === 'Control') { + this.updateBrushSession(this.getPagePoint(info.point), info.metaKey) + } + break + } + case 'transforming': { + if (key === 'Shift' || key === 'Alt') { + this.updateTransformSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + } + break + } + case 'translating': { + if (key === 'Shift' || key === 'Alt') { + this.updateTransformSession( + this.getPagePoint(info.point), + info.shiftKey, + info.altKey + ) + } + break + } + } + } + + /* ------------- Renderer Event Handlers ------------ */ + onPinchStart: TLPinchEventHandler = () => { + this.setStatus('pinching') + } + + onPinchEnd: TLPinchEventHandler = () => { + this.setStatus(this.status.previous) + } + + onPinch: TLPinchEventHandler = (info, e) => { + if (this.status.current !== 'pinching') return + + this.pinchZoom(info.origin, info.delta, info.delta[2] / 350) + this.updateSessionsOnPointerMove(info, e as any) + } + + onPan: TLWheelEventHandler = (info, e) => { + if (this.status.current === '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.getPageState().camera.zoom) + const prev = this.getPageState().camera.point + const next = Vec.sub(prev, delta) + + if (Vec.isEqual(next, prev)) return + + this.pan(delta) + this.updateSessionsOnPointerMove(info, e as any) + } + + onZoom: TLWheelEventHandler = (info, e) => { + this.zoom(info.delta[2] / 100) + this.updateSessionsOnPointerMove(info, e as any) + } + + // Pointer Events + onPointerDown: TLPointerEventHandler = (info) => { + switch (this.status.current) { + case 'idle': { + switch (this.appState.activeTool) { + case 'draw': { + this.setStatus('creating') + this.createActiveToolShape(info.point) + break + } + case 'rectangle': { + this.setStatus('creating') + this.createActiveToolShape(info.point) + break + } + case 'ellipse': { + this.setStatus('creating') + this.createActiveToolShape(info.point) + break + } + case 'arrow': { + this.setStatus('creating') + this.createActiveToolShape(info.point) + break + } + } + } + } + } + + onPointerMove: TLPointerEventHandler = (info, e) => { + this.updateSessionsOnPointerMove(info, e) + } + + onPointerUp: TLPointerEventHandler = (info) => { + const data = this.getState() + + switch (this.status.current) { + case 'pointingBounds': { + if (info.target === 'bounds') { + // If we just clicked the selecting bounds's background, clear the selection + this.deselectAll() + } else if (data.pageState.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.setSelectedIds( + data.pageState.selectedIds.filter((id) => id !== info.target) + ) + } + } + } else if (this.pointedId === info.target) { + if (info.shiftKey) { + this.setSelectedIds([...data.pageState.selectedIds, info.target]) + } else { + this.setSelectedIds([info.target]) + } + this.pointedId = undefined + } + + this.setStatus('idle') + this.pointedId = undefined + break + } + case 'pointingBoundsHandle': { + this.setStatus('idle') + this.pointedBoundsHandle = undefined + break + } + case 'pointingHandle': { + this.setStatus('idle') + this.pointedHandle = undefined + break + } + case 'translatingHandle': { + this.completeSession() + this.pointedHandle = undefined + break + } + case 'brushing': { + this.completeSession() + brushUpdater.clear() + break + } + case 'translating': { + this.completeSession(this.getPagePoint(info.point)) + this.pointedId = undefined + break + } + case 'transforming': { + this.completeSession(this.getPagePoint(info.point)) + this.pointedBoundsHandle = undefined + break + } + case 'creating': { + this.completeSession(this.getPagePoint(info.point)) + this.pointedHandle = undefined + } + } + } + + // Canvas (background) + onPointCanvas: TLCanvasEventHandler = (info) => { + switch (this.status.current) { + case '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 + } + case 'editing-text': { + this.completeSession() + break + } + } + } + + onDoubleClickCanvas: TLCanvasEventHandler = (info) => { + // Unused + switch (this.status.current) { + case 'idle': { + switch (this.appState.activeTool) { + case 'text': { + // Create a text shape + this.setStatus('creating') + this.createActiveToolShape(info.point) + break + } + } + break + } + } + } + + onRightPointCanvas: TLCanvasEventHandler = () => { + // Unused + } + + onDragCanvas: TLCanvasEventHandler = () => { + // Unused + } + + onReleaseCanvas: TLCanvasEventHandler = () => { + // Unused + } + + // Shape + onPointShape: TLPointerEventHandler = (info) => { + const data = this.getState() + switch (this.status.current) { + case 'idle': { + switch (this.appState.activeTool) { + case 'select': { + if (info.metaKey) { + // While holding command key, allow event to pass through to canvas + return + } + + if (!data.pageState.selectedIds.includes(info.target)) { + // Set the pointed ID to the shape that was clicked. + this.pointedId = info.target + + // 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.setSelectedIds([info.target], info.shiftKey) + } + + this.setStatus('pointingBounds') + break + } + } + break + } + case 'pointingBounds': { + this.pointedId = info.target + break + } + } + } + + onReleaseShape: TLPointerEventHandler = (info) => { + // Unused + } + + onDoubleClickShape: TLPointerEventHandler = (info) => { + if (this.selectedIds.includes(info.target)) { + this.setSelectedIds([info.target]) + } + } + + onRightPointShape: TLPointerEventHandler = () => { + // TODO + } + + onDragShape: TLPointerEventHandler = (info) => { + // Unused + } + + onHoverShape: TLPointerEventHandler = (info) => { + this.setState((data) => ({ + pageState: { ...data.pageState, hoveredId: info.target }, + })) + } + + onUnhoverShape: TLPointerEventHandler = (info) => { + setTimeout(() => { + this.setState((data) => + data.pageState.hoveredId === info.target + ? { + pageState: { ...data.pageState, hoveredId: undefined }, + } + : data + ) + }, 10) + } + + // Bounds (bounding box background) + onPointBounds: TLBoundsEventHandler = (info) => { + this.setStatus('pointingBounds') + } + + onDoubleClickBounds: TLBoundsEventHandler = () => { + // TODO + } + + onRightPointBounds: TLBoundsEventHandler = () => { + // TODO + } + + onDragBounds: TLBoundsEventHandler = (info) => { + // Unused + } + + onHoverBounds: TLBoundsEventHandler = () => { + // TODO + } + + onUnhoverBounds: TLBoundsEventHandler = () => { + // TODO + } + + onReleaseBounds: TLBoundsEventHandler = (info) => { + switch (this.status.current) { + case 'translating': { + this.completeSession(this.getPagePoint(info.point)) + break + } + case 'brushing': { + this.completeSession() + brushUpdater.clear() + break + } + } + } + + // Bounds handles (corners, edges) + onPointBoundsHandle: TLBoundsHandleEventHandler = (info) => { + this.pointedBoundsHandle = info.target + this.setStatus('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('pointingHandle') + } + + onDoubleClickHandle: TLPointerEventHandler = () => { + // TODO + } + + onRightPointHandle: TLPointerEventHandler = () => { + // TODO + } + + onDragHandle: TLPointerEventHandler = () => { + // TODO + } + + onHoverHandle: TLPointerEventHandler = () => { + // TODO + } + + onUnhoverHandle: TLPointerEventHandler = () => { + // TODO + } + + onReleaseHandle: TLPointerEventHandler = () => { + // Unused + } + + onTextChange = (_id: string, text: string) => { + this.updateTextSession(text) + } + + onTextBlur = (_id: string) => { + this.completeSession() + } + + onTextFocus = (_id: string) => { + // Unused + } + + onTextKeyDown = (_id: string, key: string) => { + // Unused + } + + onTextKeyUp = (_id: string, key: string) => { + // Unused + } + + onChange = (ids: string[]) => { + const appState = this.getAppState() + if (appState.isEmptyCanvas && ids.length > 0) { + this.setState((data) => ({ + appState: { + ...data.appState, + isEmptyCanvas: false, + }, + })) + } else if (!appState.isEmptyCanvas && ids.length <= 0) { + this.setState((data) => ({ + appState: { + ...data.appState, + isEmptyCanvas: true, + }, + })) + } + } + + onError = (error: Error) => { + // TODO + } + + onBlurEditingShape = () => { + this.completeSession() + } + + get document(): TLDrawDocument { + return { + id: this.currentDocumentId, + pages: this.pages, + pageStates: this.pageStates, + } + } + + get data() { + return this.getState() + } + + get selectedIds() { + return this.pageState.selectedIds + } + + get page() { + return this.pages[this.currentPageId] + } + + get pageState() { + return this.pageStates[this.currentPageId] + } + + get appState() { + return this.data.appState + } +} 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/styles/stitches.config.ts b/packages/tldraw/src/styles/stitches.config.ts similarity index 86% rename from styles/stitches.config.ts rename to packages/tldraw/src/styles/stitches.config.ts index f11152a63..9534c65d9 100644 --- a/styles/stitches.config.ts +++ b/packages/tldraw/src/styles/stitches.config.ts @@ -1,6 +1,6 @@ import { createCss, defaultThemeMap } from '@stitches/react' -const { styled, global, css, theme, getCssString } = createCss({ +const { styled, css, theme, getCssString } = createCss({ themeMap: { ...defaultThemeMap, }, @@ -136,28 +136,6 @@ const dark = theme({ }, }) -const globalStyles = global({ - '*': { boxSizing: 'border-box' }, - ':root': { - '--camera-zoom': 1, - '--scale': 'calc(1 / var(--camera-zoom))', - }, - 'html, body': { - padding: '0px', - margin: '0px', - overscrollBehavior: 'none', - overscrollBehaviorX: 'none', - fontFamily: '$ui', - fontSize: '$2', - color: '$text', - backgroundColor: '$canvas', - minHeight: '100vh', - }, - body: { - overflow: 'hidden', - }, -}) - export default styled -export { css, getCssString, globalStyles, light, dark } +export { css, getCssString, light, dark } diff --git a/packages/tldraw/src/types.ts b/packages/tldraw/src/types.ts new file mode 100644 index 000000000..892714e0c --- /dev/null +++ b/packages/tldraw/src/types.ts @@ -0,0 +1,65 @@ +import type { TLPage, TLPageState, TLSettings } from '@tldraw/core' +import type { + TLDrawShape, + ShapeStyles, + TLDrawShapeType, + TLDrawToolType, +} from './shape' + +export interface TLDrawDocument { + id: string + pages: Record> + pageStates: Record +} + +export interface TLDrawSettings extends TLSettings { + isReadonlyMode: boolean + nudgeDistanceSmall: number + nudgeDistanceLarge: number +} + +export interface Data { + page: TLPage + pageState: TLPageState + settings: TLDrawSettings + appState: { + currentStyle: ShapeStyles + currentPageId: string + activeTool: TLDrawShapeType | 'select' + activeToolType?: TLDrawToolType | 'select' + isToolLocked: boolean + isStyleOpen: boolean + isEmptyCanvas: boolean + } +} + +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', +} diff --git a/packages/tldraw/tsconfig.json b/packages/tldraw/tsconfig.json new file mode 100644 index 000000000..5f180a19e --- /dev/null +++ b/packages/tldraw/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.json", + "include": ["src"], + "exclude": ["node_modules", "**/*.test.ts", "dist"], + "compilerOptions": { + "jsx": "preserve", + "lib": ["dom", "esnext"], + "module": "esnext", + "outDir": "./dist/types" + } +} diff --git a/packages/www/.eslintrc b/packages/www/.eslintrc new file mode 100644 index 000000000..97a2bb84e --- /dev/null +++ b/packages/www/.eslintrc @@ -0,0 +1,3 @@ +{ + "extends": ["next", "next/core-web-vitals"] +} diff --git a/packages/www/.gitignore b/packages/www/.gitignore new file mode 100644 index 000000000..9b577c799 --- /dev/null +++ b/packages/www/.gitignore @@ -0,0 +1,38 @@ +# 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 +./www/.next/cache + + +# 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 diff --git a/packages/www/CHANGELOG.md b/packages/www/CHANGELOG.md new file mode 100644 index 000000000..0359b9d98 --- /dev/null +++ b/packages/www/CHANGELOG.md @@ -0,0 +1,7 @@ +# @tldraw/www + +## 0.0.21 + +### Patch Changes + +- Move to TSDX monorepo. 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..e93a799a3 --- /dev/null +++ b/packages/www/components/editor.tsx @@ -0,0 +1,101 @@ +import * as React from 'react' +import { ColorStyle, DashStyle, SizeStyle, TLDrawShapeType, TLDrawState } from '@tldraw/tldraw' +import { TLDraw, TLDrawDocument } from '@tldraw/tldraw' +import { usePersistence } from '../hooks/usePersistence' + +const initialDoc: TLDrawDocument = { + id: 'doc', + pages: { + page1: { + id: 'page1', + shapes: { + rect1: { + id: 'rect1', + parentId: 'page1', + name: 'Rectangle', + childIndex: 1, + type: TLDrawShapeType.Rectangle, + point: [32, 32], + size: [100, 100], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Blue, + }, + }, + ellipse1: { + id: 'ellipse1', + parentId: 'page1', + name: 'Ellipse', + childIndex: 2, + type: TLDrawShapeType.Ellipse, + point: [132, 132], + radius: [50, 50], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Cyan, + }, + }, + draw1: { + id: 'draw1', + parentId: 'page1', + name: 'Draw', + childIndex: 3, + type: TLDrawShapeType.Draw, + point: [232, 232], + points: [ + [50, 0], + [100, 100], + [0, 100], + [50, 0], + [100, 100], + [0, 100], + [50, 0], + [56, 5], + ], + style: { + dash: DashStyle.Draw, + size: SizeStyle.Medium, + color: ColorStyle.Green, + }, + }, + }, + bindings: {}, + }, + }, + pageStates: { + page1: { + id: 'page1', + selectedIds: [], + currentParentId: 'page1', + camera: { + point: [0, 0], + zoom: 1, + }, + }, + }, +} + +export default function Editor(): JSX.Element { + const { value, setValue, status } = usePersistence('doc', initialDoc) + + const handleChange = React.useCallback( + (tlstate: TLDrawState, reason: string) => { + if (reason.startsWith('session')) { + return + } + + setValue(tlstate.document) + }, + [setValue] + ) + + if (status === 'loading' || value === null) { + return

+ } + + console.log(value) + + return +} diff --git a/packages/www/hooks/index.ts b/packages/www/hooks/index.ts new file mode 100644 index 000000000..bd9efb644 --- /dev/null +++ b/packages/www/hooks/index.ts @@ -0,0 +1,2 @@ +export * from './useGtag' +export * from './usePersistence' diff --git a/hooks/useGtag.ts b/packages/www/hooks/useGtag.tsx similarity index 51% rename from hooks/useGtag.ts rename to packages/www/hooks/useGtag.tsx index b7e36125e..59ae26bbf 100644 --- a/hooks/useGtag.ts +++ b/packages/www/hooks/useGtag.tsx @@ -1,14 +1,13 @@ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import router from 'next/router' -import { useEffect } from 'react' -import * as gtag from 'utils/gtag' +import * as React from 'react' +import * as gtag from '../utils/gtag' export default function useGtag() { - useEffect(() => { - if (process.env.NODE_ENV !== 'production') return - + React.useEffect(() => { function handleRouteChange(url: URL) { - gtag.pageview(url) + if (process.env.NODE_ENV !== 'production') { + gtag.pageview(url) + } } router.events.on('routeChangeComplete', handleRouteChange) @@ -16,5 +15,5 @@ export default function useGtag() { return () => { router.events.off('routeChangeComplete', handleRouteChange) } - }, [router.events]) + }, []) } diff --git a/packages/www/hooks/usePersistence.tsx b/packages/www/hooks/usePersistence.tsx new file mode 100644 index 000000000..cc3524992 --- /dev/null +++ b/packages/www/hooks/usePersistence.tsx @@ -0,0 +1,93 @@ +import * as React from "react" +import { openDB, DBSchema } from "idb" +import type { TLDrawDocument } from "@tldraw/tldraw" + +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) { + // eslint-disable-next-line react-hooks/exhaustive-deps + 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", 1).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", 1).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", 1, { + upgrade(db) { + 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/next-env.d.ts b/packages/www/next-env.d.ts similarity index 100% rename from next-env.d.ts rename to packages/www/next-env.d.ts diff --git a/packages/www/next.config.js b/packages/www/next.config.js new file mode 100644 index 000000000..2c20c20a5 --- /dev/null +++ b/packages/www/next.config.js @@ -0,0 +1,7 @@ +const withTM = require('next-transpile-modules')(['@tldraw/tldraw']) + +module.exports = withTM({ + reactStrictMode: true, + webpack5: true, + symlinks: false, +}) diff --git a/packages/www/package.json b/packages/www/package.json new file mode 100644 index 000000000..f8607beab --- /dev/null +++ b/packages/www/package.json @@ -0,0 +1,39 @@ +{ + "name": "@tldraw/www", + "version": "0.0.41", + "private": true, + "description": "A tiny little drawing app (editor).", + "author": "@steveruizok", + "repository": { + "type": "git", + "url": "git+https://github.com/tldraw/tldraw.git", + "directory": "packages/www" + }, + "license": "MIT", + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next dev", + "serve": "next serve", + "lint": "next lint" + }, + "dependencies": { + "@stitches/react": "^0.2.3", + "@tldraw/tldraw": "latest", + "idb": "^6.1.2", + "next": "^11.0.1", + "next-transpile-modules": "^8.0.0", + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "devDependencies": { + "@babel/core": "^7.14.6", + "@types/jest": "^26.0.23", + "@types/node": "^14.14.25", + "@types/react": "^17.0.16", + "@types/react-dom": "^17.0.9", + "eslint": "7.32.0", + "eslint-config-next": "11.0.1", + "typescript": "^4.3.5" + } +} diff --git a/packages/www/pages/_app.tsx b/packages/www/pages/_app.tsx new file mode 100644 index 000000000..41f0d76c5 --- /dev/null +++ b/packages/www/pages/_app.tsx @@ -0,0 +1,27 @@ +import { AppProps } from 'next/app' +import useGtag from '../hooks/useGtag' +import Head from 'next/head' +import './styles.css' + +function MyApp({ Component, pageProps }: AppProps): JSX.Element { + useGtag() + + return ( + <> + + tldraw + + +
+
+ +
+
+ + ) +} + +export default MyApp diff --git a/packages/www/pages/index.tsx b/packages/www/pages/index.tsx new file mode 100644 index 000000000..73c95b5e1 --- /dev/null +++ b/packages/www/pages/index.tsx @@ -0,0 +1,13 @@ +import * as React from 'react' +import dynamic from 'next/dynamic' +const Editor = dynamic(() => import('../components/editor'), { ssr: false }) + +export function Index(): JSX.Element { + return ( +
+ +
+ ) +} + +export default Index diff --git a/packages/www/pages/r/[id].tsx b/packages/www/pages/r/[id].tsx new file mode 100644 index 000000000..c41cc57ca --- /dev/null +++ b/packages/www/pages/r/[id].tsx @@ -0,0 +1,22 @@ +import { GetServerSideProps } from 'next' +import * as React from 'react' + +export default function Room(): JSX.Element { + return
Todo
+} + +export const getServerSideProps: GetServerSideProps = async (ctx) => { + const id = ctx.query.id?.toString() + + // Get document from database + + // If document does not exist, create an empty document + + // Return the document + + return { + props: { + id, + }, + } +} diff --git a/styles/globals.css b/packages/www/pages/styles.css similarity index 70% rename from styles/globals.css rename to packages/www/pages/styles.css index b81bd4da4..8a29cb3b6 100644 --- a/styles/globals.css +++ b/packages/www/pages/styles.css @@ -5,9 +5,8 @@ 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; + 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 { @@ -17,9 +16,8 @@ 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; + 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 { @@ -29,9 +27,8 @@ 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; + 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 { @@ -41,6 +38,19 @@ src: local('Verveine Regular'), url('/VerveineRegular.woff') format('woff'); } -.margin { - user-select: none; +* { + box-sizing: border-box; +} + +html, +body { + padding: 0px; + margin: 0px; + overscroll-behavior: none; + overscroll-behavior-x: none; + min-height: 100vh; +} + +body { + overflow: hidden; } diff --git a/packages/www/pages/u/[id].tsx b/packages/www/pages/u/[id].tsx new file mode 100644 index 000000000..4599ac9b0 --- /dev/null +++ b/packages/www/pages/u/[id].tsx @@ -0,0 +1,5 @@ +import * as React from 'react' + +export default function UserPage(): JSX.Element { + return
todo
+} diff --git a/public/VerveineRegular.woff b/packages/www/public/VerveineRegular.woff similarity index 100% rename from public/VerveineRegular.woff rename to packages/www/public/VerveineRegular.woff diff --git a/packages/www/public/favicon.ico b/packages/www/public/favicon.ico new file mode 100644 index 000000000..718d6fea4 Binary files /dev/null and b/packages/www/public/favicon.ico differ diff --git a/packages/www/public/vercel.svg b/packages/www/public/vercel.svg new file mode 100644 index 000000000..fbf0e25a6 --- /dev/null +++ b/packages/www/public/vercel.svg @@ -0,0 +1,4 @@ + + + \ No newline at end of file diff --git a/packages/www/styles/index.ts b/packages/www/styles/index.ts new file mode 100644 index 000000000..2eb879795 --- /dev/null +++ b/packages/www/styles/index.ts @@ -0,0 +1,5 @@ +import styled from './stitches.config' + +export * from './stitches.config' + +export default styled diff --git a/packages/www/styles/stitches.config.ts b/packages/www/styles/stitches.config.ts new file mode 100644 index 000000000..9534c65d9 --- /dev/null +++ b/packages/www/styles/stitches.config.ts @@ -0,0 +1,141 @@ +import { createCss, defaultThemeMap } from '@stitches/react' + +const { styled, css, theme, getCssString } = createCss({ + 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 light = theme({}) + +const dark = theme({ + 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, getCssString, light, dark } diff --git a/packages/www/tsconfig.json b/packages/www/tsconfig.json new file mode 100644 index 000000000..23fb955ad --- /dev/null +++ b/packages/www/tsconfig.json @@ -0,0 +1,23 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "target": "es5", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": false, + "forceConsistentCasingInFileNames": true, + "noEmit": true, + "module": "esnext", + "esModuleInterop": true, + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "preserve", + "paths": { + "@tldraw/tldraw": ["../tldraw"] + } + }, + "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], + "exclude": ["node_modules"] +} diff --git a/utils/gtag.ts b/packages/www/utils/gtag.ts similarity index 100% rename from utils/gtag.ts rename to packages/www/utils/gtag.ts diff --git a/pages/_app.tsx b/pages/_app.tsx deleted file mode 100644 index 9be543062..000000000 --- a/pages/_app.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import useGtag from 'hooks/useGtag' -import Head from 'next/head' -import { AppProps } from 'next/app' -import { globalStyles, dark, light } from 'styles' -import { Provider } from 'next-auth/client' -import { init } from 'utils/sentry' -import 'styles/globals.css' -import { ThemeProvider } from 'next-themes' - -init() - -function MyApp({ Component, pageProps }: AppProps): JSX.Element { - globalStyles() - - useGtag() - - return ( - <> - - tldraw - - - - - - - - - ) -} - -export default MyApp diff --git a/pages/_document.tsx b/pages/_document.tsx deleted file mode 100644 index 0ec043039..000000000 --- a/pages/_document.tsx +++ /dev/null @@ -1,102 +0,0 @@ -import NextDocument, { - Html, - Head, - Main, - NextScript, - DocumentContext, -} from 'next/document' -import { getCssString } from 'styles' -import { GA_TRACKING_ID } from 'utils/gtag' - -class MyDocument extends NextDocument { - static async getInitialProps(ctx: DocumentContext): Promise<{ - styles: JSX.Element - html: string - head?: JSX.Element[] - }> { - try { - const initialProps = await NextDocument.getInitialProps(ctx) - - return { - ...initialProps, - styles: ( - <> - {initialProps.styles} -