Compare commits
257
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13309a66c5 | ||
|
|
531829d95e | ||
|
|
d3cbceb7fa | ||
|
|
73111500d3 | ||
|
|
9e17b64e5e | ||
|
|
326da61573 | ||
|
|
994f2a3f1e | ||
|
|
5dbcf64353 | ||
|
|
eda2320dae | ||
|
|
b610c04481 | ||
|
|
d969849357 | ||
|
|
9a66fc6c05 | ||
|
|
158f169c43 | ||
|
|
ce27cb6159 | ||
|
|
2e04bcd485 | ||
|
|
7436f3926b | ||
|
|
e429b7048d | ||
|
|
e61b447413 | ||
|
|
73f0d854bf | ||
|
|
cec3cf8334 | ||
|
|
8640e75ccf | ||
|
|
ca7ce64fea | ||
|
|
e3a78fe5df | ||
|
|
554985f749 | ||
|
|
d3857fbb35 | ||
|
|
93c72cbb32 | ||
|
|
aeb4d39387 | ||
|
|
a0259360d6 | ||
|
|
243d8de7a8 | ||
|
|
81c927bab6 | ||
|
|
5c0eff50a0 | ||
|
|
19056d635b | ||
|
|
4d5f00ff08 | ||
|
|
20de06ef50 | ||
|
|
1849ff6ee2 | ||
|
|
6765fc16be | ||
|
|
5ca4f5bbf4 | ||
|
|
9392ec276d | ||
|
|
b26e4fcf99 | ||
|
|
45f3410da8 | ||
|
|
94b387ef7b | ||
|
|
6d0716eb6b | ||
|
|
8e26d5b500 | ||
|
|
c5a7723185 | ||
|
|
49172ac2d3 | ||
|
|
618a846451 | ||
|
|
d9f49ffd67 | ||
|
|
46e43baad1 | ||
|
|
bd35b682fa | ||
|
|
b6f9a8005e | ||
|
|
1acfaf6b6e | ||
|
|
5cf7087754 | ||
|
|
b2d49155ef | ||
|
|
9745461db7 | ||
|
|
21e9fcb2f5 | ||
|
|
e203203993 | ||
|
|
f224e4d596 | ||
|
|
e0ca689759 | ||
|
|
f792eb5ae7 | ||
|
|
4604c8d823 | ||
|
|
0896892f8a | ||
|
|
7fe225ee99 | ||
|
|
d2fd7be457 | ||
|
|
5c61613a2e | ||
|
|
b2767924de | ||
|
|
59d0a77862 | ||
|
|
987526d1e5 | ||
|
|
e894d41a22 | ||
|
|
14d1d39e8e | ||
|
|
69336b4832 | ||
|
|
32b677fb8a | ||
|
|
570f725516 | ||
|
|
a60860867c | ||
|
|
7a61196462 | ||
|
|
9653d676fe | ||
|
|
0cdd0eebf1 | ||
|
|
ae8b1d8bf7 | ||
|
|
92ffe8dda6 | ||
|
|
4d9dbd5a45 | ||
|
|
c66cabaefd | ||
|
|
e073128469 | ||
|
|
835848d711 | ||
|
|
2bd1d7ef59 | ||
|
|
37c8b9c2ff | ||
|
|
cf9f00f55f | ||
|
|
7ae9043221 | ||
|
|
7c567408c5 | ||
|
|
54612621aa | ||
|
|
d27b3bbebe | ||
|
|
e4ffc9812e | ||
|
|
a066317d3c | ||
|
|
050bc1ce2b | ||
|
|
5007df6522 | ||
|
|
d450c36581 | ||
|
|
66c92fc65a | ||
|
|
5f1cd4591a | ||
|
|
9be6243873 | ||
|
|
c3f6d6d344 | ||
|
|
339636caab | ||
|
|
08115ef311 | ||
|
|
e68abdbab4 | ||
|
|
8aff076782 | ||
|
|
96de887cc8 | ||
|
|
98ea46664c | ||
|
|
00e30ca0e4 | ||
|
|
de6371aac4 | ||
|
|
f47ddb988f | ||
|
|
59cbf5fde5 | ||
|
|
4486fbc2c6 | ||
|
|
edfbac9d7d | ||
|
|
719ae7b72f | ||
|
|
631a228ca1 | ||
|
|
4b5270ab12 | ||
|
|
dcee594b66 | ||
|
|
79d323fab1 | ||
|
|
e4edda4555 | ||
|
|
ca89d47d4c | ||
|
|
18c526d877 | ||
|
|
cbc6bd1ad8 | ||
|
|
83d9282dbf | ||
|
|
abff780983 | ||
|
|
c009e03c8e | ||
|
|
24bf4cb5fb | ||
|
|
0850ab0dd0 | ||
|
|
a7473169ba | ||
|
|
f6325b1e5e | ||
|
|
466220a3a8 | ||
|
|
d9cc7d1033 | ||
|
|
c037e9854c | ||
|
|
9373961857 | ||
|
|
1fd2fe56ee | ||
|
|
dba71e358d | ||
|
|
1ef287027b | ||
|
|
a51ed9ced6 | ||
|
|
4501d6d630 | ||
|
|
92a5936c7f | ||
|
|
50bd5fbae1 | ||
|
|
62bead66d7 | ||
|
|
b3073984b3 | ||
|
|
3c9ee13979 | ||
|
|
228c8136cf | ||
|
|
324dd460c8 | ||
|
|
d8ea085a94 | ||
|
|
adbd486f32 | ||
|
|
0a89c4b0c8 | ||
|
|
c03845bac3 | ||
|
|
d5a6014076 | ||
|
|
74861b1398 | ||
|
|
ac71ee7278 | ||
|
|
9088df8f5a | ||
|
|
c5fe0cd446 | ||
|
|
9f8783c2dd | ||
|
|
b475412199 | ||
|
|
5f1616f2c5 | ||
|
|
cec92c1d17 | ||
|
|
5f476e09d4 | ||
|
|
9aa6a27252 | ||
|
|
a2e8806f57 | ||
|
|
b71e702991 | ||
|
|
5c67329be6 | ||
|
|
28546fbb55 | ||
|
|
b0cccbb9e8 | ||
|
|
b621d065de | ||
|
|
96580c92a5 | ||
|
|
975441549b | ||
|
|
4be701416a | ||
|
|
1acb1e33f1 | ||
|
|
986e1e40d3 | ||
|
|
fab4a0e060 | ||
|
|
b265ebf88f | ||
|
|
351845019e | ||
|
|
c0fcce6f27 | ||
|
|
b093d2d2b6 | ||
|
|
69548c5502 | ||
|
|
6ca0afa6e5 | ||
|
|
c50f81b829 | ||
|
|
b122c8c4eb | ||
|
|
9a7216fe94 | ||
|
|
8eee749076 | ||
|
|
2158ad0656 | ||
|
|
74c3fea7f5 | ||
|
|
5e456e6d05 | ||
|
|
477cce2ed6 | ||
|
|
dd8e465304 | ||
|
|
11396a21de | ||
|
|
38236bc5e0 | ||
|
|
63ce5b82d7 | ||
|
|
bae0e985b2 | ||
|
|
04f852a40a | ||
|
|
f463c047c0 | ||
|
|
1fd347cade | ||
|
|
ef62390841 | ||
|
|
bf2bca221e | ||
|
|
d0733b1960 | ||
|
|
64c2d76cfa | ||
|
|
c76784b774 | ||
|
|
25e54e5999 | ||
|
|
55b7a7d554 | ||
|
|
c1c37a6ee7 | ||
|
|
25b529f519 | ||
|
|
8e6a747873 | ||
|
|
089b05db1b | ||
|
|
081e097cef | ||
|
|
8b5657e1ce | ||
|
|
8b2b03347c | ||
|
|
c2a8712593 | ||
|
|
ff1d7728a0 | ||
|
|
98b5c37e45 | ||
|
|
7db63bd397 | ||
|
|
390da3fd0f | ||
|
|
104664cb9e | ||
|
|
c822055ec8 | ||
|
|
e15d73d94c | ||
|
|
80ee097b85 | ||
|
|
10048b877b | ||
|
|
5dd5862bb9 | ||
|
|
79989fedda | ||
|
|
cecabc2196 | ||
|
|
ed8fb40b63 | ||
|
|
6e391728fe | ||
|
|
dfbfbc3f11 | ||
|
|
9b8ee3cacf | ||
|
|
4ea73d5d5b | ||
|
|
618f204ddd | ||
|
|
720588130c | ||
|
|
f354788cd0 | ||
|
|
1c7ee09010 | ||
|
|
ca15b0a008 | ||
|
|
650930c5ce | ||
|
|
79c0d59244 | ||
|
|
cd50b5f7e9 | ||
|
|
c0434957ff | ||
|
|
66aeaeb38d | ||
|
|
7f545e74ab | ||
|
|
a776955579 | ||
|
|
afa7932c9b | ||
|
|
1ee8d7d082 | ||
|
|
06db702b5d | ||
|
|
b53d1f6f3e | ||
|
|
ca1f3aa094 | ||
|
|
8ff159e76e | ||
|
|
f9d2d537a2 | ||
|
|
dac970c640 | ||
|
|
78bb3b3d84 | ||
|
|
7d9d7ad297 | ||
|
|
de20a5e3ba | ||
|
|
289f72e45d | ||
|
|
6dd0e6a4c5 | ||
|
|
96b31ecbce | ||
|
|
a132f154cb | ||
|
|
23acd8f6d1 | ||
|
|
a60709f5ea | ||
|
|
896c476716 | ||
|
|
133ba19919 | ||
|
|
a2136bfe9d | ||
|
|
6fbd64fdaa | ||
|
|
cc4b0c2932 |
@@ -4,5 +4,9 @@ REACT_APP_BACKEND_V2_POST_URL=https://json-dev.excalidraw.com/api/v2/post/
|
|||||||
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com
|
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com
|
||||||
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries
|
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries
|
||||||
|
|
||||||
REACT_APP_SOCKET_SERVER_URL=http://localhost:3000
|
REACT_APP_PORTAL_URL=http://localhost:3002
|
||||||
|
# Fill to set socket server URL used for collaboration.
|
||||||
|
# Meant for forks only: excalidraw.com uses custom REACT_APP_PORTAL_URL flow
|
||||||
|
REACT_APP_WS_SERVER_URL=
|
||||||
|
|
||||||
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyCMkxA60XIW8KbqMYL7edC4qT5l4qHX2h8","authDomain":"excalidraw-oss-dev.firebaseapp.com","projectId":"excalidraw-oss-dev","storageBucket":"excalidraw-oss-dev.appspot.com","messagingSenderId":"664559512677","appId":"1:664559512677:web:a385181f2928d328a7aa8c"}'
|
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyCMkxA60XIW8KbqMYL7edC4qT5l4qHX2h8","authDomain":"excalidraw-oss-dev.firebaseapp.com","projectId":"excalidraw-oss-dev","storageBucket":"excalidraw-oss-dev.appspot.com","messagingSenderId":"664559512677","appId":"1:664559512677:web:a385181f2928d328a7aa8c"}'
|
||||||
+5
-1
@@ -4,7 +4,11 @@ REACT_APP_BACKEND_V2_POST_URL=https://json.excalidraw.com/api/v2/post/
|
|||||||
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com
|
REACT_APP_LIBRARY_URL=https://libraries.excalidraw.com
|
||||||
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries
|
REACT_APP_LIBRARY_BACKEND=https://us-central1-excalidraw-room-persistence.cloudfunctions.net/libraries
|
||||||
|
|
||||||
REACT_APP_SOCKET_SERVER_URL=https://oss-collab-us1.excalidraw.com
|
REACT_APP_PORTAL_URL=https://portal.excalidraw.com
|
||||||
|
# Fill to set socket server URL used for collaboration.
|
||||||
|
# Meant for forks only: excalidraw.com uses custom REACT_APP_PORTAL_URL flow
|
||||||
|
REACT_APP_WS_SERVER_URL=
|
||||||
|
|
||||||
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
|
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
|
||||||
|
|
||||||
# production-only vars
|
# production-only vars
|
||||||
|
|||||||
@@ -23,4 +23,5 @@ jobs:
|
|||||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
- name: Auto release
|
- name: Auto release
|
||||||
run: |
|
run: |
|
||||||
|
yarn add @actions/core
|
||||||
yarn autorelease
|
yarn autorelease
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Auto release preview @excalidraw/excalidraw-preview
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created, edited]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Auto-release-excalidraw-preview:
|
||||||
|
name: Auto release preview
|
||||||
|
if: github.event.comment.body == '@excalibot release package' && github.event.issue.pull_request
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: React to release comment
|
||||||
|
uses: peter-evans/create-or-update-comment@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
||||||
|
comment-id: ${{ github.event.comment.id }}
|
||||||
|
reactions: "+1"
|
||||||
|
- name: Get PR SHA
|
||||||
|
id: sha
|
||||||
|
uses: actions/github-script@v4
|
||||||
|
with:
|
||||||
|
result-encoding: string
|
||||||
|
script: |
|
||||||
|
const { owner, repo, number } = context.issue;
|
||||||
|
const pr = await github.pulls.get({
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
pull_number: number,
|
||||||
|
});
|
||||||
|
return pr.data.head.sha
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
ref: ${{ steps.sha.outputs.result }}
|
||||||
|
fetch-depth: 2
|
||||||
|
- name: Setup Node.js 14.x
|
||||||
|
uses: actions/setup-node@v2
|
||||||
|
with:
|
||||||
|
node-version: 14.x
|
||||||
|
- name: Set up publish access
|
||||||
|
run: |
|
||||||
|
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
|
||||||
|
env:
|
||||||
|
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
- name: Auto release preview
|
||||||
|
id: "autorelease"
|
||||||
|
run: |
|
||||||
|
yarn add @actions/core
|
||||||
|
yarn autorelease preview ${{ github.event.issue.number }}
|
||||||
|
- name: Post comment post release
|
||||||
|
if: always()
|
||||||
|
uses: peter-evans/create-or-update-comment@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
||||||
|
issue-number: ${{ github.event.issue.number }}
|
||||||
|
body: "@${{ github.event.comment.user.login }} ${{ steps.autorelease.outputs.result }}"
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
name: Build packages
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
pull_request:
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
packages:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
- name: Setup Node.js 14.x
|
|
||||||
uses: actions/setup-node@v2
|
|
||||||
with:
|
|
||||||
node-version: 14.x
|
|
||||||
- name: Install dependencies
|
|
||||||
run: |
|
|
||||||
yarn --frozen-lockfile
|
|
||||||
yarn --cwd src/packages/excalidraw
|
|
||||||
yarn --cwd src/packages/utils
|
|
||||||
- name: Build @excalidraw/excalidraw
|
|
||||||
run: |
|
|
||||||
yarn --cwd src/packages/excalidraw run pack
|
|
||||||
- name: Build @excalidraw/utils
|
|
||||||
run: |
|
|
||||||
yarn --cwd src/packages/utils run pack
|
|
||||||
@@ -23,3 +23,7 @@ static
|
|||||||
yarn-debug.log*
|
yarn-debug.log*
|
||||||
yarn-error.log*
|
yarn-error.log*
|
||||||
src/packages/excalidraw/types
|
src/packages/excalidraw/types
|
||||||
|
src/packages/excalidraw/example/public/bundle.js
|
||||||
|
src/packages/excalidraw/example/public/excalidraw-assets-dev
|
||||||
|
src/packages/excalidraw/example/public/excalidraw.development.js
|
||||||
|
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
|
#!/bin/sh
|
||||||
yarn lint-staged
|
yarn lint-staged
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ Last but not least, we're thankful to these companies for offering their service
|
|||||||
|
|
||||||
[](https://vercel.com) [](https://sentry.io) [](https://crowdin.com)
|
[](https://vercel.com) [](https://sentry.io) [](https://crowdin.com)
|
||||||
|
|
||||||
|
## Who's integrating Excalidraw
|
||||||
|
|
||||||
|
[Google Cloud](https://googlecloudcheatsheet.withgoogle.com/architecture) • [Meta](https://meta.com/) • [CodeSandbox](https://codesandbox.io/) • [Obsidian Excalidraw](https://github.com/zsviczian/obsidian-excalidraw-plugin) • [Replit](https://replit.com/) • [Slite](https://slite.com/) • [Notion](https://notion.so/) • [HackerRank](https://www.hackerrank.com/) •
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
### Shortcuts
|
### Shortcuts
|
||||||
@@ -118,6 +122,10 @@ yarn start
|
|||||||
|
|
||||||
Now you can open [http://localhost:3000](http://localhost:3000) and start coding in your favorite code editor.
|
Now you can open [http://localhost:3000](http://localhost:3000) and start coding in your favorite code editor.
|
||||||
|
|
||||||
|
#### Collaboration
|
||||||
|
|
||||||
|
For collaboration, you will need to set up [collab server](https://github.com/excalidraw/excalidraw-room) in local.
|
||||||
|
|
||||||
#### Commands
|
#### Commands
|
||||||
|
|
||||||
| Command | Description |
|
| Command | Description |
|
||||||
|
|||||||
+16
-16
@@ -21,15 +21,15 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@sentry/browser": "6.2.5",
|
"@sentry/browser": "6.2.5",
|
||||||
"@sentry/integrations": "6.2.5",
|
"@sentry/integrations": "6.2.5",
|
||||||
"@testing-library/jest-dom": "5.15.0",
|
"@testing-library/jest-dom": "5.16.2",
|
||||||
"@testing-library/react": "12.1.2",
|
"@testing-library/react": "12.1.2",
|
||||||
"@tldraw/vec": "0.1.3",
|
"@tldraw/vec": "1.4.3",
|
||||||
"@types/jest": "27.0.2",
|
"@types/jest": "27.4.0",
|
||||||
"@types/pica": "5.1.3",
|
"@types/pica": "5.1.3",
|
||||||
"@types/react": "17.0.34",
|
"@types/react": "17.0.39",
|
||||||
"@types/react-dom": "17.0.11",
|
"@types/react-dom": "17.0.11",
|
||||||
"@types/socket.io-client": "1.4.36",
|
"@types/socket.io-client": "1.4.36",
|
||||||
"browser-fs-access": "0.21.1",
|
"browser-fs-access": "0.24.1",
|
||||||
"clsx": "1.1.1",
|
"clsx": "1.1.1",
|
||||||
"fake-indexeddb": "3.1.7",
|
"fake-indexeddb": "3.1.7",
|
||||||
"firebase": "8.3.3",
|
"firebase": "8.3.3",
|
||||||
@@ -37,7 +37,7 @@
|
|||||||
"idb-keyval": "6.0.3",
|
"idb-keyval": "6.0.3",
|
||||||
"image-blob-reduce": "3.0.1",
|
"image-blob-reduce": "3.0.1",
|
||||||
"lodash.throttle": "4.1.1",
|
"lodash.throttle": "4.1.1",
|
||||||
"nanoid": "3.1.30",
|
"nanoid": "3.1.32",
|
||||||
"open-color": "1.9.1",
|
"open-color": "1.9.1",
|
||||||
"pako": "1.0.11",
|
"pako": "1.0.11",
|
||||||
"perfect-freehand": "1.0.16",
|
"perfect-freehand": "1.0.16",
|
||||||
@@ -49,31 +49,31 @@
|
|||||||
"react": "17.0.2",
|
"react": "17.0.2",
|
||||||
"react-dom": "17.0.2",
|
"react-dom": "17.0.2",
|
||||||
"react-scripts": "4.0.3",
|
"react-scripts": "4.0.3",
|
||||||
"roughjs": "4.5.0",
|
"roughjs": "4.5.2",
|
||||||
"sass": "1.43.4",
|
"sass": "1.49.7",
|
||||||
"socket.io-client": "2.3.1",
|
"socket.io-client": "2.3.1",
|
||||||
"typescript": "4.5.2"
|
"typescript": "4.5.5"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@excalidraw/eslint-config": "1.0.0",
|
"@excalidraw/eslint-config": "1.0.0",
|
||||||
"@excalidraw/prettier-config": "1.0.2",
|
"@excalidraw/prettier-config": "1.0.2",
|
||||||
"@types/chai": "4.2.22",
|
"@types/chai": "4.3.0",
|
||||||
"@types/lodash.throttle": "4.1.6",
|
"@types/lodash.throttle": "4.1.6",
|
||||||
"@types/pako": "1.0.2",
|
"@types/pako": "1.0.3",
|
||||||
"@types/resize-observer-browser": "0.1.6",
|
"@types/resize-observer-browser": "0.1.6",
|
||||||
"chai": "4.3.4",
|
"chai": "4.3.6",
|
||||||
|
"dotenv": "10.0.0",
|
||||||
"eslint-config-prettier": "8.3.0",
|
"eslint-config-prettier": "8.3.0",
|
||||||
"eslint-plugin-prettier": "3.3.1",
|
"eslint-plugin-prettier": "3.3.1",
|
||||||
"firebase-tools": "9.22.0",
|
|
||||||
"husky": "7.0.4",
|
"husky": "7.0.4",
|
||||||
"jest-canvas-mock": "2.3.1",
|
"jest-canvas-mock": "2.3.1",
|
||||||
"lint-staged": "12.0.1",
|
"lint-staged": "12.3.3",
|
||||||
"pepjs": "0.5.3",
|
"pepjs": "0.5.3",
|
||||||
"prettier": "2.4.1",
|
"prettier": "2.5.1",
|
||||||
"rewire": "5.0.0"
|
"rewire": "5.0.0"
|
||||||
},
|
},
|
||||||
"resolutions": {
|
"resolutions": {
|
||||||
"@typescript-eslint/typescript-estree": "5.3.0"
|
"@typescript-eslint/typescript-estree": "5.10.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
|
|||||||
@@ -72,12 +72,6 @@
|
|||||||
crossorigin="anonymous"
|
crossorigin="anonymous"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<link
|
|
||||||
href="%REACT_APP_SOCKET_SERVER_URL%/socket.io"
|
|
||||||
rel="preconnect"
|
|
||||||
crossorigin="anonymous"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<link
|
<link
|
||||||
rel="manifest"
|
rel="manifest"
|
||||||
href="manifest.json"
|
href="manifest.json"
|
||||||
|
|||||||
+30
-5
@@ -1,5 +1,6 @@
|
|||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const { exec, execSync } = require("child_process");
|
const { exec, execSync } = require("child_process");
|
||||||
|
const core = require("@actions/core");
|
||||||
|
|
||||||
const excalidrawDir = `${__dirname}/../src/packages/excalidraw`;
|
const excalidrawDir = `${__dirname}/../src/packages/excalidraw`;
|
||||||
const excalidrawPackage = `${excalidrawDir}/package.json`;
|
const excalidrawPackage = `${excalidrawDir}/package.json`;
|
||||||
@@ -15,18 +16,25 @@ const publish = () => {
|
|||||||
execSync(`yarn --frozen-lockfile`, { cwd: excalidrawDir });
|
execSync(`yarn --frozen-lockfile`, { cwd: excalidrawDir });
|
||||||
execSync(`yarn run build:umd`, { cwd: excalidrawDir });
|
execSync(`yarn run build:umd`, { cwd: excalidrawDir });
|
||||||
execSync(`yarn --cwd ${excalidrawDir} publish`);
|
execSync(`yarn --cwd ${excalidrawDir} publish`);
|
||||||
|
console.info("Published 🎉");
|
||||||
|
core.setOutput(
|
||||||
|
"result",
|
||||||
|
`**Preview version has been shipped** :rocket:
|
||||||
|
You can use [@excalidraw/excalidraw-preview@${pkg.version}](https://www.npmjs.com/package/@excalidraw/excalidraw-preview/v/${pkg.version}) for testing!`,
|
||||||
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
core.setOutput("result", "package couldn't be published :warning:!");
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// get files changed between prev and head commit
|
// get files changed between prev and head commit
|
||||||
exec(`git diff --name-only HEAD^ HEAD`, async (error, stdout, stderr) => {
|
exec(`git diff --name-only HEAD^ HEAD`, async (error, stdout, stderr) => {
|
||||||
if (error || stderr) {
|
if (error || stderr) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
|
core.setOutput("result", ":warning: Package couldn't be published!");
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const changedFiles = stdout.trim().split("\n");
|
const changedFiles = stdout.trim().split("\n");
|
||||||
const filesToIgnoreRegex = /src\/excalidraw-app|packages\/utils/;
|
const filesToIgnoreRegex = /src\/excalidraw-app|packages\/utils/;
|
||||||
|
|
||||||
@@ -37,16 +45,33 @@ exec(`git diff --name-only HEAD^ HEAD`, async (error, stdout, stderr) => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
if (!excalidrawPackageFiles.length) {
|
if (!excalidrawPackageFiles.length) {
|
||||||
|
console.info("Skipping release as no valid diff found");
|
||||||
|
core.setOutput("result", "Skipping release as no valid diff found");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// update package.json
|
// update package.json
|
||||||
pkg.version = `${pkg.version}-${getShortCommitHash()}`;
|
|
||||||
pkg.name = "@excalidraw/excalidraw-next";
|
pkg.name = "@excalidraw/excalidraw-next";
|
||||||
fs.writeFileSync(excalidrawPackage, JSON.stringify(pkg, null, 2), "utf8");
|
let version = `${pkg.version}-${getShortCommitHash()}`;
|
||||||
|
|
||||||
// update readme
|
// update readme
|
||||||
const data = fs.readFileSync(`${excalidrawDir}/README_NEXT.md`, "utf8");
|
let data = fs.readFileSync(`${excalidrawDir}/README_NEXT.md`, "utf8");
|
||||||
|
|
||||||
|
const isPreview = process.argv.slice(2)[0] === "preview";
|
||||||
|
if (isPreview) {
|
||||||
|
// use pullNumber-commithash as the version for preview
|
||||||
|
const pullRequestNumber = process.argv.slice(3)[0];
|
||||||
|
version = `${pkg.version}-${pullRequestNumber}-${getShortCommitHash()}`;
|
||||||
|
// replace "excalidraw-next" with "excalidraw-preview"
|
||||||
|
pkg.name = "@excalidraw/excalidraw-preview";
|
||||||
|
data = data.replace(/excalidraw-next/g, "excalidraw-preview");
|
||||||
|
data = data.trim();
|
||||||
|
}
|
||||||
|
pkg.version = version;
|
||||||
|
|
||||||
|
fs.writeFileSync(excalidrawPackage, JSON.stringify(pkg, null, 2), "utf8");
|
||||||
|
|
||||||
fs.writeFileSync(`${excalidrawDir}/README.md`, data, "utf8");
|
fs.writeFileSync(`${excalidrawDir}/README.md`, data, "utf8");
|
||||||
|
console.info("Publish in progress...");
|
||||||
publish();
|
publish();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ const crowdinMap = {
|
|||||||
"de-DE": "en-de",
|
"de-DE": "en-de",
|
||||||
"el-GR": "en-el",
|
"el-GR": "en-el",
|
||||||
"es-ES": "en-es",
|
"es-ES": "en-es",
|
||||||
|
"eu-ES": "en-eu",
|
||||||
"fa-IR": "en-fa",
|
"fa-IR": "en-fa",
|
||||||
"fi-FI": "en-fi",
|
"fi-FI": "en-fi",
|
||||||
"fr-FR": "en-fr",
|
"fr-FR": "en-fr",
|
||||||
@@ -42,6 +43,7 @@ const crowdinMap = {
|
|||||||
"zh-CN": "en-zhcn",
|
"zh-CN": "en-zhcn",
|
||||||
"zh-HK": "en-zhhk",
|
"zh-HK": "en-zhhk",
|
||||||
"zh-TW": "en-zhtw",
|
"zh-TW": "en-zhtw",
|
||||||
|
"lt-LT": "en-lt",
|
||||||
"lv-LV": "en-lv",
|
"lv-LV": "en-lv",
|
||||||
"cs-CZ": "en-cs",
|
"cs-CZ": "en-cs",
|
||||||
"kk-KZ": "en-kk",
|
"kk-KZ": "en-kk",
|
||||||
@@ -69,6 +71,7 @@ const flags = {
|
|||||||
"kab-KAB": "🏳",
|
"kab-KAB": "🏳",
|
||||||
"kk-KZ": "🇰🇿",
|
"kk-KZ": "🇰🇿",
|
||||||
"ko-KR": "🇰🇷",
|
"ko-KR": "🇰🇷",
|
||||||
|
"lt-LT": "🇱🇹",
|
||||||
"lv-LV": "🇱🇻",
|
"lv-LV": "🇱🇻",
|
||||||
"my-MM": "🇲🇲",
|
"my-MM": "🇲🇲",
|
||||||
"nb-NO": "🇳🇴",
|
"nb-NO": "🇳🇴",
|
||||||
@@ -102,6 +105,7 @@ const languages = {
|
|||||||
"de-DE": "Deutsch",
|
"de-DE": "Deutsch",
|
||||||
"el-GR": "Ελληνικά",
|
"el-GR": "Ελληνικά",
|
||||||
"es-ES": "Español",
|
"es-ES": "Español",
|
||||||
|
"eu-ES": "Euskara",
|
||||||
"fa-IR": "فارسی",
|
"fa-IR": "فارسی",
|
||||||
"fi-FI": "Suomi",
|
"fi-FI": "Suomi",
|
||||||
"fr-FR": "Français",
|
"fr-FR": "Français",
|
||||||
@@ -114,6 +118,7 @@ const languages = {
|
|||||||
"kab-KAB": "Taqbaylit",
|
"kab-KAB": "Taqbaylit",
|
||||||
"kk-KZ": "Қазақ тілі",
|
"kk-KZ": "Қазақ тілі",
|
||||||
"ko-KR": "한국어",
|
"ko-KR": "한국어",
|
||||||
|
"lt-LT": "Lietuvių",
|
||||||
"lv-LV": "Latviešu",
|
"lv-LV": "Latviešu",
|
||||||
"my-MM": "Burmese",
|
"my-MM": "Burmese",
|
||||||
"nb-NO": "Norsk bokmål",
|
"nb-NO": "Norsk bokmål",
|
||||||
|
|||||||
+18
-11
@@ -20,7 +20,7 @@ const headerForType = {
|
|||||||
perf: "Performance",
|
perf: "Performance",
|
||||||
build: "Build",
|
build: "Build",
|
||||||
};
|
};
|
||||||
|
const badCommits = [];
|
||||||
const getCommitHashForLastVersion = async () => {
|
const getCommitHashForLastVersion = async () => {
|
||||||
try {
|
try {
|
||||||
const commitMessage = `"release @excalidraw/excalidraw@${lastVersion}"`;
|
const commitMessage = `"release @excalidraw/excalidraw@${lastVersion}"`;
|
||||||
@@ -53,19 +53,26 @@ const getLibraryCommitsSinceLastRelease = async () => {
|
|||||||
const messageWithoutType = commit.slice(indexOfColon + 1).trim();
|
const messageWithoutType = commit.slice(indexOfColon + 1).trim();
|
||||||
const messageWithCapitalizeFirst =
|
const messageWithCapitalizeFirst =
|
||||||
messageWithoutType.charAt(0).toUpperCase() + messageWithoutType.slice(1);
|
messageWithoutType.charAt(0).toUpperCase() + messageWithoutType.slice(1);
|
||||||
const prNumber = commit.match(/\(#([0-9]*)\)/)[1];
|
const prMatch = commit.match(/\(#([0-9]*)\)/);
|
||||||
|
if (prMatch) {
|
||||||
|
const prNumber = prMatch[1];
|
||||||
|
|
||||||
// return if the changelog already contains the pr number which would happen for package updates
|
// return if the changelog already contains the pr number which would happen for package updates
|
||||||
if (existingChangeLog.includes(prNumber)) {
|
if (existingChangeLog.includes(prNumber)) {
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
const prMarkdown = `[#${prNumber}](https://github.com/excalidraw/excalidraw/pull/${prNumber})`;
|
||||||
|
const messageWithPRLink = messageWithCapitalizeFirst.replace(
|
||||||
|
/\(#[0-9]*\)/,
|
||||||
|
prMarkdown,
|
||||||
|
);
|
||||||
|
commitList[type].push(messageWithPRLink);
|
||||||
|
} else {
|
||||||
|
badCommits.push(commit);
|
||||||
|
commitList[type].push(messageWithCapitalizeFirst);
|
||||||
}
|
}
|
||||||
const prMarkdown = `[#${prNumber}](https://github.com/excalidraw/excalidraw/pull/${prNumber})`;
|
|
||||||
const messageWithPRLink = messageWithCapitalizeFirst.replace(
|
|
||||||
/\(#[0-9]*\)/,
|
|
||||||
prMarkdown,
|
|
||||||
);
|
|
||||||
commitList[type].push(messageWithPRLink);
|
|
||||||
});
|
});
|
||||||
|
console.info("Bad commits:", badCommits);
|
||||||
return commitList;
|
return commitList;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,12 @@ import { t } from "../i18n";
|
|||||||
export const actionAddToLibrary = register({
|
export const actionAddToLibrary = register({
|
||||||
name: "addToLibrary",
|
name: "addToLibrary",
|
||||||
perform: (elements, appState, _, app) => {
|
perform: (elements, appState, _, app) => {
|
||||||
if (elements.some((element) => element.type === "image")) {
|
const selectedElements = getSelectedElements(
|
||||||
|
getNonDeletedElements(elements),
|
||||||
|
appState,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
if (selectedElements.some((element) => element.type === "image")) {
|
||||||
return {
|
return {
|
||||||
commitToHistory: false,
|
commitToHistory: false,
|
||||||
appState: {
|
appState: {
|
||||||
@@ -25,10 +30,7 @@ export const actionAddToLibrary = register({
|
|||||||
{
|
{
|
||||||
id: randomId(),
|
id: randomId(),
|
||||||
status: "unpublished",
|
status: "unpublished",
|
||||||
elements: getSelectedElements(
|
elements: selectedElements.map(deepCopyElement),
|
||||||
getNonDeletedElements(elements),
|
|
||||||
appState,
|
|
||||||
).map(deepCopyElement),
|
|
||||||
created: Date.now(),
|
created: Date.now(),
|
||||||
},
|
},
|
||||||
...items,
|
...items,
|
||||||
|
|||||||
@@ -8,13 +8,13 @@ import {
|
|||||||
CenterVerticallyIcon,
|
CenterVerticallyIcon,
|
||||||
} from "../components/icons";
|
} from "../components/icons";
|
||||||
import { ToolButton } from "../components/ToolButton";
|
import { ToolButton } from "../components/ToolButton";
|
||||||
import { getElementMap, getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { KEYS } from "../keys";
|
import { KEYS } from "../keys";
|
||||||
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { getShortcutKey } from "../utils";
|
import { arrayToMap, getShortcutKey } from "../utils";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
|
|
||||||
const enableActionGroup = (
|
const enableActionGroup = (
|
||||||
@@ -34,9 +34,11 @@ const alignSelectedElements = (
|
|||||||
|
|
||||||
const updatedElements = alignElements(selectedElements, alignment);
|
const updatedElements = alignElements(selectedElements, alignment);
|
||||||
|
|
||||||
const updatedElementsMap = getElementMap(updatedElements);
|
const updatedElementsMap = arrayToMap(updatedElements);
|
||||||
|
|
||||||
return elements.map((element) => updatedElementsMap[element.id] || element);
|
return elements.map(
|
||||||
|
(element) => updatedElementsMap.get(element.id) || element,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const actionAlignTop = register({
|
export const actionAlignTop = register({
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import { t } from "../i18n";
|
|||||||
import { CODES, KEYS } from "../keys";
|
import { CODES, KEYS } from "../keys";
|
||||||
import { getNormalizedZoom, getSelectedElements } from "../scene";
|
import { getNormalizedZoom, getSelectedElements } from "../scene";
|
||||||
import { centerScrollOn } from "../scene/scroll";
|
import { centerScrollOn } from "../scene/scroll";
|
||||||
import { getNewZoom } from "../scene/zoom";
|
import { getStateForZoom } from "../scene/zoom";
|
||||||
import { AppState, NormalizedZoomValue } from "../types";
|
import { AppState, NormalizedZoomValue } from "../types";
|
||||||
import { getShortcutKey } from "../utils";
|
import { getShortcutKey } from "../utils";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
@@ -26,7 +26,7 @@ export const actionChangeViewBackgroundColor = register({
|
|||||||
commitToHistory: !!value.viewBackgroundColor,
|
commitToHistory: !!value.viewBackgroundColor,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
PanelComponent: ({ appState, updateData }) => {
|
PanelComponent: ({ elements, appState, updateData }) => {
|
||||||
return (
|
return (
|
||||||
<div style={{ position: "relative" }}>
|
<div style={{ position: "relative" }}>
|
||||||
<ColorPicker
|
<ColorPicker
|
||||||
@@ -39,6 +39,8 @@ export const actionChangeViewBackgroundColor = register({
|
|||||||
updateData({ openPopup: active ? "canvasColorPicker" : null })
|
updateData({ openPopup: active ? "canvasColorPicker" : null })
|
||||||
}
|
}
|
||||||
data-testid="canvas-background-picker"
|
data-testid="canvas-background-picker"
|
||||||
|
elements={elements}
|
||||||
|
appState={appState}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -58,11 +60,15 @@ export const actionClearCanvas = register({
|
|||||||
files: {},
|
files: {},
|
||||||
theme: appState.theme,
|
theme: appState.theme,
|
||||||
elementLocked: appState.elementLocked,
|
elementLocked: appState.elementLocked,
|
||||||
|
penMode: appState.penMode,
|
||||||
|
penDetected: appState.penDetected,
|
||||||
exportBackground: appState.exportBackground,
|
exportBackground: appState.exportBackground,
|
||||||
exportEmbedScene: appState.exportEmbedScene,
|
exportEmbedScene: appState.exportEmbedScene,
|
||||||
gridSize: appState.gridSize,
|
gridSize: appState.gridSize,
|
||||||
showStats: appState.showStats,
|
showStats: appState.showStats,
|
||||||
pasteDialog: appState.pasteDialog,
|
pasteDialog: appState.pasteDialog,
|
||||||
|
elementType:
|
||||||
|
appState.elementType === "image" ? "selection" : appState.elementType,
|
||||||
},
|
},
|
||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
@@ -73,17 +79,18 @@ export const actionClearCanvas = register({
|
|||||||
|
|
||||||
export const actionZoomIn = register({
|
export const actionZoomIn = register({
|
||||||
name: "zoomIn",
|
name: "zoomIn",
|
||||||
perform: (_elements, appState) => {
|
perform: (_elements, appState, _, app) => {
|
||||||
const zoom = getNewZoom(
|
|
||||||
getNormalizedZoom(appState.zoom.value + ZOOM_STEP),
|
|
||||||
appState.zoom,
|
|
||||||
{ left: appState.offsetLeft, top: appState.offsetTop },
|
|
||||||
{ x: appState.width / 2, y: appState.height / 2 },
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
zoom,
|
...getStateForZoom(
|
||||||
|
{
|
||||||
|
viewportX: appState.width / 2 + appState.offsetLeft,
|
||||||
|
viewportY: appState.height / 2 + appState.offsetTop,
|
||||||
|
nextZoom: getNormalizedZoom(appState.zoom.value + ZOOM_STEP),
|
||||||
|
},
|
||||||
|
appState,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
commitToHistory: false,
|
commitToHistory: false,
|
||||||
};
|
};
|
||||||
@@ -107,18 +114,18 @@ export const actionZoomIn = register({
|
|||||||
|
|
||||||
export const actionZoomOut = register({
|
export const actionZoomOut = register({
|
||||||
name: "zoomOut",
|
name: "zoomOut",
|
||||||
perform: (_elements, appState) => {
|
perform: (_elements, appState, _, app) => {
|
||||||
const zoom = getNewZoom(
|
|
||||||
getNormalizedZoom(appState.zoom.value - ZOOM_STEP),
|
|
||||||
appState.zoom,
|
|
||||||
{ left: appState.offsetLeft, top: appState.offsetTop },
|
|
||||||
{ x: appState.width / 2, y: appState.height / 2 },
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
zoom,
|
...getStateForZoom(
|
||||||
|
{
|
||||||
|
viewportX: appState.width / 2 + appState.offsetLeft,
|
||||||
|
viewportY: appState.height / 2 + appState.offsetTop,
|
||||||
|
nextZoom: getNormalizedZoom(appState.zoom.value - ZOOM_STEP),
|
||||||
|
},
|
||||||
|
appState,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
commitToHistory: false,
|
commitToHistory: false,
|
||||||
};
|
};
|
||||||
@@ -142,25 +149,24 @@ export const actionZoomOut = register({
|
|||||||
|
|
||||||
export const actionResetZoom = register({
|
export const actionResetZoom = register({
|
||||||
name: "resetZoom",
|
name: "resetZoom",
|
||||||
perform: (_elements, appState) => {
|
perform: (_elements, appState, _, app) => {
|
||||||
return {
|
return {
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
zoom: getNewZoom(
|
...getStateForZoom(
|
||||||
1 as NormalizedZoomValue,
|
|
||||||
appState.zoom,
|
|
||||||
{ left: appState.offsetLeft, top: appState.offsetTop },
|
|
||||||
{
|
{
|
||||||
x: appState.width / 2,
|
viewportX: appState.width / 2 + appState.offsetLeft,
|
||||||
y: appState.height / 2,
|
viewportY: appState.height / 2 + appState.offsetTop,
|
||||||
|
nextZoom: getNormalizedZoom(1),
|
||||||
},
|
},
|
||||||
|
appState,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
commitToHistory: false,
|
commitToHistory: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
PanelComponent: ({ updateData, appState }) => (
|
PanelComponent: ({ updateData, appState }) => (
|
||||||
<Tooltip label={t("buttons.resetZoom")}>
|
<Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}>
|
||||||
<ToolButton
|
<ToolButton
|
||||||
type="button"
|
type="button"
|
||||||
className="reset-zoom-button"
|
className="reset-zoom-button"
|
||||||
@@ -212,14 +218,12 @@ const zoomToFitElements = (
|
|||||||
? getCommonBounds(selectedElements)
|
? getCommonBounds(selectedElements)
|
||||||
: getCommonBounds(nonDeletedElements);
|
: getCommonBounds(nonDeletedElements);
|
||||||
|
|
||||||
const zoomValue = zoomValueToFitBoundsOnViewport(commonBounds, {
|
const newZoom = {
|
||||||
width: appState.width,
|
value: zoomValueToFitBoundsOnViewport(commonBounds, {
|
||||||
height: appState.height,
|
width: appState.width,
|
||||||
});
|
height: appState.height,
|
||||||
const newZoom = getNewZoom(zoomValue, appState.zoom, {
|
}),
|
||||||
left: appState.offsetLeft,
|
};
|
||||||
top: appState.offsetTop,
|
|
||||||
});
|
|
||||||
|
|
||||||
const [x1, y1, x2, y2] = commonBounds;
|
const [x1, y1, x2, y2] = commonBounds;
|
||||||
const centerX = (x1 + x2) / 2;
|
const centerX = (x1 + x2) / 2;
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ export const actionCut = register({
|
|||||||
name: "cut",
|
name: "cut",
|
||||||
perform: (elements, appState, data, app) => {
|
perform: (elements, appState, data, app) => {
|
||||||
actionCopy.perform(elements, appState, data, app);
|
actionCopy.perform(elements, appState, data, app);
|
||||||
return actionDeleteSelected.perform(elements, appState, data, app);
|
return actionDeleteSelected.perform(elements, appState);
|
||||||
},
|
},
|
||||||
contextItemLabel: "labels.cut",
|
contextItemLabel: "labels.cut",
|
||||||
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.X,
|
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.X,
|
||||||
@@ -42,6 +42,7 @@ export const actionCopyAsSvg = register({
|
|||||||
const selectedElements = getSelectedElements(
|
const selectedElements = getSelectedElements(
|
||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
|
true,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await exportCanvas(
|
await exportCanvas(
|
||||||
@@ -81,6 +82,7 @@ export const actionCopyAsPng = register({
|
|||||||
const selectedElements = getSelectedElements(
|
const selectedElements = getSelectedElements(
|
||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
|
true,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await exportCanvas(
|
await exportCanvas(
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { newElementWith } from "../element/mutateElement";
|
|||||||
import { getElementsInGroup } from "../groups";
|
import { getElementsInGroup } from "../groups";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { fixBindingsAfterDeletion } from "../element/binding";
|
import { fixBindingsAfterDeletion } from "../element/binding";
|
||||||
|
import { isBoundToContainer } from "../element/typeChecks";
|
||||||
|
|
||||||
const deleteSelectedElements = (
|
const deleteSelectedElements = (
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
@@ -21,6 +22,12 @@ const deleteSelectedElements = (
|
|||||||
if (appState.selectedElementIds[el.id]) {
|
if (appState.selectedElementIds[el.id]) {
|
||||||
return newElementWith(el, { isDeleted: true });
|
return newElementWith(el, { isDeleted: true });
|
||||||
}
|
}
|
||||||
|
if (
|
||||||
|
isBoundToContainer(el) &&
|
||||||
|
appState.selectedElementIds[el.containerId]
|
||||||
|
) {
|
||||||
|
return newElementWith(el, { isDeleted: true });
|
||||||
|
}
|
||||||
return el;
|
return el;
|
||||||
}),
|
}),
|
||||||
appState: {
|
appState: {
|
||||||
@@ -55,7 +62,7 @@ export const actionDeleteSelected = register({
|
|||||||
if (appState.editingLinearElement) {
|
if (appState.editingLinearElement) {
|
||||||
const {
|
const {
|
||||||
elementId,
|
elementId,
|
||||||
activePointIndex,
|
selectedPointsIndices,
|
||||||
startBindingElement,
|
startBindingElement,
|
||||||
endBindingElement,
|
endBindingElement,
|
||||||
} = appState.editingLinearElement;
|
} = appState.editingLinearElement;
|
||||||
@@ -65,8 +72,7 @@ export const actionDeleteSelected = register({
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
// case: no point selected → delete whole element
|
// case: no point selected → delete whole element
|
||||||
activePointIndex == null ||
|
selectedPointsIndices == null ||
|
||||||
activePointIndex === -1 ||
|
|
||||||
// case: deleting last remaining point
|
// case: deleting last remaining point
|
||||||
element.points.length < 2
|
element.points.length < 2
|
||||||
) {
|
) {
|
||||||
@@ -86,15 +92,17 @@ export const actionDeleteSelected = register({
|
|||||||
// We cannot do this inside `movePoint` because it is also called
|
// We cannot do this inside `movePoint` because it is also called
|
||||||
// when deleting the uncommitted point (which hasn't caused any binding)
|
// when deleting the uncommitted point (which hasn't caused any binding)
|
||||||
const binding = {
|
const binding = {
|
||||||
startBindingElement:
|
startBindingElement: selectedPointsIndices?.includes(0)
|
||||||
activePointIndex === 0 ? null : startBindingElement,
|
? null
|
||||||
endBindingElement:
|
: startBindingElement,
|
||||||
activePointIndex === element.points.length - 1
|
endBindingElement: selectedPointsIndices?.includes(
|
||||||
? null
|
element.points.length - 1,
|
||||||
: endBindingElement,
|
)
|
||||||
|
? null
|
||||||
|
: endBindingElement,
|
||||||
};
|
};
|
||||||
|
|
||||||
LinearElementEditor.movePoint(element, activePointIndex, "delete");
|
LinearElementEditor.deletePoints(element, selectedPointsIndices);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
elements,
|
elements,
|
||||||
@@ -103,13 +111,15 @@ export const actionDeleteSelected = register({
|
|||||||
editingLinearElement: {
|
editingLinearElement: {
|
||||||
...appState.editingLinearElement,
|
...appState.editingLinearElement,
|
||||||
...binding,
|
...binding,
|
||||||
activePointIndex: activePointIndex > 0 ? activePointIndex - 1 : 0,
|
selectedPointsIndices:
|
||||||
|
selectedPointsIndices?.[0] > 0
|
||||||
|
? [selectedPointsIndices[0] - 1]
|
||||||
|
: [0],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let { elements: nextElements, appState: nextAppState } =
|
let { elements: nextElements, appState: nextAppState } =
|
||||||
deleteSelectedElements(elements, appState);
|
deleteSelectedElements(elements, appState);
|
||||||
fixBindingsAfterDeletion(
|
fixBindingsAfterDeletion(
|
||||||
|
|||||||
@@ -4,13 +4,13 @@ import {
|
|||||||
} from "../components/icons";
|
} from "../components/icons";
|
||||||
import { ToolButton } from "../components/ToolButton";
|
import { ToolButton } from "../components/ToolButton";
|
||||||
import { distributeElements, Distribution } from "../disitrubte";
|
import { distributeElements, Distribution } from "../disitrubte";
|
||||||
import { getElementMap, getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { CODES } from "../keys";
|
import { CODES, KEYS } from "../keys";
|
||||||
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { getShortcutKey } from "../utils";
|
import { arrayToMap, getShortcutKey } from "../utils";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
|
|
||||||
const enableActionGroup = (
|
const enableActionGroup = (
|
||||||
@@ -30,9 +30,11 @@ const distributeSelectedElements = (
|
|||||||
|
|
||||||
const updatedElements = distributeElements(selectedElements, distribution);
|
const updatedElements = distributeElements(selectedElements, distribution);
|
||||||
|
|
||||||
const updatedElementsMap = getElementMap(updatedElements);
|
const updatedElementsMap = arrayToMap(updatedElements);
|
||||||
|
|
||||||
return elements.map((element) => updatedElementsMap[element.id] || element);
|
return elements.map(
|
||||||
|
(element) => updatedElementsMap.get(element.id) || element,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const distributeHorizontally = register({
|
export const distributeHorizontally = register({
|
||||||
@@ -47,7 +49,8 @@ export const distributeHorizontally = register({
|
|||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
keyTest: (event) => event.altKey && event.code === CODES.H,
|
keyTest: (event) =>
|
||||||
|
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.H,
|
||||||
PanelComponent: ({ elements, appState, updateData }) => (
|
PanelComponent: ({ elements, appState, updateData }) => (
|
||||||
<ToolButton
|
<ToolButton
|
||||||
hidden={!enableActionGroup(elements, appState)}
|
hidden={!enableActionGroup(elements, appState)}
|
||||||
@@ -75,7 +78,8 @@ export const distributeVertically = register({
|
|||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
keyTest: (event) => event.altKey && event.code === CODES.V,
|
keyTest: (event) =>
|
||||||
|
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.V,
|
||||||
PanelComponent: ({ elements, appState, updateData }) => (
|
PanelComponent: ({ elements, appState, updateData }) => (
|
||||||
<ToolButton
|
<ToolButton
|
||||||
hidden={!enableActionGroup(elements, appState)}
|
hidden={!enableActionGroup(elements, appState)}
|
||||||
|
|||||||
@@ -2,13 +2,12 @@ import { KEYS } from "../keys";
|
|||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { duplicateElement, getNonDeletedElements } from "../element";
|
import { duplicateElement, getNonDeletedElements } from "../element";
|
||||||
import { isSomeElementSelected } from "../scene";
|
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
||||||
import { ToolButton } from "../components/ToolButton";
|
import { ToolButton } from "../components/ToolButton";
|
||||||
import { clone } from "../components/icons";
|
import { clone } from "../components/icons";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { getShortcutKey } from "../utils";
|
import { arrayToMap, getShortcutKey } from "../utils";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { mutateElement } from "../element/mutateElement";
|
|
||||||
import {
|
import {
|
||||||
selectGroupsForSelectedElements,
|
selectGroupsForSelectedElements,
|
||||||
getSelectedGroupForElement,
|
getSelectedGroupForElement,
|
||||||
@@ -18,41 +17,23 @@ import { AppState } from "../types";
|
|||||||
import { fixBindingsAfterDuplication } from "../element/binding";
|
import { fixBindingsAfterDuplication } from "../element/binding";
|
||||||
import { ActionResult } from "./types";
|
import { ActionResult } from "./types";
|
||||||
import { GRID_SIZE } from "../constants";
|
import { GRID_SIZE } from "../constants";
|
||||||
|
import { bindTextToShapeAfterDuplication } from "../element/textElement";
|
||||||
|
import { isBoundToContainer } from "../element/typeChecks";
|
||||||
|
|
||||||
export const actionDuplicateSelection = register({
|
export const actionDuplicateSelection = register({
|
||||||
name: "duplicateSelection",
|
name: "duplicateSelection",
|
||||||
perform: (elements, appState) => {
|
perform: (elements, appState) => {
|
||||||
// duplicate point if selected while editing multi-point element
|
// duplicate selected point(s) if editing a line
|
||||||
if (appState.editingLinearElement) {
|
if (appState.editingLinearElement) {
|
||||||
const { activePointIndex, elementId } = appState.editingLinearElement;
|
const ret = LinearElementEditor.duplicateSelectedPoints(appState);
|
||||||
const element = LinearElementEditor.getElement(elementId);
|
|
||||||
if (!element || activePointIndex === null) {
|
if (!ret) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const { points } = element;
|
|
||||||
const selectedPoint = points[activePointIndex];
|
|
||||||
const nextPoint = points[activePointIndex + 1];
|
|
||||||
mutateElement(element, {
|
|
||||||
points: [
|
|
||||||
...points.slice(0, activePointIndex + 1),
|
|
||||||
nextPoint
|
|
||||||
? [
|
|
||||||
(selectedPoint[0] + nextPoint[0]) / 2,
|
|
||||||
(selectedPoint[1] + nextPoint[1]) / 2,
|
|
||||||
]
|
|
||||||
: [selectedPoint[0] + 30, selectedPoint[1] + 30],
|
|
||||||
...points.slice(activePointIndex + 1),
|
|
||||||
],
|
|
||||||
});
|
|
||||||
return {
|
return {
|
||||||
appState: {
|
|
||||||
...appState,
|
|
||||||
editingLinearElement: {
|
|
||||||
...appState.editingLinearElement,
|
|
||||||
activePointIndex: activePointIndex + 1,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
elements,
|
elements,
|
||||||
|
appState: ret.appState,
|
||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -106,9 +87,12 @@ const duplicateElements = (
|
|||||||
const finalElements: ExcalidrawElement[] = [];
|
const finalElements: ExcalidrawElement[] = [];
|
||||||
|
|
||||||
let index = 0;
|
let index = 0;
|
||||||
|
const selectedElementIds = arrayToMap(
|
||||||
|
getSelectedElements(elements, appState, true),
|
||||||
|
);
|
||||||
while (index < elements.length) {
|
while (index < elements.length) {
|
||||||
const element = elements[index];
|
const element = elements[index];
|
||||||
if (appState.selectedElementIds[element.id]) {
|
if (selectedElementIds.get(element.id)) {
|
||||||
if (element.groupIds.length) {
|
if (element.groupIds.length) {
|
||||||
const groupId = getSelectedGroupForElement(appState, element);
|
const groupId = getSelectedGroupForElement(appState, element);
|
||||||
// if group selected, duplicate it atomically
|
// if group selected, duplicate it atomically
|
||||||
@@ -130,7 +114,11 @@ const duplicateElements = (
|
|||||||
}
|
}
|
||||||
index++;
|
index++;
|
||||||
}
|
}
|
||||||
|
bindTextToShapeAfterDuplication(
|
||||||
|
finalElements,
|
||||||
|
oldElements,
|
||||||
|
oldIdToDuplicatedId,
|
||||||
|
);
|
||||||
fixBindingsAfterDuplication(finalElements, oldElements, oldIdToDuplicatedId);
|
fixBindingsAfterDuplication(finalElements, oldElements, oldIdToDuplicatedId);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -140,7 +128,9 @@ const duplicateElements = (
|
|||||||
...appState,
|
...appState,
|
||||||
selectedGroupIds: {},
|
selectedGroupIds: {},
|
||||||
selectedElementIds: newElements.reduce((acc, element) => {
|
selectedElementIds: newElements.reduce((acc, element) => {
|
||||||
acc[element.id] = true;
|
if (!isBoundToContainer(element)) {
|
||||||
|
acc[element.id] = true;
|
||||||
|
}
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as any),
|
}, {} as any),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
import { getSelectedElements } from "../scene";
|
import { getSelectedElements } from "../scene";
|
||||||
import { getElementMap, getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { mutateElement } from "../element/mutateElement";
|
import { mutateElement } from "../element/mutateElement";
|
||||||
import { ExcalidrawElement, NonDeleted } from "../element/types";
|
import { ExcalidrawElement, NonDeleted } from "../element/types";
|
||||||
import { normalizeAngle, resizeSingleElement } from "../element/resizeElements";
|
import { normalizeAngle, resizeSingleElement } from "../element/resizeElements";
|
||||||
@@ -9,6 +9,7 @@ import { getTransformHandles } from "../element/transformHandles";
|
|||||||
import { isFreeDrawElement, isLinearElement } from "../element/typeChecks";
|
import { isFreeDrawElement, isLinearElement } from "../element/typeChecks";
|
||||||
import { updateBoundElements } from "../element/binding";
|
import { updateBoundElements } from "../element/binding";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
|
import { arrayToMap } from "../utils";
|
||||||
|
|
||||||
const enableActionFlipHorizontal = (
|
const enableActionFlipHorizontal = (
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
@@ -83,9 +84,11 @@ const flipSelectedElements = (
|
|||||||
flipDirection,
|
flipDirection,
|
||||||
);
|
);
|
||||||
|
|
||||||
const updatedElementsMap = getElementMap(updatedElements);
|
const updatedElementsMap = arrayToMap(updatedElements);
|
||||||
|
|
||||||
return elements.map((element) => updatedElementsMap[element.id] || element);
|
return elements.map(
|
||||||
|
(element) => updatedElementsMap.get(element.id) || element,
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const flipElements = (
|
const flipElements = (
|
||||||
@@ -142,10 +145,9 @@ const flipElement = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isLinearElement(element)) {
|
if (isLinearElement(element)) {
|
||||||
for (let i = 1; i < element.points.length; i++) {
|
for (let index = 1; index < element.points.length; index++) {
|
||||||
LinearElementEditor.movePoint(element, i, [
|
LinearElementEditor.movePoints(element, [
|
||||||
-element.points[i][0],
|
{ index, point: [-element.points[index][0], element.points[index][1]] },
|
||||||
element.points[i][1],
|
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
LinearElementEditor.normalizePoints(element);
|
LinearElementEditor.normalizePoints(element);
|
||||||
@@ -153,7 +155,7 @@ const flipElement = (
|
|||||||
// calculate new x-coord for transformation
|
// calculate new x-coord for transformation
|
||||||
newNCoordsX = usingNWHandle ? element.x + 2 * width : element.x - 2 * width;
|
newNCoordsX = usingNWHandle ? element.x + 2 * width : element.x - 2 * width;
|
||||||
resizeSingleElement(
|
resizeSingleElement(
|
||||||
element,
|
new Map().set(element.id, element),
|
||||||
true,
|
true,
|
||||||
element,
|
element,
|
||||||
usingNWHandle ? "nw" : "ne",
|
usingNWHandle ? "nw" : "ne",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { CODES, KEYS } from "../keys";
|
import { CODES, KEYS } from "../keys";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { getShortcutKey } from "../utils";
|
import { arrayToMap, getShortcutKey } from "../utils";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
import { UngroupIcon, GroupIcon } from "../components/icons";
|
import { UngroupIcon, GroupIcon } from "../components/icons";
|
||||||
import { newElementWith } from "../element/mutateElement";
|
import { newElementWith } from "../element/mutateElement";
|
||||||
@@ -17,8 +17,9 @@ import {
|
|||||||
import { getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { randomId } from "../random";
|
import { randomId } from "../random";
|
||||||
import { ToolButton } from "../components/ToolButton";
|
import { ToolButton } from "../components/ToolButton";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement, ExcalidrawTextElement } from "../element/types";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
|
import { isBoundToContainer } from "../element/typeChecks";
|
||||||
|
|
||||||
const allElementsInSameGroup = (elements: readonly ExcalidrawElement[]) => {
|
const allElementsInSameGroup = (elements: readonly ExcalidrawElement[]) => {
|
||||||
if (elements.length >= 2) {
|
if (elements.length >= 2) {
|
||||||
@@ -44,6 +45,7 @@ const enableActionGroup = (
|
|||||||
const selectedElements = getSelectedElements(
|
const selectedElements = getSelectedElements(
|
||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
|
true,
|
||||||
);
|
);
|
||||||
return (
|
return (
|
||||||
selectedElements.length >= 2 && !allElementsInSameGroup(selectedElements)
|
selectedElements.length >= 2 && !allElementsInSameGroup(selectedElements)
|
||||||
@@ -56,6 +58,7 @@ export const actionGroup = register({
|
|||||||
const selectedElements = getSelectedElements(
|
const selectedElements = getSelectedElements(
|
||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
|
true,
|
||||||
);
|
);
|
||||||
if (selectedElements.length < 2) {
|
if (selectedElements.length < 2) {
|
||||||
// nothing to group
|
// nothing to group
|
||||||
@@ -83,8 +86,9 @@ export const actionGroup = register({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
const newGroupId = randomId();
|
const newGroupId = randomId();
|
||||||
|
const selectElementIds = arrayToMap(selectedElements);
|
||||||
const updatedElements = elements.map((element) => {
|
const updatedElements = elements.map((element) => {
|
||||||
if (!appState.selectedElementIds[element.id]) {
|
if (!selectElementIds.get(element.id)) {
|
||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
return newElementWith(element, {
|
return newElementWith(element, {
|
||||||
@@ -148,7 +152,12 @@ export const actionUngroup = register({
|
|||||||
if (groupIds.length === 0) {
|
if (groupIds.length === 0) {
|
||||||
return { appState, elements, commitToHistory: false };
|
return { appState, elements, commitToHistory: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const boundTextElementIds: ExcalidrawTextElement["id"][] = [];
|
||||||
const nextElements = elements.map((element) => {
|
const nextElements = elements.map((element) => {
|
||||||
|
if (isBoundToContainer(element)) {
|
||||||
|
boundTextElementIds.push(element.id);
|
||||||
|
}
|
||||||
const nextGroupIds = removeFromSelectedGroups(
|
const nextGroupIds = removeFromSelectedGroups(
|
||||||
element.groupIds,
|
element.groupIds,
|
||||||
appState.selectedGroupIds,
|
appState.selectedGroupIds,
|
||||||
@@ -160,11 +169,19 @@ export const actionUngroup = register({
|
|||||||
groupIds: nextGroupIds,
|
groupIds: nextGroupIds,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const updateAppState = selectGroupsForSelectedElements(
|
||||||
|
{ ...appState, selectedGroupIds: {} },
|
||||||
|
getNonDeletedElements(nextElements),
|
||||||
|
);
|
||||||
|
|
||||||
|
// remove binded text elements from selection
|
||||||
|
boundTextElementIds.forEach(
|
||||||
|
(id) => (updateAppState.selectedElementIds[id] = false),
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
appState: selectGroupsForSelectedElements(
|
appState: updateAppState,
|
||||||
{ ...appState, selectedGroupIds: {} },
|
|
||||||
getNonDeletedElements(nextElements),
|
|
||||||
),
|
|
||||||
elements: nextElements,
|
elements: nextElements,
|
||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,9 +6,9 @@ import History, { HistoryEntry } from "../history";
|
|||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { isWindows, KEYS } from "../keys";
|
import { isWindows, KEYS } from "../keys";
|
||||||
import { getElementMap } from "../element";
|
|
||||||
import { newElementWith } from "../element/mutateElement";
|
import { newElementWith } from "../element/mutateElement";
|
||||||
import { fixBindingsAfterDeletion } from "../element/binding";
|
import { fixBindingsAfterDeletion } from "../element/binding";
|
||||||
|
import { arrayToMap } from "../utils";
|
||||||
|
|
||||||
const writeData = (
|
const writeData = (
|
||||||
prevElements: readonly ExcalidrawElement[],
|
prevElements: readonly ExcalidrawElement[],
|
||||||
@@ -27,17 +27,17 @@ const writeData = (
|
|||||||
return { commitToHistory };
|
return { commitToHistory };
|
||||||
}
|
}
|
||||||
|
|
||||||
const prevElementMap = getElementMap(prevElements);
|
const prevElementMap = arrayToMap(prevElements);
|
||||||
const nextElements = data.elements;
|
const nextElements = data.elements;
|
||||||
const nextElementMap = getElementMap(nextElements);
|
const nextElementMap = arrayToMap(nextElements);
|
||||||
|
|
||||||
const deletedElements = prevElements.filter(
|
const deletedElements = prevElements.filter(
|
||||||
(prevElement) => !nextElementMap.hasOwnProperty(prevElement.id),
|
(prevElement) => !nextElementMap.has(prevElement.id),
|
||||||
);
|
);
|
||||||
const elements = nextElements
|
const elements = nextElements
|
||||||
.map((nextElement) =>
|
.map((nextElement) =>
|
||||||
newElementWith(
|
newElementWith(
|
||||||
prevElementMap[nextElement.id] || nextElement,
|
prevElementMap.get(nextElement.id) || nextElement,
|
||||||
nextElement,
|
nextElement,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -30,19 +30,31 @@ import {
|
|||||||
TextAlignCenterIcon,
|
TextAlignCenterIcon,
|
||||||
TextAlignLeftIcon,
|
TextAlignLeftIcon,
|
||||||
TextAlignRightIcon,
|
TextAlignRightIcon,
|
||||||
|
TextAlignTopIcon,
|
||||||
|
TextAlignBottomIcon,
|
||||||
|
TextAlignMiddleIcon,
|
||||||
} from "../components/icons";
|
} from "../components/icons";
|
||||||
import {
|
import {
|
||||||
DEFAULT_FONT_FAMILY,
|
DEFAULT_FONT_FAMILY,
|
||||||
DEFAULT_FONT_SIZE,
|
DEFAULT_FONT_SIZE,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
|
VERTICAL_ALIGN,
|
||||||
} from "../constants";
|
} from "../constants";
|
||||||
import {
|
import {
|
||||||
getNonDeletedElements,
|
getNonDeletedElements,
|
||||||
isTextElement,
|
isTextElement,
|
||||||
redrawTextBoundingBox,
|
redrawTextBoundingBox,
|
||||||
} from "../element";
|
} from "../element";
|
||||||
import { newElementWith } from "../element/mutateElement";
|
import { mutateElement, newElementWith } from "../element/mutateElement";
|
||||||
import { isLinearElement, isLinearElementType } from "../element/typeChecks";
|
import {
|
||||||
|
getBoundTextElement,
|
||||||
|
getContainerElement,
|
||||||
|
} from "../element/textElement";
|
||||||
|
import {
|
||||||
|
isBoundToContainer,
|
||||||
|
isLinearElement,
|
||||||
|
isLinearElementType,
|
||||||
|
} from "../element/typeChecks";
|
||||||
import {
|
import {
|
||||||
Arrowhead,
|
Arrowhead,
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
@@ -50,27 +62,37 @@ import {
|
|||||||
ExcalidrawTextElement,
|
ExcalidrawTextElement,
|
||||||
FontFamilyValues,
|
FontFamilyValues,
|
||||||
TextAlign,
|
TextAlign,
|
||||||
|
VerticalAlign,
|
||||||
} from "../element/types";
|
} from "../element/types";
|
||||||
import { getLanguage, t } from "../i18n";
|
import { getLanguage, t } from "../i18n";
|
||||||
|
import { KEYS } from "../keys";
|
||||||
import { randomInteger } from "../random";
|
import { randomInteger } from "../random";
|
||||||
import {
|
import {
|
||||||
canChangeSharpness,
|
canChangeSharpness,
|
||||||
canHaveArrowheads,
|
canHaveArrowheads,
|
||||||
getCommonAttributeOfSelectedElements,
|
getCommonAttributeOfSelectedElements,
|
||||||
|
getSelectedElements,
|
||||||
getTargetElements,
|
getTargetElements,
|
||||||
isSomeElementSelected,
|
isSomeElementSelected,
|
||||||
} from "../scene";
|
} from "../scene";
|
||||||
import { hasStrokeColor } from "../scene/comparisons";
|
import { hasStrokeColor } from "../scene/comparisons";
|
||||||
|
import { arrayToMap } from "../utils";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
|
|
||||||
|
const FONT_SIZE_RELATIVE_INCREASE_STEP = 0.1;
|
||||||
|
|
||||||
const changeProperty = (
|
const changeProperty = (
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
callback: (element: ExcalidrawElement) => ExcalidrawElement,
|
callback: (element: ExcalidrawElement) => ExcalidrawElement,
|
||||||
|
includeBoundText = false,
|
||||||
) => {
|
) => {
|
||||||
|
const selectedElementIds = arrayToMap(
|
||||||
|
getSelectedElements(elements, appState, includeBoundText),
|
||||||
|
);
|
||||||
return elements.map((element) => {
|
return elements.map((element) => {
|
||||||
if (
|
if (
|
||||||
appState.selectedElementIds[element.id] ||
|
selectedElementIds.get(element.id) ||
|
||||||
element.id === appState.editingElement?.id
|
element.id === appState.editingElement?.id
|
||||||
) {
|
) {
|
||||||
return callback(element);
|
return callback(element);
|
||||||
@@ -100,18 +122,97 @@ const getFormValue = function <T>(
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const offsetElementAfterFontResize = (
|
||||||
|
prevElement: ExcalidrawTextElement,
|
||||||
|
nextElement: ExcalidrawTextElement,
|
||||||
|
) => {
|
||||||
|
if (isBoundToContainer(nextElement)) {
|
||||||
|
return nextElement;
|
||||||
|
}
|
||||||
|
return mutateElement(
|
||||||
|
nextElement,
|
||||||
|
{
|
||||||
|
x:
|
||||||
|
prevElement.textAlign === "left"
|
||||||
|
? prevElement.x
|
||||||
|
: prevElement.x +
|
||||||
|
(prevElement.width - nextElement.width) /
|
||||||
|
(prevElement.textAlign === "center" ? 2 : 1),
|
||||||
|
// centering vertically is non-standard, but for Excalidraw I think
|
||||||
|
// it makes sense
|
||||||
|
y: prevElement.y + (prevElement.height - nextElement.height) / 2,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const changeFontSize = (
|
||||||
|
elements: readonly ExcalidrawElement[],
|
||||||
|
appState: AppState,
|
||||||
|
getNewFontSize: (element: ExcalidrawTextElement) => number,
|
||||||
|
fallbackValue?: ExcalidrawTextElement["fontSize"],
|
||||||
|
) => {
|
||||||
|
const newFontSizes = new Set<number>();
|
||||||
|
|
||||||
|
return {
|
||||||
|
elements: changeProperty(
|
||||||
|
elements,
|
||||||
|
appState,
|
||||||
|
(oldElement) => {
|
||||||
|
if (isTextElement(oldElement)) {
|
||||||
|
const newFontSize = getNewFontSize(oldElement);
|
||||||
|
newFontSizes.add(newFontSize);
|
||||||
|
|
||||||
|
let newElement: ExcalidrawTextElement = newElementWith(oldElement, {
|
||||||
|
fontSize: newFontSize,
|
||||||
|
});
|
||||||
|
redrawTextBoundingBox(
|
||||||
|
newElement,
|
||||||
|
getContainerElement(oldElement),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
|
||||||
|
newElement = offsetElementAfterFontResize(oldElement, newElement);
|
||||||
|
|
||||||
|
return newElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
return oldElement;
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
appState: {
|
||||||
|
...appState,
|
||||||
|
// update state only if we've set all select text elements to
|
||||||
|
// the same font size
|
||||||
|
currentItemFontSize:
|
||||||
|
newFontSizes.size === 1
|
||||||
|
? [...newFontSizes][0]
|
||||||
|
: fallbackValue ?? appState.currentItemFontSize,
|
||||||
|
},
|
||||||
|
commitToHistory: true,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
export const actionChangeStrokeColor = register({
|
export const actionChangeStrokeColor = register({
|
||||||
name: "changeStrokeColor",
|
name: "changeStrokeColor",
|
||||||
perform: (elements, appState, value) => {
|
perform: (elements, appState, value) => {
|
||||||
return {
|
return {
|
||||||
...(value.currentItemStrokeColor && {
|
...(value.currentItemStrokeColor && {
|
||||||
elements: changeProperty(elements, appState, (el) => {
|
elements: changeProperty(
|
||||||
return hasStrokeColor(el.type)
|
elements,
|
||||||
? newElementWith(el, {
|
appState,
|
||||||
strokeColor: value.currentItemStrokeColor,
|
(el) => {
|
||||||
})
|
return hasStrokeColor(el.type)
|
||||||
: el;
|
? newElementWith(el, {
|
||||||
}),
|
strokeColor: value.currentItemStrokeColor,
|
||||||
|
})
|
||||||
|
: el;
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
}),
|
}),
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
@@ -137,6 +238,8 @@ export const actionChangeStrokeColor = register({
|
|||||||
setActive={(active) =>
|
setActive={(active) =>
|
||||||
updateData({ openPopup: active ? "strokeColorPicker" : null })
|
updateData({ openPopup: active ? "strokeColorPicker" : null })
|
||||||
}
|
}
|
||||||
|
elements={elements}
|
||||||
|
appState={appState}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
@@ -177,6 +280,8 @@ export const actionChangeBackgroundColor = register({
|
|||||||
setActive={(active) =>
|
setActive={(active) =>
|
||||||
updateData({ openPopup: active ? "backgroundColorPicker" : null })
|
updateData({ openPopup: active ? "backgroundColorPicker" : null })
|
||||||
}
|
}
|
||||||
|
elements={elements}
|
||||||
|
appState={appState}
|
||||||
/>
|
/>
|
||||||
</>
|
</>
|
||||||
),
|
),
|
||||||
@@ -425,24 +530,7 @@ export const actionChangeOpacity = register({
|
|||||||
export const actionChangeFontSize = register({
|
export const actionChangeFontSize = register({
|
||||||
name: "changeFontSize",
|
name: "changeFontSize",
|
||||||
perform: (elements, appState, value) => {
|
perform: (elements, appState, value) => {
|
||||||
return {
|
return changeFontSize(elements, appState, () => value, value);
|
||||||
elements: changeProperty(elements, appState, (el) => {
|
|
||||||
if (isTextElement(el)) {
|
|
||||||
const element: ExcalidrawTextElement = newElementWith(el, {
|
|
||||||
fontSize: value,
|
|
||||||
});
|
|
||||||
redrawTextBoundingBox(element);
|
|
||||||
return element;
|
|
||||||
}
|
|
||||||
|
|
||||||
return el;
|
|
||||||
}),
|
|
||||||
appState: {
|
|
||||||
...appState,
|
|
||||||
currentItemFontSize: value,
|
|
||||||
},
|
|
||||||
commitToHistory: true,
|
|
||||||
};
|
|
||||||
},
|
},
|
||||||
PanelComponent: ({ elements, appState, updateData }) => (
|
PanelComponent: ({ elements, appState, updateData }) => (
|
||||||
<fieldset>
|
<fieldset>
|
||||||
@@ -454,27 +542,40 @@ export const actionChangeFontSize = register({
|
|||||||
value: 16,
|
value: 16,
|
||||||
text: t("labels.small"),
|
text: t("labels.small"),
|
||||||
icon: <FontSizeSmallIcon theme={appState.theme} />,
|
icon: <FontSizeSmallIcon theme={appState.theme} />,
|
||||||
|
testId: "fontSize-small",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
value: 20,
|
value: 20,
|
||||||
text: t("labels.medium"),
|
text: t("labels.medium"),
|
||||||
icon: <FontSizeMediumIcon theme={appState.theme} />,
|
icon: <FontSizeMediumIcon theme={appState.theme} />,
|
||||||
|
testId: "fontSize-medium",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
value: 28,
|
value: 28,
|
||||||
text: t("labels.large"),
|
text: t("labels.large"),
|
||||||
icon: <FontSizeLargeIcon theme={appState.theme} />,
|
icon: <FontSizeLargeIcon theme={appState.theme} />,
|
||||||
|
testId: "fontSize-large",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
value: 36,
|
value: 36,
|
||||||
text: t("labels.veryLarge"),
|
text: t("labels.veryLarge"),
|
||||||
icon: <FontSizeExtraLargeIcon theme={appState.theme} />,
|
icon: <FontSizeExtraLargeIcon theme={appState.theme} />,
|
||||||
|
testId: "fontSize-veryLarge",
|
||||||
},
|
},
|
||||||
]}
|
]}
|
||||||
value={getFormValue(
|
value={getFormValue(
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState,
|
||||||
(element) => isTextElement(element) && element.fontSize,
|
(element) => {
|
||||||
|
if (isTextElement(element)) {
|
||||||
|
return element.fontSize;
|
||||||
|
}
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
if (boundTextElement) {
|
||||||
|
return boundTextElement.fontSize;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
appState.currentItemFontSize || DEFAULT_FONT_SIZE,
|
appState.currentItemFontSize || DEFAULT_FONT_SIZE,
|
||||||
)}
|
)}
|
||||||
onChange={(value) => updateData(value)}
|
onChange={(value) => updateData(value)}
|
||||||
@@ -483,21 +584,71 @@ export const actionChangeFontSize = register({
|
|||||||
),
|
),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const actionDecreaseFontSize = register({
|
||||||
|
name: "decreaseFontSize",
|
||||||
|
perform: (elements, appState, value) => {
|
||||||
|
return changeFontSize(elements, appState, (element) =>
|
||||||
|
Math.round(
|
||||||
|
// get previous value before relative increase (doesn't work fully
|
||||||
|
// due to rounding and float precision issues)
|
||||||
|
(1 / (1 + FONT_SIZE_RELATIVE_INCREASE_STEP)) * element.fontSize,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
keyTest: (event) => {
|
||||||
|
return (
|
||||||
|
event[KEYS.CTRL_OR_CMD] &&
|
||||||
|
event.shiftKey &&
|
||||||
|
// KEYS.COMMA needed for MacOS
|
||||||
|
(event.key === KEYS.CHEVRON_LEFT || event.key === KEYS.COMMA)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const actionIncreaseFontSize = register({
|
||||||
|
name: "increaseFontSize",
|
||||||
|
perform: (elements, appState, value) => {
|
||||||
|
return changeFontSize(elements, appState, (element) =>
|
||||||
|
Math.round(element.fontSize * (1 + FONT_SIZE_RELATIVE_INCREASE_STEP)),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
keyTest: (event) => {
|
||||||
|
return (
|
||||||
|
event[KEYS.CTRL_OR_CMD] &&
|
||||||
|
event.shiftKey &&
|
||||||
|
// KEYS.PERIOD needed for MacOS
|
||||||
|
(event.key === KEYS.CHEVRON_RIGHT || event.key === KEYS.PERIOD)
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
export const actionChangeFontFamily = register({
|
export const actionChangeFontFamily = register({
|
||||||
name: "changeFontFamily",
|
name: "changeFontFamily",
|
||||||
perform: (elements, appState, value) => {
|
perform: (elements, appState, value) => {
|
||||||
return {
|
return {
|
||||||
elements: changeProperty(elements, appState, (el) => {
|
elements: changeProperty(
|
||||||
if (isTextElement(el)) {
|
elements,
|
||||||
const element: ExcalidrawTextElement = newElementWith(el, {
|
appState,
|
||||||
fontFamily: value,
|
(oldElement) => {
|
||||||
});
|
if (isTextElement(oldElement)) {
|
||||||
redrawTextBoundingBox(element);
|
const newElement: ExcalidrawTextElement = newElementWith(
|
||||||
return element;
|
oldElement,
|
||||||
}
|
{
|
||||||
|
fontFamily: value,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
redrawTextBoundingBox(
|
||||||
|
newElement,
|
||||||
|
getContainerElement(oldElement),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
return newElement;
|
||||||
|
}
|
||||||
|
|
||||||
return el;
|
return oldElement;
|
||||||
}),
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
currentItemFontFamily: value,
|
currentItemFontFamily: value,
|
||||||
@@ -537,7 +688,16 @@ export const actionChangeFontFamily = register({
|
|||||||
value={getFormValue(
|
value={getFormValue(
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState,
|
||||||
(element) => isTextElement(element) && element.fontFamily,
|
(element) => {
|
||||||
|
if (isTextElement(element)) {
|
||||||
|
return element.fontFamily;
|
||||||
|
}
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
if (boundTextElement) {
|
||||||
|
return boundTextElement.fontFamily;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
appState.currentItemFontFamily || DEFAULT_FONT_FAMILY,
|
appState.currentItemFontFamily || DEFAULT_FONT_FAMILY,
|
||||||
)}
|
)}
|
||||||
onChange={(value) => updateData(value)}
|
onChange={(value) => updateData(value)}
|
||||||
@@ -551,17 +711,27 @@ export const actionChangeTextAlign = register({
|
|||||||
name: "changeTextAlign",
|
name: "changeTextAlign",
|
||||||
perform: (elements, appState, value) => {
|
perform: (elements, appState, value) => {
|
||||||
return {
|
return {
|
||||||
elements: changeProperty(elements, appState, (el) => {
|
elements: changeProperty(
|
||||||
if (isTextElement(el)) {
|
elements,
|
||||||
const element: ExcalidrawTextElement = newElementWith(el, {
|
appState,
|
||||||
textAlign: value,
|
(oldElement) => {
|
||||||
});
|
if (isTextElement(oldElement)) {
|
||||||
redrawTextBoundingBox(element);
|
const newElement: ExcalidrawTextElement = newElementWith(
|
||||||
return element;
|
oldElement,
|
||||||
}
|
{ textAlign: value },
|
||||||
|
);
|
||||||
|
redrawTextBoundingBox(
|
||||||
|
newElement,
|
||||||
|
getContainerElement(oldElement),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
return newElement;
|
||||||
|
}
|
||||||
|
|
||||||
return el;
|
return oldElement;
|
||||||
}),
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
appState: {
|
appState: {
|
||||||
...appState,
|
...appState,
|
||||||
currentItemTextAlign: value,
|
currentItemTextAlign: value,
|
||||||
@@ -569,38 +739,119 @@ export const actionChangeTextAlign = register({
|
|||||||
commitToHistory: true,
|
commitToHistory: true,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
PanelComponent: ({ elements, appState, updateData }) => (
|
PanelComponent: ({ elements, appState, updateData }) => {
|
||||||
<fieldset>
|
return (
|
||||||
<legend>{t("labels.textAlign")}</legend>
|
<fieldset>
|
||||||
<ButtonIconSelect<TextAlign | false>
|
<legend>{t("labels.textAlign")}</legend>
|
||||||
group="text-align"
|
<ButtonIconSelect<TextAlign | false>
|
||||||
options={[
|
group="text-align"
|
||||||
{
|
options={[
|
||||||
value: "left",
|
{
|
||||||
text: t("labels.left"),
|
value: "left",
|
||||||
icon: <TextAlignLeftIcon theme={appState.theme} />,
|
text: t("labels.left"),
|
||||||
},
|
icon: <TextAlignLeftIcon theme={appState.theme} />,
|
||||||
{
|
},
|
||||||
value: "center",
|
{
|
||||||
text: t("labels.center"),
|
value: "center",
|
||||||
icon: <TextAlignCenterIcon theme={appState.theme} />,
|
text: t("labels.center"),
|
||||||
},
|
icon: <TextAlignCenterIcon theme={appState.theme} />,
|
||||||
{
|
},
|
||||||
value: "right",
|
{
|
||||||
text: t("labels.right"),
|
value: "right",
|
||||||
icon: <TextAlignRightIcon theme={appState.theme} />,
|
text: t("labels.right"),
|
||||||
},
|
icon: <TextAlignRightIcon theme={appState.theme} />,
|
||||||
]}
|
},
|
||||||
value={getFormValue(
|
]}
|
||||||
elements,
|
value={getFormValue(
|
||||||
appState,
|
elements,
|
||||||
(element) => isTextElement(element) && element.textAlign,
|
appState,
|
||||||
appState.currentItemTextAlign,
|
(element) => {
|
||||||
)}
|
if (isTextElement(element)) {
|
||||||
onChange={(value) => updateData(value)}
|
return element.textAlign;
|
||||||
/>
|
}
|
||||||
</fieldset>
|
const boundTextElement = getBoundTextElement(element);
|
||||||
),
|
if (boundTextElement) {
|
||||||
|
return boundTextElement.textAlign;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
appState.currentItemTextAlign,
|
||||||
|
)}
|
||||||
|
onChange={(value) => updateData(value)}
|
||||||
|
/>
|
||||||
|
</fieldset>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
export const actionChangeVerticalAlign = register({
|
||||||
|
name: "changeVerticalAlign",
|
||||||
|
perform: (elements, appState, value) => {
|
||||||
|
return {
|
||||||
|
elements: changeProperty(
|
||||||
|
elements,
|
||||||
|
appState,
|
||||||
|
(oldElement) => {
|
||||||
|
if (isTextElement(oldElement)) {
|
||||||
|
const newElement: ExcalidrawTextElement = newElementWith(
|
||||||
|
oldElement,
|
||||||
|
{ verticalAlign: value },
|
||||||
|
);
|
||||||
|
|
||||||
|
redrawTextBoundingBox(
|
||||||
|
newElement,
|
||||||
|
getContainerElement(oldElement),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
return newElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
return oldElement;
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
appState: {
|
||||||
|
...appState,
|
||||||
|
},
|
||||||
|
commitToHistory: true,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
PanelComponent: ({ elements, appState, updateData }) => {
|
||||||
|
return (
|
||||||
|
<fieldset>
|
||||||
|
<ButtonIconSelect<VerticalAlign | false>
|
||||||
|
group="text-align"
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
value: VERTICAL_ALIGN.TOP,
|
||||||
|
text: t("labels.alignTop"),
|
||||||
|
icon: <TextAlignTopIcon theme={appState.theme} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: VERTICAL_ALIGN.MIDDLE,
|
||||||
|
text: t("labels.centerVertically"),
|
||||||
|
icon: <TextAlignMiddleIcon theme={appState.theme} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: VERTICAL_ALIGN.BOTTOM,
|
||||||
|
text: t("labels.alignBottom"),
|
||||||
|
icon: <TextAlignBottomIcon theme={appState.theme} />,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
value={getFormValue(elements, appState, (element) => {
|
||||||
|
if (isTextElement(element) && element.containerId) {
|
||||||
|
return element.verticalAlign;
|
||||||
|
}
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
if (boundTextElement) {
|
||||||
|
return boundTextElement.verticalAlign;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
})}
|
||||||
|
onChange={(value) => updateData(value)}
|
||||||
|
/>
|
||||||
|
</fieldset>
|
||||||
|
);
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
export const actionChangeSharpness = register({
|
export const actionChangeSharpness = register({
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { KEYS } from "../keys";
|
import { KEYS } from "../keys";
|
||||||
import { register } from "./register";
|
import { register } from "./register";
|
||||||
import { selectGroupsForSelectedElements } from "../groups";
|
import { selectGroupsForSelectedElements } from "../groups";
|
||||||
import { getNonDeletedElements } from "../element";
|
import { getNonDeletedElements, isTextElement } from "../element";
|
||||||
|
|
||||||
export const actionSelectAll = register({
|
export const actionSelectAll = register({
|
||||||
name: "selectAll",
|
name: "selectAll",
|
||||||
@@ -15,7 +15,10 @@ export const actionSelectAll = register({
|
|||||||
...appState,
|
...appState,
|
||||||
editingGroupId: null,
|
editingGroupId: null,
|
||||||
selectedElementIds: elements.reduce((map, element) => {
|
selectedElementIds: elements.reduce((map, element) => {
|
||||||
if (!element.isDeleted) {
|
if (
|
||||||
|
!element.isDeleted &&
|
||||||
|
!(isTextElement(element) && element.containerId)
|
||||||
|
) {
|
||||||
map[element.id] = true;
|
map[element.id] = true;
|
||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import ExcalidrawApp from "../excalidraw-app";
|
||||||
|
import { t } from "../i18n";
|
||||||
|
import { CODES } from "../keys";
|
||||||
|
import { API } from "../tests/helpers/api";
|
||||||
|
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
|
||||||
|
import { fireEvent, render, screen } from "../tests/test-utils";
|
||||||
|
import { copiedStyles } from "./actionStyles";
|
||||||
|
|
||||||
|
const { h } = window;
|
||||||
|
|
||||||
|
const mouse = new Pointer("mouse");
|
||||||
|
|
||||||
|
describe("actionStyles", () => {
|
||||||
|
beforeEach(async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
});
|
||||||
|
it("should copy & paste styles via keyboard", () => {
|
||||||
|
UI.clickTool("rectangle");
|
||||||
|
mouse.down(10, 10);
|
||||||
|
mouse.up(20, 20);
|
||||||
|
|
||||||
|
UI.clickTool("rectangle");
|
||||||
|
mouse.down(10, 10);
|
||||||
|
mouse.up(20, 20);
|
||||||
|
|
||||||
|
// Change some styles of second rectangle
|
||||||
|
UI.clickLabeledElement("Stroke");
|
||||||
|
UI.clickLabeledElement(t("colors.c92a2a"));
|
||||||
|
UI.clickLabeledElement("Background");
|
||||||
|
UI.clickLabeledElement(t("colors.e64980"));
|
||||||
|
// Fill style
|
||||||
|
fireEvent.click(screen.getByTitle("Cross-hatch"));
|
||||||
|
// Stroke width
|
||||||
|
fireEvent.click(screen.getByTitle("Bold"));
|
||||||
|
// Stroke style
|
||||||
|
fireEvent.click(screen.getByTitle("Dotted"));
|
||||||
|
// Roughness
|
||||||
|
fireEvent.click(screen.getByTitle("Cartoonist"));
|
||||||
|
// Opacity
|
||||||
|
fireEvent.change(screen.getByLabelText("Opacity"), {
|
||||||
|
target: { value: "60" },
|
||||||
|
});
|
||||||
|
|
||||||
|
mouse.reset();
|
||||||
|
|
||||||
|
API.setSelectedElements([h.elements[1]]);
|
||||||
|
|
||||||
|
Keyboard.withModifierKeys({ ctrl: true, alt: true }, () => {
|
||||||
|
Keyboard.codeDown(CODES.C);
|
||||||
|
});
|
||||||
|
const secondRect = JSON.parse(copiedStyles);
|
||||||
|
expect(secondRect.id).toBe(h.elements[1].id);
|
||||||
|
|
||||||
|
mouse.reset();
|
||||||
|
// Paste styles to first rectangle
|
||||||
|
API.setSelectedElements([h.elements[0]]);
|
||||||
|
Keyboard.withModifierKeys({ ctrl: true, alt: true }, () => {
|
||||||
|
Keyboard.codeDown(CODES.V);
|
||||||
|
});
|
||||||
|
|
||||||
|
const firstRect = API.getSelectedElement();
|
||||||
|
expect(firstRect.id).toBe(h.elements[0].id);
|
||||||
|
expect(firstRect.strokeColor).toBe("#c92a2a");
|
||||||
|
expect(firstRect.backgroundColor).toBe("#e64980");
|
||||||
|
expect(firstRect.fillStyle).toBe("cross-hatch");
|
||||||
|
expect(firstRect.strokeWidth).toBe(2); // Bold: 2
|
||||||
|
expect(firstRect.strokeStyle).toBe("dotted");
|
||||||
|
expect(firstRect.roughness).toBe(2); // Cartoonist: 2
|
||||||
|
expect(firstRect.opacity).toBe(60);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
DEFAULT_FONT_FAMILY,
|
DEFAULT_FONT_FAMILY,
|
||||||
DEFAULT_TEXT_ALIGN,
|
DEFAULT_TEXT_ALIGN,
|
||||||
} from "../constants";
|
} from "../constants";
|
||||||
|
import { getContainerElement } from "../element/textElement";
|
||||||
|
|
||||||
// `copiedStyles` is exported only for tests.
|
// `copiedStyles` is exported only for tests.
|
||||||
export let copiedStyles: string = "{}";
|
export let copiedStyles: string = "{}";
|
||||||
@@ -55,13 +56,18 @@ export const actionPasteStyles = register({
|
|||||||
opacity: pastedElement?.opacity,
|
opacity: pastedElement?.opacity,
|
||||||
roughness: pastedElement?.roughness,
|
roughness: pastedElement?.roughness,
|
||||||
});
|
});
|
||||||
if (isTextElement(newElement)) {
|
if (isTextElement(newElement) && isTextElement(element)) {
|
||||||
mutateElement(newElement, {
|
mutateElement(newElement, {
|
||||||
fontSize: pastedElement?.fontSize || DEFAULT_FONT_SIZE,
|
fontSize: pastedElement?.fontSize || DEFAULT_FONT_SIZE,
|
||||||
fontFamily: pastedElement?.fontFamily || DEFAULT_FONT_FAMILY,
|
fontFamily: pastedElement?.fontFamily || DEFAULT_FONT_FAMILY,
|
||||||
textAlign: pastedElement?.textAlign || DEFAULT_TEXT_ALIGN,
|
textAlign: pastedElement?.textAlign || DEFAULT_TEXT_ALIGN,
|
||||||
});
|
});
|
||||||
redrawTextBoundingBox(newElement);
|
|
||||||
|
redrawTextBoundingBox(
|
||||||
|
newElement,
|
||||||
|
getContainerElement(newElement),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return newElement;
|
return newElement;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { getNonDeletedElements } from "../element";
|
||||||
|
import { mutateElement } from "../element/mutateElement";
|
||||||
|
import { getBoundTextElement, measureText } from "../element/textElement";
|
||||||
|
import { ExcalidrawTextElement } from "../element/types";
|
||||||
|
import { getSelectedElements } from "../scene";
|
||||||
|
import { getFontString } from "../utils";
|
||||||
|
import { register } from "./register";
|
||||||
|
|
||||||
|
export const actionUnbindText = register({
|
||||||
|
name: "unbindText",
|
||||||
|
contextItemLabel: "labels.unbindText",
|
||||||
|
perform: (elements, appState) => {
|
||||||
|
const selectedElements = getSelectedElements(
|
||||||
|
getNonDeletedElements(elements),
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
selectedElements.forEach((element) => {
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
if (boundTextElement) {
|
||||||
|
const { width, height, baseline } = measureText(
|
||||||
|
boundTextElement.originalText,
|
||||||
|
getFontString(boundTextElement),
|
||||||
|
);
|
||||||
|
mutateElement(boundTextElement as ExcalidrawTextElement, {
|
||||||
|
containerId: null,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
baseline,
|
||||||
|
text: boundTextElement.originalText,
|
||||||
|
});
|
||||||
|
mutateElement(element, {
|
||||||
|
boundElements: element.boundElements?.filter(
|
||||||
|
(ele) => ele.id !== boundTextElement.id,
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
elements,
|
||||||
|
appState,
|
||||||
|
commitToHistory: true,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -17,6 +17,7 @@ export {
|
|||||||
actionChangeFontSize,
|
actionChangeFontSize,
|
||||||
actionChangeFontFamily,
|
actionChangeFontFamily,
|
||||||
actionChangeTextAlign,
|
actionChangeTextAlign,
|
||||||
|
actionChangeVerticalAlign,
|
||||||
} from "./actionProperties";
|
} from "./actionProperties";
|
||||||
|
|
||||||
export {
|
export {
|
||||||
@@ -80,3 +81,5 @@ export { actionToggleGridMode } from "./actionToggleGridMode";
|
|||||||
export { actionToggleZenMode } from "./actionToggleZenMode";
|
export { actionToggleZenMode } from "./actionToggleZenMode";
|
||||||
|
|
||||||
export { actionToggleStats } from "./actionToggleStats";
|
export { actionToggleStats } from "./actionToggleStats";
|
||||||
|
export { actionUnbindText } from "./actionUnbindText";
|
||||||
|
export { actionLink } from "../element/Hyperlink";
|
||||||
|
|||||||
+37
-1
@@ -10,6 +10,31 @@ import {
|
|||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { AppClassProperties, AppState } from "../types";
|
import { AppClassProperties, AppState } from "../types";
|
||||||
import { MODES } from "../constants";
|
import { MODES } from "../constants";
|
||||||
|
import { trackEvent } from "../analytics";
|
||||||
|
|
||||||
|
const trackAction = (
|
||||||
|
action: Action,
|
||||||
|
source: "ui" | "keyboard" | "api",
|
||||||
|
value: any,
|
||||||
|
) => {
|
||||||
|
if (action.trackEvent !== false) {
|
||||||
|
try {
|
||||||
|
if (action.trackEvent === true) {
|
||||||
|
trackEvent(
|
||||||
|
action.name,
|
||||||
|
source,
|
||||||
|
typeof value === "number" || typeof value === "string"
|
||||||
|
? String(value)
|
||||||
|
: undefined,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
action.trackEvent?.(action, source, value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("error while logging action:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export class ActionManager implements ActionsManagerInterface {
|
export class ActionManager implements ActionsManagerInterface {
|
||||||
actions = {} as ActionsManagerInterface["actions"];
|
actions = {} as ActionsManagerInterface["actions"];
|
||||||
@@ -65,9 +90,15 @@ export class ActionManager implements ActionsManagerInterface {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (data.length === 0) {
|
if (data.length !== 1) {
|
||||||
|
if (data.length > 1) {
|
||||||
|
console.warn("Canceling as multiple actions match this shortcut", data);
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const action = data[0];
|
||||||
|
|
||||||
const { viewModeEnabled } = this.getAppState();
|
const { viewModeEnabled } = this.getAppState();
|
||||||
if (viewModeEnabled) {
|
if (viewModeEnabled) {
|
||||||
if (!Object.values(MODES).includes(data[0].name)) {
|
if (!Object.values(MODES).includes(data[0].name)) {
|
||||||
@@ -75,6 +106,8 @@ export class ActionManager implements ActionsManagerInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
trackAction(action, "keyboard", null);
|
||||||
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
this.updater(
|
this.updater(
|
||||||
data[0].perform(
|
data[0].perform(
|
||||||
@@ -96,6 +129,7 @@ export class ActionManager implements ActionsManagerInterface {
|
|||||||
this.app,
|
this.app,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
trackAction(action, "api", null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -122,6 +156,8 @@ export class ActionManager implements ActionsManagerInterface {
|
|||||||
this.app,
|
this.app,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
trackAction(action, "ui", formState);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ import { Action } from "./types";
|
|||||||
|
|
||||||
export let actions: readonly Action[] = [];
|
export let actions: readonly Action[] = [];
|
||||||
|
|
||||||
export const register = (action: Action): Action => {
|
export const register = <T extends Action>(action: T) => {
|
||||||
actions = actions.concat(action);
|
actions = actions.concat(action);
|
||||||
return action;
|
return action as T & {
|
||||||
|
keyTest?: unknown extends T["keyTest"] ? never : T["keyTest"];
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { isDarwin } from "../keys";
|
import { isDarwin } from "../keys";
|
||||||
import { getShortcutKey } from "../utils";
|
import { getShortcutKey } from "../utils";
|
||||||
|
import { ActionName } from "./types";
|
||||||
|
|
||||||
export type ShortcutName =
|
export type ShortcutName = SubtypeOf<
|
||||||
|
ActionName,
|
||||||
| "cut"
|
| "cut"
|
||||||
| "copy"
|
| "copy"
|
||||||
| "paste"
|
| "paste"
|
||||||
@@ -25,7 +27,9 @@ export type ShortcutName =
|
|||||||
| "addToLibrary"
|
| "addToLibrary"
|
||||||
| "viewMode"
|
| "viewMode"
|
||||||
| "flipHorizontal"
|
| "flipHorizontal"
|
||||||
| "flipVertical";
|
| "flipVertical"
|
||||||
|
| "hyperlink"
|
||||||
|
>;
|
||||||
|
|
||||||
const shortcutMap: Record<ShortcutName, string[]> = {
|
const shortcutMap: Record<ShortcutName, string[]> = {
|
||||||
cut: [getShortcutKey("CtrlOrCmd+X")],
|
cut: [getShortcutKey("CtrlOrCmd+X")],
|
||||||
@@ -62,10 +66,11 @@ const shortcutMap: Record<ShortcutName, string[]> = {
|
|||||||
flipHorizontal: [getShortcutKey("Shift+H")],
|
flipHorizontal: [getShortcutKey("Shift+H")],
|
||||||
flipVertical: [getShortcutKey("Shift+V")],
|
flipVertical: [getShortcutKey("Shift+V")],
|
||||||
viewMode: [getShortcutKey("Alt+R")],
|
viewMode: [getShortcutKey("Alt+R")],
|
||||||
|
hyperlink: [getShortcutKey("CtrlOrCmd+K")],
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getShortcutFromShortcutName = (name: ShortcutName) => {
|
export const getShortcutFromShortcutName = (name: ShortcutName) => {
|
||||||
const shortcuts = shortcutMap[name];
|
const shortcuts = shortcutMap[name];
|
||||||
// if multiple shortcuts availiable, take the first one
|
// if multiple shortcuts available, take the first one
|
||||||
return shortcuts && shortcuts.length > 0 ? shortcuts[0] : "";
|
return shortcuts && shortcuts.length > 0 ? shortcuts[0] : "";
|
||||||
};
|
};
|
||||||
|
|||||||
+15
-2
@@ -82,6 +82,7 @@ export type ActionName =
|
|||||||
| "zoomToSelection"
|
| "zoomToSelection"
|
||||||
| "changeFontFamily"
|
| "changeFontFamily"
|
||||||
| "changeTextAlign"
|
| "changeTextAlign"
|
||||||
|
| "changeVerticalAlign"
|
||||||
| "toggleFullScreen"
|
| "toggleFullScreen"
|
||||||
| "toggleShortcuts"
|
| "toggleShortcuts"
|
||||||
| "group"
|
| "group"
|
||||||
@@ -101,7 +102,11 @@ export type ActionName =
|
|||||||
| "flipVertical"
|
| "flipVertical"
|
||||||
| "viewMode"
|
| "viewMode"
|
||||||
| "exportWithDarkMode"
|
| "exportWithDarkMode"
|
||||||
| "toggleTheme";
|
| "toggleTheme"
|
||||||
|
| "increaseFontSize"
|
||||||
|
| "decreaseFontSize"
|
||||||
|
| "unbindText"
|
||||||
|
| "hyperlink";
|
||||||
|
|
||||||
export type PanelComponentProps = {
|
export type PanelComponentProps = {
|
||||||
elements: readonly ExcalidrawElement[];
|
elements: readonly ExcalidrawElement[];
|
||||||
@@ -121,12 +126,20 @@ export interface Action {
|
|||||||
appState: AppState,
|
appState: AppState,
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
) => boolean;
|
) => boolean;
|
||||||
contextItemLabel?: string;
|
contextItemLabel?:
|
||||||
|
| string
|
||||||
|
| ((
|
||||||
|
elements: readonly ExcalidrawElement[],
|
||||||
|
appState: Readonly<AppState>,
|
||||||
|
) => string);
|
||||||
contextItemPredicate?: (
|
contextItemPredicate?: (
|
||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
) => boolean;
|
) => boolean;
|
||||||
checked?: (appState: Readonly<AppState>) => boolean;
|
checked?: (appState: Readonly<AppState>) => boolean;
|
||||||
|
trackEvent?:
|
||||||
|
| boolean
|
||||||
|
| ((action: Action, type: "ui" | "keyboard" | "api", value: any) => void);
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ActionsManagerInterface {
|
export interface ActionsManagerInterface {
|
||||||
|
|||||||
+1
-22
@@ -1,6 +1,7 @@
|
|||||||
import { ExcalidrawElement } from "./element/types";
|
import { ExcalidrawElement } from "./element/types";
|
||||||
import { newElementWith } from "./element/mutateElement";
|
import { newElementWith } from "./element/mutateElement";
|
||||||
import { Box, getCommonBoundingBox } from "./element/bounds";
|
import { Box, getCommonBoundingBox } from "./element/bounds";
|
||||||
|
import { getMaximumGroups } from "./groups";
|
||||||
|
|
||||||
export interface Alignment {
|
export interface Alignment {
|
||||||
position: "start" | "center" | "end";
|
position: "start" | "center" | "end";
|
||||||
@@ -30,28 +31,6 @@ export const alignElements = (
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getMaximumGroups = (
|
|
||||||
elements: ExcalidrawElement[],
|
|
||||||
): ExcalidrawElement[][] => {
|
|
||||||
const groups: Map<String, ExcalidrawElement[]> = new Map<
|
|
||||||
String,
|
|
||||||
ExcalidrawElement[]
|
|
||||||
>();
|
|
||||||
|
|
||||||
elements.forEach((element: ExcalidrawElement) => {
|
|
||||||
const groupId =
|
|
||||||
element.groupIds.length === 0
|
|
||||||
? element.id
|
|
||||||
: element.groupIds[element.groupIds.length - 1];
|
|
||||||
|
|
||||||
const currentGroupMembers = groups.get(groupId) || [];
|
|
||||||
|
|
||||||
groups.set(groupId, [...currentGroupMembers, element]);
|
|
||||||
});
|
|
||||||
|
|
||||||
return Array.from(groups.values());
|
|
||||||
};
|
|
||||||
|
|
||||||
const calculateTranslation = (
|
const calculateTranslation = (
|
||||||
group: ExcalidrawElement[],
|
group: ExcalidrawElement[],
|
||||||
selectionBoundingBox: Box,
|
selectionBoundingBox: Box,
|
||||||
|
|||||||
+5
-5
@@ -3,16 +3,16 @@ export const trackEvent =
|
|||||||
process.env?.REACT_APP_GOOGLE_ANALYTICS_ID &&
|
process.env?.REACT_APP_GOOGLE_ANALYTICS_ID &&
|
||||||
typeof window !== "undefined" &&
|
typeof window !== "undefined" &&
|
||||||
window.gtag
|
window.gtag
|
||||||
? (category: string, name: string, label?: string, value?: number) => {
|
? (category: string, action: string, label?: string, value?: number) => {
|
||||||
window.gtag("event", name, {
|
window.gtag("event", action, {
|
||||||
event_category: category,
|
event_category: category,
|
||||||
event_label: label,
|
event_label: label,
|
||||||
value,
|
value,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
: typeof process !== "undefined" && process.env?.JEST_WORKER_ID
|
: typeof process !== "undefined" && process.env?.JEST_WORKER_ID
|
||||||
? (category: string, name: string, label?: string, value?: number) => {}
|
? (category: string, action: string, label?: string, value?: number) => {}
|
||||||
: (category: string, name: string, label?: string, value?: number) => {
|
: (category: string, action: string, label?: string, value?: number) => {
|
||||||
// Uncomment the next line to track locally
|
// Uncomment the next line to track locally
|
||||||
// console.info("Track Event", category, name, label, value);
|
// console.info("Track Event", category, action, label, value);
|
||||||
};
|
};
|
||||||
|
|||||||
+9
-1
@@ -43,6 +43,8 @@ export const getDefaultAppState = (): Omit<
|
|||||||
editingLinearElement: null,
|
editingLinearElement: null,
|
||||||
elementLocked: false,
|
elementLocked: false,
|
||||||
elementType: "selection",
|
elementType: "selection",
|
||||||
|
penMode: false,
|
||||||
|
penDetected: false,
|
||||||
errorMessage: null,
|
errorMessage: null,
|
||||||
exportBackground: true,
|
exportBackground: true,
|
||||||
exportScale: defaultExportScale,
|
exportScale: defaultExportScale,
|
||||||
@@ -77,9 +79,12 @@ export const getDefaultAppState = (): Omit<
|
|||||||
toastMessage: null,
|
toastMessage: null,
|
||||||
viewBackgroundColor: oc.white,
|
viewBackgroundColor: oc.white,
|
||||||
zenModeEnabled: false,
|
zenModeEnabled: false,
|
||||||
zoom: { value: 1 as NormalizedZoomValue, translation: { x: 0, y: 0 } },
|
zoom: {
|
||||||
|
value: 1 as NormalizedZoomValue,
|
||||||
|
},
|
||||||
viewModeEnabled: false,
|
viewModeEnabled: false,
|
||||||
pendingImageElement: null,
|
pendingImageElement: null,
|
||||||
|
showHyperlinkPopup: false,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -127,6 +132,8 @@ const APP_STATE_STORAGE_CONF = (<
|
|||||||
editingLinearElement: { browser: false, export: false, server: false },
|
editingLinearElement: { browser: false, export: false, server: false },
|
||||||
elementLocked: { browser: true, export: false, server: false },
|
elementLocked: { browser: true, export: false, server: false },
|
||||||
elementType: { browser: true, export: false, server: false },
|
elementType: { browser: true, export: false, server: false },
|
||||||
|
penMode: { browser: false, export: false, server: false },
|
||||||
|
penDetected: { browser: false, export: false, server: false },
|
||||||
errorMessage: { browser: false, export: false, server: false },
|
errorMessage: { browser: false, export: false, server: false },
|
||||||
exportBackground: { browser: true, export: false, server: false },
|
exportBackground: { browser: true, export: false, server: false },
|
||||||
exportEmbedScene: { browser: true, export: false, server: false },
|
exportEmbedScene: { browser: true, export: false, server: false },
|
||||||
@@ -168,6 +175,7 @@ const APP_STATE_STORAGE_CONF = (<
|
|||||||
zoom: { browser: true, export: false, server: false },
|
zoom: { browser: true, export: false, server: false },
|
||||||
viewModeEnabled: { browser: false, export: false, server: false },
|
viewModeEnabled: { browser: false, export: false, server: false },
|
||||||
pendingImageElement: { browser: false, export: false, server: false },
|
pendingImageElement: { browser: false, export: false, server: false },
|
||||||
|
showHyperlinkPopup: { browser: false, export: false, server: false },
|
||||||
});
|
});
|
||||||
|
|
||||||
const _clearAppStateForStorage = <
|
const _clearAppStateForStorage = <
|
||||||
|
|||||||
+8
-3
@@ -1,5 +1,10 @@
|
|||||||
import colors from "./colors";
|
import colors from "./colors";
|
||||||
import { DEFAULT_FONT_FAMILY, DEFAULT_FONT_SIZE, ENV } from "./constants";
|
import {
|
||||||
|
DEFAULT_FONT_FAMILY,
|
||||||
|
DEFAULT_FONT_SIZE,
|
||||||
|
ENV,
|
||||||
|
VERTICAL_ALIGN,
|
||||||
|
} from "./constants";
|
||||||
import { newElement, newLinearElement, newTextElement } from "./element";
|
import { newElement, newLinearElement, newTextElement } from "./element";
|
||||||
import { NonDeletedExcalidrawElement } from "./element/types";
|
import { NonDeletedExcalidrawElement } from "./element/types";
|
||||||
import { randomId } from "./random";
|
import { randomId } from "./random";
|
||||||
@@ -103,7 +108,7 @@ const transposeCells = (cells: string[][]) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const tryParseSpreadsheet = (text: string): ParseSpreadsheetResult => {
|
export const tryParseSpreadsheet = (text: string): ParseSpreadsheetResult => {
|
||||||
// Copy/paste from excel, spreadhseets, tsv, csv.
|
// Copy/paste from excel, spreadsheets, tsv, csv.
|
||||||
// For now we only accept 2 columns with an optional header
|
// For now we only accept 2 columns with an optional header
|
||||||
|
|
||||||
// Check for tab separated values
|
// Check for tab separated values
|
||||||
@@ -161,7 +166,7 @@ const commonProps = {
|
|||||||
strokeSharpness: "sharp",
|
strokeSharpness: "sharp",
|
||||||
strokeStyle: "solid",
|
strokeStyle: "solid",
|
||||||
strokeWidth: 1,
|
strokeWidth: 1,
|
||||||
verticalAlign: "middle",
|
verticalAlign: VERTICAL_ALIGN.MIDDLE,
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
const getChartDimentions = (spreadsheet: Spreadsheet) => {
|
const getChartDimentions = (spreadsheet: Spreadsheet) => {
|
||||||
|
|||||||
+3
-2
@@ -58,7 +58,8 @@ export const copyToClipboard = async (
|
|||||||
appState: AppState,
|
appState: AppState,
|
||||||
files: BinaryFiles,
|
files: BinaryFiles,
|
||||||
) => {
|
) => {
|
||||||
const selectedElements = getSelectedElements(elements, appState);
|
// select binded text elements when copying
|
||||||
|
const selectedElements = getSelectedElements(elements, appState, true);
|
||||||
const contents: ElementsClipboard = {
|
const contents: ElementsClipboard = {
|
||||||
type: EXPORT_DATA_TYPES.excalidrawClipboard,
|
type: EXPORT_DATA_TYPES.excalidrawClipboard,
|
||||||
elements: selectedElements,
|
elements: selectedElements,
|
||||||
@@ -123,7 +124,7 @@ const getSystemClipboard = async (
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attemps to parse clipboard. Prefers system clipboard.
|
* Attempts to parse clipboard. Prefers system clipboard.
|
||||||
*/
|
*/
|
||||||
export const parseClipboard = async (
|
export const parseClipboard = async (
|
||||||
event: ClipboardEvent | null,
|
event: ClipboardEvent | null,
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import { capitalizeString, isTransparent, setCursorForShape } from "../utils";
|
|||||||
import Stack from "./Stack";
|
import Stack from "./Stack";
|
||||||
import { ToolButton } from "./ToolButton";
|
import { ToolButton } from "./ToolButton";
|
||||||
import { hasStrokeColor } from "../scene/comparisons";
|
import { hasStrokeColor } from "../scene/comparisons";
|
||||||
|
import { hasBoundTextElement, isBoundToContainer } from "../element/typeChecks";
|
||||||
|
|
||||||
export const SelectedShapeActions = ({
|
export const SelectedShapeActions = ({
|
||||||
appState,
|
appState,
|
||||||
@@ -35,6 +36,15 @@ export const SelectedShapeActions = ({
|
|||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let isSingleElementBoundContainer = false;
|
||||||
|
if (
|
||||||
|
targetElements.length === 2 &&
|
||||||
|
(hasBoundTextElement(targetElements[0]) ||
|
||||||
|
hasBoundTextElement(targetElements[1]))
|
||||||
|
) {
|
||||||
|
isSingleElementBoundContainer = true;
|
||||||
|
}
|
||||||
const isEditing = Boolean(appState.editingElement);
|
const isEditing = Boolean(appState.editingElement);
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
const isRTL = document.documentElement.getAttribute("dir") === "rtl";
|
const isRTL = document.documentElement.getAttribute("dir") === "rtl";
|
||||||
@@ -100,6 +110,10 @@ export const SelectedShapeActions = ({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{targetElements.some(
|
||||||
|
(element) =>
|
||||||
|
hasBoundTextElement(element) || isBoundToContainer(element),
|
||||||
|
) && renderAction("changeVerticalAlign")}
|
||||||
{(canHaveArrowheads(elementType) ||
|
{(canHaveArrowheads(elementType) ||
|
||||||
targetElements.some((element) => canHaveArrowheads(element.type))) && (
|
targetElements.some((element) => canHaveArrowheads(element.type))) && (
|
||||||
<>{renderAction("changeArrowhead")}</>
|
<>{renderAction("changeArrowhead")}</>
|
||||||
@@ -117,7 +131,7 @@ export const SelectedShapeActions = ({
|
|||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
{targetElements.length > 1 && (
|
{targetElements.length > 1 && !isSingleElementBoundContainer && (
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>{t("labels.align")}</legend>
|
<legend>{t("labels.align")}</legend>
|
||||||
<div className="buttonList">
|
<div className="buttonList">
|
||||||
@@ -150,14 +164,15 @@ export const SelectedShapeActions = ({
|
|||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
)}
|
)}
|
||||||
{!isMobile && !isEditing && targetElements.length > 0 && (
|
{!isEditing && targetElements.length > 0 && (
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>{t("labels.actions")}</legend>
|
<legend>{t("labels.actions")}</legend>
|
||||||
<div className="buttonList">
|
<div className="buttonList">
|
||||||
{renderAction("duplicateSelection")}
|
{!isMobile && renderAction("duplicateSelection")}
|
||||||
{renderAction("deleteSelectedElements")}
|
{!isMobile && renderAction("deleteSelectedElements")}
|
||||||
{renderAction("group")}
|
{renderAction("group")}
|
||||||
{renderAction("ungroup")}
|
{renderAction("ungroup")}
|
||||||
|
{targetElements.length === 1 && renderAction("hyperlink")}
|
||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
)}
|
)}
|
||||||
|
|||||||
+740
-224
File diff suppressed because it is too large
Load Diff
@@ -7,7 +7,7 @@ export const ButtonIconSelect = <T extends Object>({
|
|||||||
onChange,
|
onChange,
|
||||||
group,
|
group,
|
||||||
}: {
|
}: {
|
||||||
options: { value: T; text: string; icon: JSX.Element }[];
|
options: { value: T; text: string; icon: JSX.Element; testId?: string }[];
|
||||||
value: T | null;
|
value: T | null;
|
||||||
onChange: (value: T) => void;
|
onChange: (value: T) => void;
|
||||||
group: string;
|
group: string;
|
||||||
@@ -24,6 +24,7 @@ export const ButtonIconSelect = <T extends Object>({
|
|||||||
name={group}
|
name={group}
|
||||||
onChange={() => onChange(option.value)}
|
onChange={() => onChange(option.value)}
|
||||||
checked={value === option.value}
|
checked={value === option.value}
|
||||||
|
data-testid={option.testId}
|
||||||
/>
|
/>
|
||||||
{option.icon}
|
{option.icon}
|
||||||
</label>
|
</label>
|
||||||
|
|||||||
+11
-4
@@ -3,15 +3,22 @@ import OpenColor from "open-color";
|
|||||||
import "./Card.scss";
|
import "./Card.scss";
|
||||||
|
|
||||||
export const Card: React.FC<{
|
export const Card: React.FC<{
|
||||||
color: keyof OpenColor;
|
color: keyof OpenColor | "primary";
|
||||||
}> = ({ children, color }) => {
|
}> = ({ children, color }) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="Card"
|
className="Card"
|
||||||
style={{
|
style={{
|
||||||
["--card-color" as any]: OpenColor[color][7],
|
["--card-color" as any]:
|
||||||
["--card-color-darker" as any]: OpenColor[color][8],
|
color === "primary" ? "var(--color-primary)" : OpenColor[color][7],
|
||||||
["--card-color-darkest" as any]: OpenColor[color][9],
|
["--card-color-darker" as any]:
|
||||||
|
color === "primary"
|
||||||
|
? "var(--color-primary-darker)"
|
||||||
|
: OpenColor[color][8],
|
||||||
|
["--card-color-darkest" as any]:
|
||||||
|
color === "primary"
|
||||||
|
? "var(--color-primary-darkest)"
|
||||||
|
: OpenColor[color][9],
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -6,14 +6,14 @@ import "./CheckboxItem.scss";
|
|||||||
|
|
||||||
export const CheckboxItem: React.FC<{
|
export const CheckboxItem: React.FC<{
|
||||||
checked: boolean;
|
checked: boolean;
|
||||||
onChange: (checked: boolean) => void;
|
onChange: (checked: boolean, event: React.MouseEvent) => void;
|
||||||
className?: string;
|
className?: string;
|
||||||
}> = ({ children, checked, onChange, className }) => {
|
}> = ({ children, checked, onChange, className }) => {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={clsx("Checkbox", className, { "is-checked": checked })}
|
className={clsx("Checkbox", className, { "is-checked": checked })}
|
||||||
onClick={(event) => {
|
onClick={(event) => {
|
||||||
onChange(!checked);
|
onChange(!checked, event);
|
||||||
(
|
(
|
||||||
(event.currentTarget as HTMLDivElement).querySelector(
|
(event.currentTarget as HTMLDivElement).querySelector(
|
||||||
".Checkbox-box",
|
".Checkbox-box",
|
||||||
|
|||||||
@@ -46,7 +46,7 @@
|
|||||||
top: -11px;
|
top: -11px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.color-picker-content {
|
.color-picker-content--default {
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(5, auto);
|
grid-template-columns: repeat(5, auto);
|
||||||
@@ -59,6 +59,26 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.color-picker-content--canvas {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
padding: 0.25rem;
|
||||||
|
|
||||||
|
&-title {
|
||||||
|
color: $oc-gray-6;
|
||||||
|
font-size: 12px;
|
||||||
|
padding: 0 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&-colors {
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
|
||||||
|
.color-picker-swatch {
|
||||||
|
margin: 0 0.25rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.color-picker-content .color-input-container {
|
.color-picker-content .color-input-container {
|
||||||
grid-column: 1 / span 5;
|
grid-column: 1 / span 5;
|
||||||
}
|
}
|
||||||
|
|||||||
+154
-42
@@ -7,6 +7,53 @@ import { isArrowKey, KEYS } from "../keys";
|
|||||||
import { t, getLanguage } from "../i18n";
|
import { t, getLanguage } from "../i18n";
|
||||||
import { isWritableElement } from "../utils";
|
import { isWritableElement } from "../utils";
|
||||||
import colors from "../colors";
|
import colors from "../colors";
|
||||||
|
import { ExcalidrawElement } from "../element/types";
|
||||||
|
import { AppState } from "../types";
|
||||||
|
|
||||||
|
const MAX_CUSTOM_COLORS = 5;
|
||||||
|
const MAX_DEFAULT_COLORS = 15;
|
||||||
|
|
||||||
|
export const getCustomColors = (
|
||||||
|
elements: readonly ExcalidrawElement[],
|
||||||
|
type: "elementBackground" | "elementStroke",
|
||||||
|
) => {
|
||||||
|
const customColors: string[] = [];
|
||||||
|
const updatedElements = elements
|
||||||
|
.filter((element) => !element.isDeleted)
|
||||||
|
.sort((ele1, ele2) => ele2.updated - ele1.updated);
|
||||||
|
|
||||||
|
let index = 0;
|
||||||
|
const elementColorTypeMap = {
|
||||||
|
elementBackground: "backgroundColor",
|
||||||
|
elementStroke: "strokeColor",
|
||||||
|
};
|
||||||
|
const colorType = elementColorTypeMap[type] as
|
||||||
|
| "backgroundColor"
|
||||||
|
| "strokeColor";
|
||||||
|
while (
|
||||||
|
index < updatedElements.length &&
|
||||||
|
customColors.length < MAX_CUSTOM_COLORS
|
||||||
|
) {
|
||||||
|
const element = updatedElements[index];
|
||||||
|
|
||||||
|
if (
|
||||||
|
customColors.length < MAX_CUSTOM_COLORS &&
|
||||||
|
isCustomColor(element[colorType], type) &&
|
||||||
|
!customColors.includes(element[colorType])
|
||||||
|
) {
|
||||||
|
customColors.push(element[colorType]);
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
return customColors;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isCustomColor = (
|
||||||
|
color: string,
|
||||||
|
type: "elementBackground" | "elementStroke",
|
||||||
|
) => {
|
||||||
|
return !colors[type].includes(color);
|
||||||
|
};
|
||||||
|
|
||||||
const isValidColor = (color: string) => {
|
const isValidColor = (color: string) => {
|
||||||
const style = new Option().style;
|
const style = new Option().style;
|
||||||
@@ -35,6 +82,7 @@ const keyBindings = [
|
|||||||
["1", "2", "3", "4", "5"],
|
["1", "2", "3", "4", "5"],
|
||||||
["q", "w", "e", "r", "t"],
|
["q", "w", "e", "r", "t"],
|
||||||
["a", "s", "d", "f", "g"],
|
["a", "s", "d", "f", "g"],
|
||||||
|
["z", "x", "c", "v", "b"],
|
||||||
].flat();
|
].flat();
|
||||||
|
|
||||||
const Picker = ({
|
const Picker = ({
|
||||||
@@ -45,6 +93,7 @@ const Picker = ({
|
|||||||
label,
|
label,
|
||||||
showInput = true,
|
showInput = true,
|
||||||
type,
|
type,
|
||||||
|
elements,
|
||||||
}: {
|
}: {
|
||||||
colors: string[];
|
colors: string[];
|
||||||
color: string | null;
|
color: string | null;
|
||||||
@@ -53,12 +102,20 @@ const Picker = ({
|
|||||||
label: string;
|
label: string;
|
||||||
showInput: boolean;
|
showInput: boolean;
|
||||||
type: "canvasBackground" | "elementBackground" | "elementStroke";
|
type: "canvasBackground" | "elementBackground" | "elementStroke";
|
||||||
|
elements: readonly ExcalidrawElement[];
|
||||||
}) => {
|
}) => {
|
||||||
const firstItem = React.useRef<HTMLButtonElement>();
|
const firstItem = React.useRef<HTMLButtonElement>();
|
||||||
const activeItem = React.useRef<HTMLButtonElement>();
|
const activeItem = React.useRef<HTMLButtonElement>();
|
||||||
const gallery = React.useRef<HTMLDivElement>();
|
const gallery = React.useRef<HTMLDivElement>();
|
||||||
const colorInput = React.useRef<HTMLInputElement>();
|
const colorInput = React.useRef<HTMLInputElement>();
|
||||||
|
|
||||||
|
const [customColors] = React.useState(() => {
|
||||||
|
if (type === "canvasBackground") {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return getCustomColors(elements, type);
|
||||||
|
});
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
// After the component is first mounted focus on first input
|
// After the component is first mounted focus on first input
|
||||||
if (activeItem.current) {
|
if (activeItem.current) {
|
||||||
@@ -85,23 +142,42 @@ const Picker = ({
|
|||||||
} else if (isArrowKey(event.key)) {
|
} else if (isArrowKey(event.key)) {
|
||||||
const { activeElement } = document;
|
const { activeElement } = document;
|
||||||
const isRTL = getLanguage().rtl;
|
const isRTL = getLanguage().rtl;
|
||||||
const index = Array.prototype.indexOf.call(
|
let isCustom = false;
|
||||||
gallery!.current!.children,
|
let index = Array.prototype.indexOf.call(
|
||||||
|
gallery!.current!.querySelector(".color-picker-content--default")!
|
||||||
|
.children,
|
||||||
activeElement,
|
activeElement,
|
||||||
);
|
);
|
||||||
|
if (index === -1) {
|
||||||
|
index = Array.prototype.indexOf.call(
|
||||||
|
gallery!.current!.querySelector(
|
||||||
|
".color-picker-content--canvas-colors",
|
||||||
|
)!.children,
|
||||||
|
activeElement,
|
||||||
|
);
|
||||||
|
if (index !== -1) {
|
||||||
|
isCustom = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const parentSelector = isCustom
|
||||||
|
? gallery!.current!.querySelector(
|
||||||
|
".color-picker-content--canvas-colors",
|
||||||
|
)!
|
||||||
|
: gallery!.current!.querySelector(".color-picker-content--default")!;
|
||||||
|
|
||||||
if (index !== -1) {
|
if (index !== -1) {
|
||||||
const length = gallery!.current!.children.length - (showInput ? 1 : 0);
|
const length = parentSelector!.children.length - (showInput ? 1 : 0);
|
||||||
const nextIndex =
|
const nextIndex =
|
||||||
event.key === (isRTL ? KEYS.ARROW_LEFT : KEYS.ARROW_RIGHT)
|
event.key === (isRTL ? KEYS.ARROW_LEFT : KEYS.ARROW_RIGHT)
|
||||||
? (index + 1) % length
|
? (index + 1) % length
|
||||||
: event.key === (isRTL ? KEYS.ARROW_RIGHT : KEYS.ARROW_LEFT)
|
: event.key === (isRTL ? KEYS.ARROW_RIGHT : KEYS.ARROW_LEFT)
|
||||||
? (length + index - 1) % length
|
? (length + index - 1) % length
|
||||||
: event.key === KEYS.ARROW_DOWN
|
: !isCustom && event.key === KEYS.ARROW_DOWN
|
||||||
? (index + 5) % length
|
? (index + 5) % length
|
||||||
: event.key === KEYS.ARROW_UP
|
: !isCustom && event.key === KEYS.ARROW_UP
|
||||||
? (length + index - 5) % length
|
? (length + index - 5) % length
|
||||||
: index;
|
: index;
|
||||||
(gallery!.current!.children![nextIndex] as any).focus();
|
(parentSelector!.children![nextIndex] as HTMLElement)?.focus();
|
||||||
}
|
}
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
} else if (
|
} else if (
|
||||||
@@ -109,7 +185,15 @@ const Picker = ({
|
|||||||
!isWritableElement(event.target)
|
!isWritableElement(event.target)
|
||||||
) {
|
) {
|
||||||
const index = keyBindings.indexOf(event.key.toLowerCase());
|
const index = keyBindings.indexOf(event.key.toLowerCase());
|
||||||
(gallery!.current!.children![index] as any).focus();
|
const isCustom = index >= MAX_DEFAULT_COLORS;
|
||||||
|
const parentSelector = isCustom
|
||||||
|
? gallery!.current!.querySelector(
|
||||||
|
".color-picker-content--canvas-colors",
|
||||||
|
)!
|
||||||
|
: gallery!.current!.querySelector(".color-picker-content--default")!;
|
||||||
|
const actualIndex = isCustom ? index - MAX_DEFAULT_COLORS : index;
|
||||||
|
(parentSelector!.children![actualIndex] as HTMLElement)?.focus();
|
||||||
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
} else if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
|
} else if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -119,6 +203,50 @@ const Picker = ({
|
|||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const renderColors = (colors: Array<string>, custom: boolean = false) => {
|
||||||
|
return colors.map((_color, i) => {
|
||||||
|
const _colorWithoutHash = _color.replace("#", "");
|
||||||
|
const keyBinding = custom
|
||||||
|
? keyBindings[i + MAX_DEFAULT_COLORS]
|
||||||
|
: keyBindings[i];
|
||||||
|
const label = custom
|
||||||
|
? _colorWithoutHash
|
||||||
|
: t(`colors.${_colorWithoutHash}`);
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className="color-picker-swatch"
|
||||||
|
onClick={(event) => {
|
||||||
|
(event.currentTarget as HTMLButtonElement).focus();
|
||||||
|
onChange(_color);
|
||||||
|
}}
|
||||||
|
title={`${label}${
|
||||||
|
!isTransparent(_color) ? ` (${_color})` : ""
|
||||||
|
} — ${keyBinding.toUpperCase()}`}
|
||||||
|
aria-label={label}
|
||||||
|
aria-keyshortcuts={keyBindings[i]}
|
||||||
|
style={{ color: _color }}
|
||||||
|
key={_color}
|
||||||
|
ref={(el) => {
|
||||||
|
if (!custom && el && i === 0) {
|
||||||
|
firstItem.current = el;
|
||||||
|
}
|
||||||
|
if (el && _color === color) {
|
||||||
|
activeItem.current = el;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onFocus={() => {
|
||||||
|
onChange(_color);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isTransparent(_color) ? (
|
||||||
|
<div className="color-picker-transparent"></div>
|
||||||
|
) : undefined}
|
||||||
|
<span className="color-picker-keybinding">{keyBinding}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className={`color-picker color-picker-type-${type}`}
|
className={`color-picker color-picker-type-${type}`}
|
||||||
@@ -138,41 +266,20 @@ const Picker = ({
|
|||||||
}}
|
}}
|
||||||
tabIndex={0}
|
tabIndex={0}
|
||||||
>
|
>
|
||||||
{colors.map((_color, i) => {
|
<div className="color-picker-content--default">
|
||||||
const _colorWithoutHash = _color.replace("#", "");
|
{renderColors(colors)}
|
||||||
return (
|
</div>
|
||||||
<button
|
{!!customColors.length && (
|
||||||
className="color-picker-swatch"
|
<div className="color-picker-content--canvas">
|
||||||
onClick={(event) => {
|
<span className="color-picker-content--canvas-title">
|
||||||
(event.currentTarget as HTMLButtonElement).focus();
|
{t("labels.canvasColors")}
|
||||||
onChange(_color);
|
</span>
|
||||||
}}
|
<div className="color-picker-content--canvas-colors">
|
||||||
title={`${t(`colors.${_colorWithoutHash}`)}${
|
{renderColors(customColors, true)}
|
||||||
!isTransparent(_color) ? ` (${_color})` : ""
|
</div>
|
||||||
} — ${keyBindings[i].toUpperCase()}`}
|
</div>
|
||||||
aria-label={t(`colors.${_colorWithoutHash}`)}
|
)}
|
||||||
aria-keyshortcuts={keyBindings[i]}
|
|
||||||
style={{ color: _color }}
|
|
||||||
key={_color}
|
|
||||||
ref={(el) => {
|
|
||||||
if (el && i === 0) {
|
|
||||||
firstItem.current = el;
|
|
||||||
}
|
|
||||||
if (el && _color === color) {
|
|
||||||
activeItem.current = el;
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onFocus={() => {
|
|
||||||
onChange(_color);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{isTransparent(_color) ? (
|
|
||||||
<div className="color-picker-transparent"></div>
|
|
||||||
) : undefined}
|
|
||||||
<span className="color-picker-keybinding">{keyBindings[i]}</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
{showInput && (
|
{showInput && (
|
||||||
<ColorInput
|
<ColorInput
|
||||||
color={color}
|
color={color}
|
||||||
@@ -246,6 +353,8 @@ export const ColorPicker = ({
|
|||||||
label,
|
label,
|
||||||
isActive,
|
isActive,
|
||||||
setActive,
|
setActive,
|
||||||
|
elements,
|
||||||
|
appState,
|
||||||
}: {
|
}: {
|
||||||
type: "canvasBackground" | "elementBackground" | "elementStroke";
|
type: "canvasBackground" | "elementBackground" | "elementStroke";
|
||||||
color: string | null;
|
color: string | null;
|
||||||
@@ -253,6 +362,8 @@ export const ColorPicker = ({
|
|||||||
label: string;
|
label: string;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
setActive: (active: boolean) => void;
|
setActive: (active: boolean) => void;
|
||||||
|
elements: readonly ExcalidrawElement[];
|
||||||
|
appState: AppState;
|
||||||
}) => {
|
}) => {
|
||||||
const pickerButton = React.useRef<HTMLButtonElement>(null);
|
const pickerButton = React.useRef<HTMLButtonElement>(null);
|
||||||
|
|
||||||
@@ -294,6 +405,7 @@ export const ColorPicker = ({
|
|||||||
label={label}
|
label={label}
|
||||||
showInput={false}
|
showInput={false}
|
||||||
type={type}
|
type={type}
|
||||||
|
elements={elements}
|
||||||
/>
|
/>
|
||||||
</Popover>
|
</Popover>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
import { Action } from "../actions/types";
|
import { Action } from "../actions/types";
|
||||||
import { ActionManager } from "../actions/manager";
|
import { ActionManager } from "../actions/manager";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
|
import { NonDeletedExcalidrawElement } from "../element/types";
|
||||||
|
|
||||||
export type ContextMenuOption = "separator" | Action;
|
export type ContextMenuOption = "separator" | Action;
|
||||||
|
|
||||||
@@ -21,6 +22,7 @@ type ContextMenuProps = {
|
|||||||
left: number;
|
left: number;
|
||||||
actionManager: ActionManager;
|
actionManager: ActionManager;
|
||||||
appState: Readonly<AppState>;
|
appState: Readonly<AppState>;
|
||||||
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const ContextMenu = ({
|
const ContextMenu = ({
|
||||||
@@ -30,6 +32,7 @@ const ContextMenu = ({
|
|||||||
left,
|
left,
|
||||||
actionManager,
|
actionManager,
|
||||||
appState,
|
appState,
|
||||||
|
elements,
|
||||||
}: ContextMenuProps) => {
|
}: ContextMenuProps) => {
|
||||||
return (
|
return (
|
||||||
<Popover
|
<Popover
|
||||||
@@ -37,6 +40,10 @@ const ContextMenu = ({
|
|||||||
top={top}
|
top={top}
|
||||||
left={left}
|
left={left}
|
||||||
fitInViewport={true}
|
fitInViewport={true}
|
||||||
|
offsetLeft={appState.offsetLeft}
|
||||||
|
offsetTop={appState.offsetTop}
|
||||||
|
viewportWidth={appState.width}
|
||||||
|
viewportHeight={appState.height}
|
||||||
>
|
>
|
||||||
<ul
|
<ul
|
||||||
className="context-menu"
|
className="context-menu"
|
||||||
@@ -48,9 +55,14 @@ const ContextMenu = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const actionName = option.name;
|
const actionName = option.name;
|
||||||
const label = option.contextItemLabel
|
let label = "";
|
||||||
? t(option.contextItemLabel)
|
if (option.contextItemLabel) {
|
||||||
: "";
|
if (typeof option.contextItemLabel === "function") {
|
||||||
|
label = t(option.contextItemLabel(elements, appState));
|
||||||
|
} else {
|
||||||
|
label = t(option.contextItemLabel);
|
||||||
|
}
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<li key={idx} data-testid={actionName} onClick={onCloseRequest}>
|
<li key={idx} data-testid={actionName} onClick={onCloseRequest}>
|
||||||
<button
|
<button
|
||||||
@@ -97,6 +109,7 @@ type ContextMenuParams = {
|
|||||||
actionManager: ContextMenuProps["actionManager"];
|
actionManager: ContextMenuProps["actionManager"];
|
||||||
appState: Readonly<AppState>;
|
appState: Readonly<AppState>;
|
||||||
container: HTMLElement;
|
container: HTMLElement;
|
||||||
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleClose = (container: HTMLElement) => {
|
const handleClose = (container: HTMLElement) => {
|
||||||
@@ -125,6 +138,7 @@ export default {
|
|||||||
onCloseRequest={() => handleClose(params.container)}
|
onCloseRequest={() => handleClose(params.container)}
|
||||||
actionManager={params.actionManager}
|
actionManager={params.actionManager}
|
||||||
appState={params.appState}
|
appState={params.appState}
|
||||||
|
elements={params.elements}
|
||||||
/>,
|
/>,
|
||||||
getContextMenuNode(params.container),
|
getContextMenuNode(params.container),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -154,7 +154,7 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
|
|||||||
<Shortcut label={t("toolBar.line")} shortcuts={["P", "6"]} />
|
<Shortcut label={t("toolBar.line")} shortcuts={["P", "6"]} />
|
||||||
<Shortcut
|
<Shortcut
|
||||||
label={t("toolBar.freedraw")}
|
label={t("toolBar.freedraw")}
|
||||||
shortcuts={["Shift+P", "7"]}
|
shortcuts={["Shift + P", "X", "7"]}
|
||||||
/>
|
/>
|
||||||
<Shortcut label={t("toolBar.text")} shortcuts={["T", "8"]} />
|
<Shortcut label={t("toolBar.text")} shortcuts={["T", "8"]} />
|
||||||
<Shortcut label={t("toolBar.image")} shortcuts={["9"]} />
|
<Shortcut label={t("toolBar.image")} shortcuts={["9"]} />
|
||||||
@@ -205,6 +205,10 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
|
|||||||
label={t("helpDialog.preventBinding")}
|
label={t("helpDialog.preventBinding")}
|
||||||
shortcuts={[getShortcutKey("CtrlOrCmd")]}
|
shortcuts={[getShortcutKey("CtrlOrCmd")]}
|
||||||
/>
|
/>
|
||||||
|
<Shortcut
|
||||||
|
label={t("toolBar.link")}
|
||||||
|
shortcuts={[getShortcutKey("CtrlOrCmd+K")]}
|
||||||
|
/>
|
||||||
</ShortcutIsland>
|
</ShortcutIsland>
|
||||||
<ShortcutIsland caption={t("helpDialog.view")}>
|
<ShortcutIsland caption={t("helpDialog.view")}>
|
||||||
<Shortcut
|
<Shortcut
|
||||||
@@ -260,6 +264,18 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
|
|||||||
label={t("labels.multiSelect")}
|
label={t("labels.multiSelect")}
|
||||||
shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]}
|
shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]}
|
||||||
/>
|
/>
|
||||||
|
<Shortcut
|
||||||
|
label={t("helpDialog.deepSelect")}
|
||||||
|
shortcuts={[
|
||||||
|
getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<Shortcut
|
||||||
|
label={t("helpDialog.deepBoxSelect")}
|
||||||
|
shortcuts={[
|
||||||
|
getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
<Shortcut
|
<Shortcut
|
||||||
label={t("labels.moveCanvas")}
|
label={t("labels.moveCanvas")}
|
||||||
shortcuts={[
|
shortcuts={[
|
||||||
@@ -382,6 +398,14 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
|
|||||||
label={t("labels.showBackground")}
|
label={t("labels.showBackground")}
|
||||||
shortcuts={[getShortcutKey("G")]}
|
shortcuts={[getShortcutKey("G")]}
|
||||||
/>
|
/>
|
||||||
|
<Shortcut
|
||||||
|
label={t("labels.decreaseFontSize")}
|
||||||
|
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]}
|
||||||
|
/>
|
||||||
|
<Shortcut
|
||||||
|
label={t("labels.increaseFontSize")}
|
||||||
|
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]}
|
||||||
|
/>
|
||||||
</ShortcutIsland>
|
</ShortcutIsland>
|
||||||
</Column>
|
</Column>
|
||||||
</Columns>
|
</Columns>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { AppState } from "../types";
|
|||||||
import {
|
import {
|
||||||
isImageElement,
|
isImageElement,
|
||||||
isLinearElement,
|
isLinearElement,
|
||||||
|
isTextBindableContainer,
|
||||||
isTextElement,
|
isTextElement,
|
||||||
} from "../element/typeChecks";
|
} from "../element/typeChecks";
|
||||||
import { getShortcutKey } from "../utils";
|
import { getShortcutKey } from "../utils";
|
||||||
@@ -60,15 +61,6 @@ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => {
|
|||||||
return t("hints.rotate");
|
return t("hints.rotate");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
|
|
||||||
if (appState.editingLinearElement) {
|
|
||||||
return appState.editingLinearElement.activePointIndex
|
|
||||||
? t("hints.lineEditor_pointSelected")
|
|
||||||
: t("hints.lineEditor_nothingSelected");
|
|
||||||
}
|
|
||||||
return t("hints.lineEditor_info");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (selectedElements.length === 1 && isTextElement(selectedElements[0])) {
|
if (selectedElements.length === 1 && isTextElement(selectedElements[0])) {
|
||||||
return t("hints.text_selected");
|
return t("hints.text_selected");
|
||||||
}
|
}
|
||||||
@@ -77,8 +69,31 @@ const getHints = ({ appState, elements, isMobile }: HintViewerProps) => {
|
|||||||
return t("hints.text_editing");
|
return t("hints.text_editing");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (elementType === "selection" && !selectedElements.length && !isMobile) {
|
if (elementType === "selection") {
|
||||||
return t("hints.canvasPanning");
|
if (
|
||||||
|
appState.draggingElement?.type === "selection" &&
|
||||||
|
!appState.editingElement &&
|
||||||
|
!appState.editingLinearElement
|
||||||
|
) {
|
||||||
|
return t("hints.deepBoxSelect");
|
||||||
|
}
|
||||||
|
if (!selectedElements.length && !isMobile) {
|
||||||
|
return t("hints.canvasPanning");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selectedElements.length === 1) {
|
||||||
|
if (isLinearElement(selectedElements[0])) {
|
||||||
|
if (appState.editingLinearElement) {
|
||||||
|
return appState.editingLinearElement.selectedPointsIndices
|
||||||
|
? t("hints.lineEditor_pointSelected")
|
||||||
|
: t("hints.lineEditor_nothingSelected");
|
||||||
|
}
|
||||||
|
return t("hints.lineEditor_info");
|
||||||
|
}
|
||||||
|
if (isTextBindableContainer(selectedElements[0])) {
|
||||||
|
return t("hints.bindTextToElement");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
|
||||||
&:focus {
|
&:focus-visible {
|
||||||
outline: transparent;
|
outline: transparent;
|
||||||
background-color: var(--button-gray-2);
|
background-color: var(--button-gray-2);
|
||||||
& svg {
|
& svg {
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ const ImageExportModal = ({
|
|||||||
const { exportBackground, viewBackgroundColor } = appState;
|
const { exportBackground, viewBackgroundColor } = appState;
|
||||||
|
|
||||||
const exportedElements = exportSelected
|
const exportedElements = exportSelected
|
||||||
? getSelectedElements(elements, appState)
|
? getSelectedElements(elements, appState, true)
|
||||||
: elements;
|
: elements;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
--padding: 0;
|
--padding: 0;
|
||||||
background-color: var(--island-bg-color);
|
background-color: var(--island-bg-color);
|
||||||
box-shadow: var(--shadow-island);
|
box-shadow: var(--shadow-island);
|
||||||
border-radius: 4px;
|
border-radius: var(--border-radius-lg);
|
||||||
padding: calc(var(--padding) * var(--space-factor));
|
padding: calc(var(--padding) * var(--space-factor));
|
||||||
position: relative;
|
position: relative;
|
||||||
transition: box-shadow 0.5s ease-in-out;
|
transition: box-shadow 0.5s ease-in-out;
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import { ExportCB, ImageExportDialog } from "./ImageExportDialog";
|
|||||||
import { FixedSideContainer } from "./FixedSideContainer";
|
import { FixedSideContainer } from "./FixedSideContainer";
|
||||||
import { HintViewer } from "./HintViewer";
|
import { HintViewer } from "./HintViewer";
|
||||||
import { Island } from "./Island";
|
import { Island } from "./Island";
|
||||||
import "./LayerUI.scss";
|
|
||||||
import { LoadingMessage } from "./LoadingMessage";
|
import { LoadingMessage } from "./LoadingMessage";
|
||||||
import { LockButton } from "./LockButton";
|
import { LockButton } from "./LockButton";
|
||||||
import { MobileMenu } from "./MobileMenu";
|
import { MobileMenu } from "./MobileMenu";
|
||||||
@@ -35,6 +34,10 @@ import { LibraryButton } from "./LibraryButton";
|
|||||||
import { isImageFileHandle } from "../data/blob";
|
import { isImageFileHandle } from "../data/blob";
|
||||||
import { LibraryMenu } from "./LibraryMenu";
|
import { LibraryMenu } from "./LibraryMenu";
|
||||||
|
|
||||||
|
import "./LayerUI.scss";
|
||||||
|
import "./Toolbar.scss";
|
||||||
|
import { PenModeButton } from "./PenModeButton";
|
||||||
|
|
||||||
interface LayerUIProps {
|
interface LayerUIProps {
|
||||||
actionManager: ActionManager;
|
actionManager: ActionManager;
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
@@ -44,6 +47,7 @@ interface LayerUIProps {
|
|||||||
elements: readonly NonDeletedExcalidrawElement[];
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
onCollabButtonClick?: () => void;
|
onCollabButtonClick?: () => void;
|
||||||
onLockToggle: () => void;
|
onLockToggle: () => void;
|
||||||
|
onPenModeToggle: () => void;
|
||||||
onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
|
onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
|
||||||
zenModeEnabled: boolean;
|
zenModeEnabled: boolean;
|
||||||
showExitZenModeBtn: boolean;
|
showExitZenModeBtn: boolean;
|
||||||
@@ -74,6 +78,7 @@ const LayerUI = ({
|
|||||||
elements,
|
elements,
|
||||||
onCollabButtonClick,
|
onCollabButtonClick,
|
||||||
onLockToggle,
|
onLockToggle,
|
||||||
|
onPenModeToggle,
|
||||||
onInsertElements,
|
onInsertElements,
|
||||||
zenModeEnabled,
|
zenModeEnabled,
|
||||||
showExitZenModeBtn,
|
showExitZenModeBtn,
|
||||||
@@ -233,7 +238,7 @@ const LayerUI = ({
|
|||||||
className={CLASSES.SHAPE_ACTIONS_MENU}
|
className={CLASSES.SHAPE_ACTIONS_MENU}
|
||||||
padding={2}
|
padding={2}
|
||||||
style={{
|
style={{
|
||||||
// we want to make sure this doesn't overflow so substracting 200
|
// we want to make sure this doesn't overflow so subtracting 200
|
||||||
// which is approximately height of zoom footer and top left menu items with some buffer
|
// which is approximately height of zoom footer and top left menu items with some buffer
|
||||||
// if active file name is displayed, subtracting 248 to account for its height
|
// if active file name is displayed, subtracting 248 to account for its height
|
||||||
maxHeight: `${appState.height - (appState.fileHandle ? 248 : 200)}px`,
|
maxHeight: `${appState.height - (appState.fileHandle ? 248 : 200)}px`,
|
||||||
@@ -268,7 +273,7 @@ const LayerUI = ({
|
|||||||
|
|
||||||
const libraryMenu = appState.isLibraryOpen ? (
|
const libraryMenu = appState.isLibraryOpen ? (
|
||||||
<LibraryMenu
|
<LibraryMenu
|
||||||
pendingElements={getSelectedElements(elements, appState)}
|
pendingElements={getSelectedElements(elements, appState, true)}
|
||||||
onClose={closeLibrary}
|
onClose={closeLibrary}
|
||||||
onInsertShape={onInsertElements}
|
onInsertShape={onInsertElements}
|
||||||
onAddToLibrary={deselectItems}
|
onAddToLibrary={deselectItems}
|
||||||
@@ -305,7 +310,19 @@ const LayerUI = ({
|
|||||||
<Section heading="shapes">
|
<Section heading="shapes">
|
||||||
{(heading) => (
|
{(heading) => (
|
||||||
<Stack.Col gap={4} align="start">
|
<Stack.Col gap={4} align="start">
|
||||||
<Stack.Row gap={1}>
|
<Stack.Row
|
||||||
|
gap={1}
|
||||||
|
className={clsx("App-toolbar-container", {
|
||||||
|
"zen-mode": zenModeEnabled,
|
||||||
|
})}
|
||||||
|
>
|
||||||
|
<PenModeButton
|
||||||
|
zenModeEnabled={zenModeEnabled}
|
||||||
|
checked={appState.penMode}
|
||||||
|
onChange={onPenModeToggle}
|
||||||
|
title={t("toolBar.penMode")}
|
||||||
|
penDetected={appState.penDetected}
|
||||||
|
/>
|
||||||
<LockButton
|
<LockButton
|
||||||
zenModeEnabled={zenModeEnabled}
|
zenModeEnabled={zenModeEnabled}
|
||||||
checked={appState.elementLocked}
|
checked={appState.elementLocked}
|
||||||
@@ -314,7 +331,9 @@ const LayerUI = ({
|
|||||||
/>
|
/>
|
||||||
<Island
|
<Island
|
||||||
padding={1}
|
padding={1}
|
||||||
className={clsx({ "zen-mode": zenModeEnabled })}
|
className={clsx("App-toolbar", {
|
||||||
|
"zen-mode": zenModeEnabled,
|
||||||
|
})}
|
||||||
>
|
>
|
||||||
<HintViewer
|
<HintViewer
|
||||||
appState={appState}
|
appState={appState}
|
||||||
@@ -489,6 +508,7 @@ const LayerUI = ({
|
|||||||
setAppState={setAppState}
|
setAppState={setAppState}
|
||||||
onCollabButtonClick={onCollabButtonClick}
|
onCollabButtonClick={onCollabButtonClick}
|
||||||
onLockToggle={onLockToggle}
|
onLockToggle={onLockToggle}
|
||||||
|
onPenModeToggle={onPenModeToggle}
|
||||||
canvas={canvas}
|
canvas={canvas}
|
||||||
isCollaborating={isCollaborating}
|
isCollaborating={isCollaborating}
|
||||||
renderCustomFooter={renderCustomFooter}
|
renderCustomFooter={renderCustomFooter}
|
||||||
|
|||||||
@@ -16,18 +16,18 @@ const LIBRARY_ICON = (
|
|||||||
export const LibraryButton: React.FC<{
|
export const LibraryButton: React.FC<{
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
setAppState: React.Component<any, AppState>["setState"];
|
setAppState: React.Component<any, AppState>["setState"];
|
||||||
}> = ({ appState, setAppState }) => {
|
isMobile?: boolean;
|
||||||
|
}> = ({ appState, setAppState, isMobile }) => {
|
||||||
return (
|
return (
|
||||||
<label
|
<label
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"ToolIcon ToolIcon_type_floating ToolIcon__library zen-mode-visibility",
|
"ToolIcon ToolIcon_type_floating ToolIcon__library",
|
||||||
`ToolIcon_size_medium`,
|
`ToolIcon_size_medium`,
|
||||||
{
|
{
|
||||||
"zen-mode-visibility--hidden": appState.zenModeEnabled,
|
"is-mobile": isMobile,
|
||||||
},
|
},
|
||||||
)}
|
)}
|
||||||
title={`${capitalizeString(t("toolBar.library"))} — 0`}
|
title={`${capitalizeString(t("toolBar.library"))} — 0`}
|
||||||
style={{ marginInlineStart: "var(--space-factor)" }}
|
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
className="ToolIcon_type_checkbox"
|
className="ToolIcon_type_checkbox"
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import "./LibraryMenu.scss";
|
|||||||
import LibraryMenuItems from "./LibraryMenuItems";
|
import LibraryMenuItems from "./LibraryMenuItems";
|
||||||
import { EVENT } from "../constants";
|
import { EVENT } from "../constants";
|
||||||
import { KEYS } from "../keys";
|
import { KEYS } from "../keys";
|
||||||
|
import { arrayToMap } from "../utils";
|
||||||
|
|
||||||
const useOnClickOutside = (
|
const useOnClickOutside = (
|
||||||
ref: RefObject<HTMLElement>,
|
ref: RefObject<HTMLElement>,
|
||||||
@@ -236,6 +237,10 @@ export const LibraryMenu = ({
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const [lastSelectedItem, setLastSelectedItem] = useState<
|
||||||
|
LibraryItem["id"] | null
|
||||||
|
>(null);
|
||||||
|
|
||||||
return loadingState === "preloading" ? null : (
|
return loadingState === "preloading" ? null : (
|
||||||
<Island padding={1} ref={ref} className="layer-ui__library">
|
<Island padding={1} ref={ref} className="layer-ui__library">
|
||||||
{showPublishLibraryDialog && (
|
{showPublishLibraryDialog && (
|
||||||
@@ -271,10 +276,44 @@ export const LibraryMenu = ({
|
|||||||
files={files}
|
files={files}
|
||||||
id={id}
|
id={id}
|
||||||
selectedItems={selectedItems}
|
selectedItems={selectedItems}
|
||||||
onToggle={(id) => {
|
onToggle={(id, event) => {
|
||||||
if (!selectedItems.includes(id)) {
|
const shouldSelect = !selectedItems.includes(id);
|
||||||
setSelectedItems([...selectedItems, id]);
|
|
||||||
|
if (shouldSelect) {
|
||||||
|
if (event.shiftKey && lastSelectedItem) {
|
||||||
|
const rangeStart = libraryItems.findIndex(
|
||||||
|
(item) => item.id === lastSelectedItem,
|
||||||
|
);
|
||||||
|
const rangeEnd = libraryItems.findIndex(
|
||||||
|
(item) => item.id === id,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rangeStart === -1 || rangeEnd === -1) {
|
||||||
|
setSelectedItems([...selectedItems, id]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const selectedItemsMap = arrayToMap(selectedItems);
|
||||||
|
const nextSelectedIds = libraryItems.reduce(
|
||||||
|
(acc: LibraryItem["id"][], item, idx) => {
|
||||||
|
if (
|
||||||
|
(idx >= rangeStart && idx <= rangeEnd) ||
|
||||||
|
selectedItemsMap.has(item.id)
|
||||||
|
) {
|
||||||
|
acc.push(item.id);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
setSelectedItems(nextSelectedIds);
|
||||||
|
} else {
|
||||||
|
setSelectedItems([...selectedItems, id]);
|
||||||
|
}
|
||||||
|
setLastSelectedItem(id);
|
||||||
} else {
|
} else {
|
||||||
|
setLastSelectedItem(null);
|
||||||
setSelectedItems(selectedItems.filter((_id) => _id !== id));
|
setSelectedItems(selectedItems.filter((_id) => _id !== id));
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { ToolButton } from "./ToolButton";
|
|||||||
import { Tooltip } from "./Tooltip";
|
import { Tooltip } from "./Tooltip";
|
||||||
|
|
||||||
import "./LibraryMenuItems.scss";
|
import "./LibraryMenuItems.scss";
|
||||||
|
import { VERSIONS } from "../constants";
|
||||||
|
|
||||||
const LibraryMenuItems = ({
|
const LibraryMenuItems = ({
|
||||||
libraryItems,
|
libraryItems,
|
||||||
@@ -51,7 +52,7 @@ const LibraryMenuItems = ({
|
|||||||
library: Library;
|
library: Library;
|
||||||
id: string;
|
id: string;
|
||||||
selectedItems: LibraryItem["id"][];
|
selectedItems: LibraryItem["id"][];
|
||||||
onToggle: (id: LibraryItem["id"]) => void;
|
onToggle: (id: LibraryItem["id"], event: React.MouseEvent) => void;
|
||||||
onPublish: () => void;
|
onPublish: () => void;
|
||||||
resetLibrary: () => void;
|
resetLibrary: () => void;
|
||||||
}) => {
|
}) => {
|
||||||
@@ -212,10 +213,8 @@ const LibraryMenuItems = ({
|
|||||||
onClick={params.onClick || (() => {})}
|
onClick={params.onClick || (() => {})}
|
||||||
id={params.item?.id || null}
|
id={params.item?.id || null}
|
||||||
selected={!!params.item?.id && selectedItems.includes(params.item.id)}
|
selected={!!params.item?.id && selectedItems.includes(params.item.id)}
|
||||||
onToggle={() => {
|
onToggle={(id, event) => {
|
||||||
if (params.item?.id) {
|
onToggle(id, event);
|
||||||
onToggle(params.item.id);
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
</Stack.Col>
|
</Stack.Col>
|
||||||
@@ -293,7 +292,9 @@ const LibraryMenuItems = ({
|
|||||||
<a
|
<a
|
||||||
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
|
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
|
||||||
window.name || "_blank"
|
window.name || "_blank"
|
||||||
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}`}
|
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}&version=${
|
||||||
|
VERSIONS.excalidrawLibrary
|
||||||
|
}`}
|
||||||
target="_excalidraw_libraries"
|
target="_excalidraw_libraries"
|
||||||
>
|
>
|
||||||
{t("labels.libraries")}
|
{t("labels.libraries")}
|
||||||
|
|||||||
@@ -27,6 +27,8 @@
|
|||||||
|
|
||||||
.library-unit__dragger {
|
.library-unit__dragger {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
@@ -99,8 +101,13 @@
|
|||||||
margin-top: -10px;
|
margin-top: -10px;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
.library-unit--hover .library-unit__adder {
|
.library-unit:hover .library-unit__adder {
|
||||||
color: $oc-blue-7;
|
fill: $oc-blue-7;
|
||||||
|
}
|
||||||
|
.library-unit:active .library-unit__adder {
|
||||||
|
animation: none;
|
||||||
|
transform: scale(0.8);
|
||||||
|
fill: $oc-black;
|
||||||
}
|
}
|
||||||
|
|
||||||
.library-unit__active {
|
.library-unit__active {
|
||||||
|
|||||||
@@ -8,12 +8,15 @@ import { BinaryFiles, LibraryItem } from "../types";
|
|||||||
import "./LibraryUnit.scss";
|
import "./LibraryUnit.scss";
|
||||||
import { CheckboxItem } from "./CheckboxItem";
|
import { CheckboxItem } from "./CheckboxItem";
|
||||||
|
|
||||||
// fa-plus
|
|
||||||
const PLUS_ICON = (
|
const PLUS_ICON = (
|
||||||
<svg viewBox="0 0 1792 1792">
|
<svg viewBox="0 0 1792 1792">
|
||||||
<path
|
<path
|
||||||
fill="currentColor"
|
d="M1600 736v192c0 26.667-9.33 49.333-28 68-18.67 18.67-41.33 28-68 28h-416v416c0 26.67-9.33 49.33-28 68s-41.33 28-68 28H800c-26.667 0-49.333-9.33-68-28s-28-41.33-28-68v-416H288c-26.667 0-49.333-9.33-68-28-18.667-18.667-28-41.333-28-68V736c0-26.667 9.333-49.333 28-68s41.333-28 68-28h416V224c0-26.667 9.333-49.333 28-68s41.333-28 68-28h192c26.67 0 49.33 9.333 68 28s28 41.333 28 68v416h416c26.67 0 49.33 9.333 68 28s28 41.333 28 68Z"
|
||||||
d="M1600 736v192q0 40-28 68t-68 28h-416v416q0 40-28 68t-68 28h-192q-40 0-68-28t-28-68v-416h-416q-40 0-68-28t-28-68v-192q0-40 28-68t68-28h416v-416q0-40 28-68t68-28h192q40 0 68 28t28 68v416h416q40 0 68 28t28 68z"
|
style={{
|
||||||
|
stroke: "#fff",
|
||||||
|
strokeWidth: 140,
|
||||||
|
}}
|
||||||
|
transform="translate(0 64)"
|
||||||
/>
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
@@ -33,7 +36,7 @@ export const LibraryUnit = ({
|
|||||||
isPending?: boolean;
|
isPending?: boolean;
|
||||||
onClick: () => void;
|
onClick: () => void;
|
||||||
selected: boolean;
|
selected: boolean;
|
||||||
onToggle: (id: string) => void;
|
onToggle: (id: string, event: React.MouseEvent) => void;
|
||||||
}) => {
|
}) => {
|
||||||
const ref = useRef<HTMLDivElement | null>(null);
|
const ref = useRef<HTMLDivElement | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -84,7 +87,17 @@ export const LibraryUnit = ({
|
|||||||
})}
|
})}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
draggable={!!elements}
|
draggable={!!elements}
|
||||||
onClick={!!elements || !!isPending ? onClick : undefined}
|
onClick={
|
||||||
|
!!elements || !!isPending
|
||||||
|
? (event) => {
|
||||||
|
if (id && event.shiftKey) {
|
||||||
|
onToggle(id, event);
|
||||||
|
} else {
|
||||||
|
onClick();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
onDragStart={(event) => {
|
onDragStart={(event) => {
|
||||||
setIsHovered(false);
|
setIsHovered(false);
|
||||||
event.dataTransfer.setData(
|
event.dataTransfer.setData(
|
||||||
@@ -97,7 +110,7 @@ export const LibraryUnit = ({
|
|||||||
{id && elements && (isHovered || isMobile || selected) && (
|
{id && elements && (isHovered || isMobile || selected) && (
|
||||||
<CheckboxItem
|
<CheckboxItem
|
||||||
checked={selected}
|
checked={selected}
|
||||||
onChange={() => onToggle(id)}
|
onChange={(checked, event) => onToggle(id, event)}
|
||||||
className="library-unit__checkbox"
|
className="library-unit__checkbox"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ type LockIconProps = {
|
|||||||
checked: boolean;
|
checked: boolean;
|
||||||
onChange?(): void;
|
onChange?(): void;
|
||||||
zenModeEnabled?: boolean;
|
zenModeEnabled?: boolean;
|
||||||
|
isMobile?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_SIZE: ToolButtonSize = "medium";
|
const DEFAULT_SIZE: ToolButtonSize = "medium";
|
||||||
@@ -42,10 +43,10 @@ export const LockButton = (props: LockIconProps) => {
|
|||||||
return (
|
return (
|
||||||
<label
|
<label
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"ToolIcon ToolIcon__lock ToolIcon_type_floating zen-mode-visibility",
|
"ToolIcon ToolIcon__lock ToolIcon_type_floating",
|
||||||
`ToolIcon_size_${DEFAULT_SIZE}`,
|
`ToolIcon_size_${DEFAULT_SIZE}`,
|
||||||
{
|
{
|
||||||
"zen-mode-visibility--hidden": props.zenModeEnabled,
|
"is-mobile": props.isMobile,
|
||||||
},
|
},
|
||||||
)}
|
)}
|
||||||
title={`${props.title} — Q`}
|
title={`${props.title} — Q`}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { LockButton } from "./LockButton";
|
|||||||
import { UserList } from "./UserList";
|
import { UserList } from "./UserList";
|
||||||
import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
|
import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
|
||||||
import { LibraryButton } from "./LibraryButton";
|
import { LibraryButton } from "./LibraryButton";
|
||||||
|
import { PenModeButton } from "./PenModeButton";
|
||||||
|
|
||||||
type MobileMenuProps = {
|
type MobileMenuProps = {
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
@@ -28,6 +29,7 @@ type MobileMenuProps = {
|
|||||||
libraryMenu: JSX.Element | null;
|
libraryMenu: JSX.Element | null;
|
||||||
onCollabButtonClick?: () => void;
|
onCollabButtonClick?: () => void;
|
||||||
onLockToggle: () => void;
|
onLockToggle: () => void;
|
||||||
|
onPenModeToggle: () => void;
|
||||||
canvas: HTMLCanvasElement | null;
|
canvas: HTMLCanvasElement | null;
|
||||||
isCollaborating: boolean;
|
isCollaborating: boolean;
|
||||||
renderCustomFooter?: (isMobile: boolean, appState: AppState) => JSX.Element;
|
renderCustomFooter?: (isMobile: boolean, appState: AppState) => JSX.Element;
|
||||||
@@ -50,6 +52,7 @@ export const MobileMenu = ({
|
|||||||
setAppState,
|
setAppState,
|
||||||
onCollabButtonClick,
|
onCollabButtonClick,
|
||||||
onLockToggle,
|
onLockToggle,
|
||||||
|
onPenModeToggle,
|
||||||
canvas,
|
canvas,
|
||||||
isCollaborating,
|
isCollaborating,
|
||||||
renderCustomFooter,
|
renderCustomFooter,
|
||||||
@@ -64,8 +67,8 @@ export const MobileMenu = ({
|
|||||||
<Section heading="shapes">
|
<Section heading="shapes">
|
||||||
{(heading) => (
|
{(heading) => (
|
||||||
<Stack.Col gap={4} align="center">
|
<Stack.Col gap={4} align="center">
|
||||||
<Stack.Row gap={1}>
|
<Stack.Row gap={1} className="App-toolbar-container">
|
||||||
<Island padding={1}>
|
<Island padding={1} className="App-toolbar">
|
||||||
{heading}
|
{heading}
|
||||||
<Stack.Row gap={1}>
|
<Stack.Row gap={1}>
|
||||||
<ShapesSwitcher
|
<ShapesSwitcher
|
||||||
@@ -85,8 +88,20 @@ export const MobileMenu = ({
|
|||||||
checked={appState.elementLocked}
|
checked={appState.elementLocked}
|
||||||
onChange={onLockToggle}
|
onChange={onLockToggle}
|
||||||
title={t("toolBar.lock")}
|
title={t("toolBar.lock")}
|
||||||
|
isMobile
|
||||||
|
/>
|
||||||
|
<LibraryButton
|
||||||
|
appState={appState}
|
||||||
|
setAppState={setAppState}
|
||||||
|
isMobile
|
||||||
|
/>
|
||||||
|
<PenModeButton
|
||||||
|
checked={appState.penMode}
|
||||||
|
onChange={onPenModeToggle}
|
||||||
|
title={t("toolBar.penMode")}
|
||||||
|
isMobile
|
||||||
|
penDetected={appState.penDetected}
|
||||||
/>
|
/>
|
||||||
<LibraryButton appState={appState} setAppState={setAppState} />
|
|
||||||
</Stack.Row>
|
</Stack.Row>
|
||||||
{libraryMenu}
|
{libraryMenu}
|
||||||
</Stack.Col>
|
</Stack.Col>
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import "./ToolIcon.scss";
|
||||||
|
|
||||||
|
import clsx from "clsx";
|
||||||
|
import { ToolButtonSize } from "./ToolButton";
|
||||||
|
|
||||||
|
type PenModeIconProps = {
|
||||||
|
title?: string;
|
||||||
|
name?: string;
|
||||||
|
checked: boolean;
|
||||||
|
onChange?(): void;
|
||||||
|
zenModeEnabled?: boolean;
|
||||||
|
isMobile?: boolean;
|
||||||
|
penDetected: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DEFAULT_SIZE: ToolButtonSize = "medium";
|
||||||
|
|
||||||
|
const ICONS = {
|
||||||
|
CHECKED: (
|
||||||
|
<svg
|
||||||
|
width="205"
|
||||||
|
height="205"
|
||||||
|
viewBox="0 0 205 205"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
>
|
||||||
|
<path d="m35 195-25-29.17V50h50v115l-25 30" />
|
||||||
|
<path d="M10 40V10h50v30H10" />
|
||||||
|
<path d="M125 145h70v50h-70" />
|
||||||
|
<path d="M190 145v-30l-10-20h-40l-10 20v30h15v-30l5-5h20l5 5v30h15" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
UNCHECKED: (
|
||||||
|
<svg
|
||||||
|
width="205"
|
||||||
|
height="205"
|
||||||
|
viewBox="0 0 205 205"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
className="unlocked-icon rtl-mirror"
|
||||||
|
>
|
||||||
|
<path d="m35 195-25-29.17V50h50v115l-25 30" />
|
||||||
|
<path d="M10 40V10h50v30H10" />
|
||||||
|
<path d="M125 145h70v50h-70" />
|
||||||
|
<path d="M145 145v-30l-10-20H95l-10 20v30h15v-30l5-5h20l5 5v30h15" />
|
||||||
|
</svg>
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PenModeButton = (props: PenModeIconProps) => {
|
||||||
|
if (!props.penDetected) {
|
||||||
|
if (props.isMobile) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
className={clsx(
|
||||||
|
"ToolIcon ToolIcon__penMode ToolIcon_type_floating",
|
||||||
|
`ToolIcon_size_${DEFAULT_SIZE}`,
|
||||||
|
{
|
||||||
|
"is-mobile": props.isMobile,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="ToolIcon__icon ToolIcon__hidden" />
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<label
|
||||||
|
className={clsx(
|
||||||
|
"ToolIcon ToolIcon__penMode ToolIcon_type_floating",
|
||||||
|
`ToolIcon_size_${DEFAULT_SIZE}`,
|
||||||
|
{
|
||||||
|
"is-mobile": props.isMobile,
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
title={`${props.title}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
className="ToolIcon_type_checkbox"
|
||||||
|
type="checkbox"
|
||||||
|
name={props.name}
|
||||||
|
onChange={props.onChange}
|
||||||
|
checked={props.checked}
|
||||||
|
aria-label={props.title}
|
||||||
|
/>
|
||||||
|
<div className="ToolIcon__icon">
|
||||||
|
{props.checked ? ICONS.CHECKED : ICONS.UNCHECKED}
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -8,6 +8,10 @@ type Props = {
|
|||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
onCloseRequest?(event: PointerEvent): void;
|
onCloseRequest?(event: PointerEvent): void;
|
||||||
fitInViewport?: boolean;
|
fitInViewport?: boolean;
|
||||||
|
offsetLeft?: number;
|
||||||
|
offsetTop?: number;
|
||||||
|
viewportWidth?: number;
|
||||||
|
viewportHeight?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Popover = ({
|
export const Popover = ({
|
||||||
@@ -16,6 +20,10 @@ export const Popover = ({
|
|||||||
top,
|
top,
|
||||||
onCloseRequest,
|
onCloseRequest,
|
||||||
fitInViewport = false,
|
fitInViewport = false,
|
||||||
|
offsetLeft = 0,
|
||||||
|
offsetTop = 0,
|
||||||
|
viewportWidth = window.innerWidth,
|
||||||
|
viewportHeight = window.innerHeight,
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const popoverRef = useRef<HTMLDivElement>(null);
|
const popoverRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
@@ -24,17 +32,14 @@ export const Popover = ({
|
|||||||
if (fitInViewport && popoverRef.current) {
|
if (fitInViewport && popoverRef.current) {
|
||||||
const element = popoverRef.current;
|
const element = popoverRef.current;
|
||||||
const { x, y, width, height } = element.getBoundingClientRect();
|
const { x, y, width, height } = element.getBoundingClientRect();
|
||||||
|
if (x + width - offsetLeft > viewportWidth) {
|
||||||
const viewportWidth = window.innerWidth;
|
|
||||||
if (x + width > viewportWidth) {
|
|
||||||
element.style.left = `${viewportWidth - width}px`;
|
element.style.left = `${viewportWidth - width}px`;
|
||||||
}
|
}
|
||||||
const viewportHeight = window.innerHeight;
|
if (y + height - offsetTop > viewportHeight) {
|
||||||
if (y + height > viewportHeight) {
|
|
||||||
element.style.top = `${viewportHeight - height}px`;
|
element.style.top = `${viewportHeight - height}px`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [fitInViewport]);
|
}, [fitInViewport, viewportWidth, viewportHeight, offsetLeft, offsetTop]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (onCloseRequest) {
|
if (onCloseRequest) {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ReactNode, useCallback, useEffect, useState } from "react";
|
import { ReactNode, useCallback, useEffect, useState } from "react";
|
||||||
import oc from "open-color";
|
import OpenColor from "open-color";
|
||||||
|
|
||||||
import { Dialog } from "./Dialog";
|
import { Dialog } from "./Dialog";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
@@ -7,16 +7,19 @@ import { t } from "../i18n";
|
|||||||
import { ToolButton } from "./ToolButton";
|
import { ToolButton } from "./ToolButton";
|
||||||
|
|
||||||
import { AppState, LibraryItems, LibraryItem } from "../types";
|
import { AppState, LibraryItems, LibraryItem } from "../types";
|
||||||
import { exportToBlob } from "../packages/utils";
|
import { exportToCanvas } from "../packages/utils";
|
||||||
import { EXPORT_DATA_TYPES, EXPORT_SOURCE } from "../constants";
|
import {
|
||||||
|
EXPORT_DATA_TYPES,
|
||||||
|
EXPORT_SOURCE,
|
||||||
|
MIME_TYPES,
|
||||||
|
VERSIONS,
|
||||||
|
} from "../constants";
|
||||||
import { ExportedLibraryData } from "../data/types";
|
import { ExportedLibraryData } from "../data/types";
|
||||||
|
|
||||||
import "./PublishLibrary.scss";
|
import "./PublishLibrary.scss";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
|
||||||
import { newElement } from "../element";
|
|
||||||
import { mutateElement } from "../element/mutateElement";
|
|
||||||
import { getCommonBoundingBox } from "../element/bounds";
|
|
||||||
import SingleLibraryItem from "./SingleLibraryItem";
|
import SingleLibraryItem from "./SingleLibraryItem";
|
||||||
|
import { canvasToBlob, resizeImageFile } from "../data/blob";
|
||||||
|
import { chunk } from "../utils";
|
||||||
|
|
||||||
interface PublishLibraryDataParams {
|
interface PublishLibraryDataParams {
|
||||||
authorName: string;
|
authorName: string;
|
||||||
@@ -55,6 +58,75 @@ const importPublishLibDataFromStorage = () => {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
||||||
|
const MAX_ITEMS_PER_ROW = 6;
|
||||||
|
const BOX_SIZE = 128;
|
||||||
|
const BOX_PADDING = Math.round(BOX_SIZE / 16);
|
||||||
|
const BORDER_WIDTH = Math.max(Math.round(BOX_SIZE / 64), 2);
|
||||||
|
|
||||||
|
const rows = chunk(libraryItems, MAX_ITEMS_PER_ROW);
|
||||||
|
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
|
||||||
|
canvas.width =
|
||||||
|
rows[0].length * BOX_SIZE +
|
||||||
|
(rows[0].length + 1) * (BOX_PADDING * 2) -
|
||||||
|
BOX_PADDING * 2;
|
||||||
|
canvas.height =
|
||||||
|
rows.length * BOX_SIZE +
|
||||||
|
(rows.length + 1) * (BOX_PADDING * 2) -
|
||||||
|
BOX_PADDING * 2;
|
||||||
|
|
||||||
|
const ctx = canvas.getContext("2d")!;
|
||||||
|
|
||||||
|
ctx.fillStyle = OpenColor.white;
|
||||||
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
|
// draw items
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
for (const [index, item] of libraryItems.entries()) {
|
||||||
|
const itemCanvas = await exportToCanvas({
|
||||||
|
elements: item.elements,
|
||||||
|
files: null,
|
||||||
|
maxWidthOrHeight: BOX_SIZE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { width, height } = itemCanvas;
|
||||||
|
|
||||||
|
// draw item
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
const rowOffset =
|
||||||
|
Math.floor(index / MAX_ITEMS_PER_ROW) * (BOX_SIZE + BOX_PADDING * 2);
|
||||||
|
const colOffset =
|
||||||
|
(index % MAX_ITEMS_PER_ROW) * (BOX_SIZE + BOX_PADDING * 2);
|
||||||
|
|
||||||
|
ctx.drawImage(
|
||||||
|
itemCanvas,
|
||||||
|
colOffset + (BOX_SIZE - width) / 2 + BOX_PADDING,
|
||||||
|
rowOffset + (BOX_SIZE - height) / 2 + BOX_PADDING,
|
||||||
|
);
|
||||||
|
|
||||||
|
// draw item border
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
ctx.lineWidth = BORDER_WIDTH;
|
||||||
|
ctx.strokeStyle = OpenColor.gray[4];
|
||||||
|
ctx.strokeRect(
|
||||||
|
colOffset + BOX_PADDING / 2,
|
||||||
|
rowOffset + BOX_PADDING / 2,
|
||||||
|
BOX_SIZE + BOX_PADDING,
|
||||||
|
BOX_SIZE + BOX_PADDING,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return await resizeImageFile(
|
||||||
|
new File([await canvasToBlob(canvas)], "preview", { type: MIME_TYPES.png }),
|
||||||
|
{
|
||||||
|
outputType: MIME_TYPES.jpg,
|
||||||
|
maxWidthOrHeight: 5000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
const PublishLibrary = ({
|
const PublishLibrary = ({
|
||||||
onClose,
|
onClose,
|
||||||
libraryItems,
|
libraryItems,
|
||||||
@@ -129,59 +201,12 @@ const PublishLibrary = ({
|
|||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const elements: ExcalidrawElement[] = [];
|
|
||||||
const prevBoundingBox = { minX: 0, minY: 0, maxX: 0, maxY: 0 };
|
|
||||||
clonedLibItems.forEach((libItem) => {
|
|
||||||
const boundingBox = getCommonBoundingBox(libItem.elements);
|
|
||||||
const width = boundingBox.maxX - boundingBox.minX + 30;
|
|
||||||
const height = boundingBox.maxY - boundingBox.minY + 30;
|
|
||||||
const offset = {
|
|
||||||
x: prevBoundingBox.maxX - boundingBox.minX,
|
|
||||||
y: prevBoundingBox.maxY - boundingBox.minY,
|
|
||||||
};
|
|
||||||
|
|
||||||
const itemsWithUpdatedCoords = libItem.elements.map((element) => {
|
const previewImage = await generatePreviewImage(clonedLibItems);
|
||||||
element = mutateElement(element, {
|
|
||||||
x: element.x + offset.x + 15,
|
|
||||||
y: element.y + offset.y + 15,
|
|
||||||
});
|
|
||||||
return element;
|
|
||||||
});
|
|
||||||
const items = [
|
|
||||||
...itemsWithUpdatedCoords,
|
|
||||||
newElement({
|
|
||||||
type: "rectangle",
|
|
||||||
width,
|
|
||||||
height,
|
|
||||||
x: prevBoundingBox.maxX,
|
|
||||||
y: prevBoundingBox.maxY,
|
|
||||||
strokeColor: "#ced4da",
|
|
||||||
backgroundColor: "transparent",
|
|
||||||
strokeStyle: "solid",
|
|
||||||
opacity: 100,
|
|
||||||
roughness: 0,
|
|
||||||
strokeSharpness: "sharp",
|
|
||||||
fillStyle: "solid",
|
|
||||||
strokeWidth: 1,
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
elements.push(...items);
|
|
||||||
prevBoundingBox.maxX = prevBoundingBox.maxX + width + 30;
|
|
||||||
});
|
|
||||||
const png = await exportToBlob({
|
|
||||||
elements,
|
|
||||||
mimeType: "image/png",
|
|
||||||
appState: {
|
|
||||||
...appState,
|
|
||||||
viewBackgroundColor: oc.white,
|
|
||||||
exportBackground: true,
|
|
||||||
},
|
|
||||||
files: null,
|
|
||||||
});
|
|
||||||
|
|
||||||
const libContent: ExportedLibraryData = {
|
const libContent: ExportedLibraryData = {
|
||||||
type: EXPORT_DATA_TYPES.excalidrawLibrary,
|
type: EXPORT_DATA_TYPES.excalidrawLibrary,
|
||||||
version: 2,
|
version: VERSIONS.excalidrawLibrary,
|
||||||
source: EXPORT_SOURCE,
|
source: EXPORT_SOURCE,
|
||||||
libraryItems: clonedLibItems,
|
libraryItems: clonedLibItems,
|
||||||
};
|
};
|
||||||
@@ -190,7 +215,8 @@ const PublishLibrary = ({
|
|||||||
|
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("excalidrawLib", lib);
|
formData.append("excalidrawLib", lib);
|
||||||
formData.append("excalidrawPng", png!);
|
formData.append("previewImage", previewImage);
|
||||||
|
formData.append("previewImageType", previewImage.type);
|
||||||
formData.append("title", libraryData.name);
|
formData.append("title", libraryData.name);
|
||||||
formData.append("authorName", libraryData.authorName);
|
formData.append("authorName", libraryData.authorName);
|
||||||
formData.append("githubHandle", libraryData.githubHandle);
|
formData.append("githubHandle", libraryData.githubHandle);
|
||||||
|
|||||||
@@ -8,17 +8,7 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
-webkit-tap-highlight-color: transparent;
|
-webkit-tap-highlight-color: transparent;
|
||||||
border-radius: var(--space-factor);
|
|
||||||
user-select: none;
|
user-select: none;
|
||||||
|
|
||||||
background-color: var(--button-gray-1);
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background-color: var(--button-gray-2);
|
|
||||||
}
|
|
||||||
&:active {
|
|
||||||
background-color: var(--button-gray-3);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon--plain {
|
.ToolIcon--plain {
|
||||||
@@ -29,6 +19,20 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.ToolIcon_type_radio,
|
||||||
|
.ToolIcon_type_checkbox {
|
||||||
|
& + .ToolIcon__icon {
|
||||||
|
background-color: var(--button-gray-1);
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background-color: var(--button-gray-2);
|
||||||
|
}
|
||||||
|
&:active {
|
||||||
|
background-color: var(--button-gray-3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
width: 2.5rem;
|
width: 2.5rem;
|
||||||
height: 2.5rem;
|
height: 2.5rem;
|
||||||
@@ -38,7 +42,11 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|
||||||
border-radius: var(--space-factor);
|
border-radius: var(--border-radius-lg);
|
||||||
|
|
||||||
|
& + .ToolIcon__label {
|
||||||
|
margin-inline-start: 0;
|
||||||
|
}
|
||||||
|
|
||||||
svg {
|
svg {
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -46,10 +54,6 @@
|
|||||||
fill: var(--icon-fill-color);
|
fill: var(--icon-fill-color);
|
||||||
color: var(--icon-fill-color);
|
color: var(--icon-fill-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
& + .ToolIcon__label {
|
|
||||||
margin-inline-start: 0;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon__label {
|
.ToolIcon__label {
|
||||||
@@ -79,7 +83,7 @@
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
|
|
||||||
&:focus {
|
&:focus-visible {
|
||||||
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,7 +125,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&:focus + .ToolIcon__icon {
|
&:focus-visible + .ToolIcon__icon {
|
||||||
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,10 +145,6 @@
|
|||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
&:focus {
|
|
||||||
box-shadow: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.ToolIcon__icon {
|
.ToolIcon__icon {
|
||||||
background-color: var(--button-gray-1);
|
background-color: var(--button-gray-1);
|
||||||
&:hover {
|
&:hover {
|
||||||
@@ -159,13 +159,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.ToolIcon.ToolIcon__lock {
|
|
||||||
margin-inline-end: var(--space-factor);
|
|
||||||
&.ToolIcon_type_floating {
|
|
||||||
margin-left: 0.1rem;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.ToolIcon__keybinding {
|
.ToolIcon__keybinding {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
bottom: 2px;
|
bottom: 2px;
|
||||||
@@ -226,6 +219,10 @@
|
|||||||
margin-inline-end: 0;
|
margin-inline-end: 0;
|
||||||
top: 60px;
|
top: 60px;
|
||||||
}
|
}
|
||||||
|
.ToolIcon.ToolIcon__penMode {
|
||||||
|
margin-inline-end: 0;
|
||||||
|
top: 140px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.unlocked-icon {
|
.unlocked-icon {
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
@import "open-color/open-color.scss";
|
||||||
|
|
||||||
|
@mixin toolbarButtonColorStates {
|
||||||
|
.ToolIcon_type_radio,
|
||||||
|
.ToolIcon_type_checkbox {
|
||||||
|
& + .ToolIcon__icon:active {
|
||||||
|
background: var(--color-primary-light);
|
||||||
|
}
|
||||||
|
&:checked + .ToolIcon__icon {
|
||||||
|
background: var(--color-primary);
|
||||||
|
--icon-fill-color: #{$oc-white};
|
||||||
|
--keybinding-color: #{$oc-white};
|
||||||
|
}
|
||||||
|
&:checked + .ToolIcon__icon:active {
|
||||||
|
background: var(--color-primary-darker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon__keybinding {
|
||||||
|
bottom: 4px;
|
||||||
|
right: 4px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.excalidraw {
|
||||||
|
.App-toolbar-container {
|
||||||
|
.ToolIcon_type_floating {
|
||||||
|
@include toolbarButtonColorStates;
|
||||||
|
|
||||||
|
&:not(.is-mobile) {
|
||||||
|
.ToolIcon__icon {
|
||||||
|
padding: 1px;
|
||||||
|
background-color: var(--island-bg-color);
|
||||||
|
box-shadow: 1px 3px 4px 0px rgb(0 0 0 / 15%);
|
||||||
|
border-radius: 50%;
|
||||||
|
transition: box-shadow 0.5s ease, transform 0.5s ease;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon_type_radio,
|
||||||
|
.ToolIcon_type_checkbox {
|
||||||
|
&:focus-within + .ToolIcon__icon {
|
||||||
|
// override for custom floating button shadow
|
||||||
|
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon__hidden {
|
||||||
|
box-shadow: none !important;
|
||||||
|
background-color: transparent !important;
|
||||||
|
pointer-events: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon.ToolIcon__lock {
|
||||||
|
margin-inline-end: var(--space-factor);
|
||||||
|
&.ToolIcon_type_floating {
|
||||||
|
margin-left: 0.1rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon__library {
|
||||||
|
margin-inline-start: var(--space-factor);
|
||||||
|
}
|
||||||
|
|
||||||
|
&.zen-mode {
|
||||||
|
.ToolIcon_type_floating {
|
||||||
|
.ToolIcon__icon {
|
||||||
|
box-shadow: none;
|
||||||
|
transform: scale(0.9);
|
||||||
|
}
|
||||||
|
.ToolIcon_type_checkbox:not(:checked):not(:hover):not(:active) {
|
||||||
|
& + .ToolIcon__icon {
|
||||||
|
svg {
|
||||||
|
fill: $oc-gray-5;
|
||||||
|
color: $oc-gray-5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.App-toolbar {
|
||||||
|
border-radius: var(--border-radius-lg);
|
||||||
|
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.01), 1px 1px 5px rgb(0 0 0 / 15%);
|
||||||
|
|
||||||
|
.ToolIcon {
|
||||||
|
&:hover {
|
||||||
|
--icon-fill-color: var(
|
||||||
|
--color-primary-contrast-offset,
|
||||||
|
var(--color-primary)
|
||||||
|
);
|
||||||
|
--keybinding-color: var(
|
||||||
|
--color-primary-contrast-offset,
|
||||||
|
var(--color-primary)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
&:active {
|
||||||
|
--icon-fill-color: #{$oc-gray-9};
|
||||||
|
--keybinding-color: #{$oc-gray-9};
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon__icon {
|
||||||
|
background: transparent;
|
||||||
|
border-radius: var(--border-radius-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@include toolbarButtonColorStates;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.zen-mode {
|
||||||
|
.ToolIcon__keybinding,
|
||||||
|
.HintViewer {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
&.theme--dark .App-toolbar .ToolIcon:active {
|
||||||
|
--icon-fill-color: #{$oc-gray-3};
|
||||||
|
--keybinding-color: #{$oc-gray-3};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,7 +29,6 @@
|
|||||||
// wraps the element we want to apply the tooltip to
|
// wraps the element we want to apply the tooltip to
|
||||||
.excalidraw-tooltip-wrapper {
|
.excalidraw-tooltip-wrapper {
|
||||||
display: flex;
|
display: flex;
|
||||||
height: 100%;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.excalidraw-tooltip-icon {
|
.excalidraw-tooltip-icon {
|
||||||
|
|||||||
+55
-32
@@ -2,7 +2,7 @@ import "./Tooltip.scss";
|
|||||||
|
|
||||||
import React, { useEffect } from "react";
|
import React, { useEffect } from "react";
|
||||||
|
|
||||||
const getTooltipDiv = () => {
|
export const getTooltipDiv = () => {
|
||||||
const existingDiv = document.querySelector<HTMLDivElement>(
|
const existingDiv = document.querySelector<HTMLDivElement>(
|
||||||
".excalidraw-tooltip",
|
".excalidraw-tooltip",
|
||||||
);
|
);
|
||||||
@@ -15,6 +15,50 @@ const getTooltipDiv = () => {
|
|||||||
return div;
|
return div;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const updateTooltipPosition = (
|
||||||
|
tooltip: HTMLDivElement,
|
||||||
|
item: {
|
||||||
|
left: number;
|
||||||
|
top: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
},
|
||||||
|
position: "bottom" | "top" = "bottom",
|
||||||
|
) => {
|
||||||
|
const tooltipRect = tooltip.getBoundingClientRect();
|
||||||
|
|
||||||
|
const viewportWidth = window.innerWidth;
|
||||||
|
const viewportHeight = window.innerHeight;
|
||||||
|
|
||||||
|
const margin = 5;
|
||||||
|
|
||||||
|
let left = item.left + item.width / 2 - tooltipRect.width / 2;
|
||||||
|
if (left < 0) {
|
||||||
|
left = margin;
|
||||||
|
} else if (left + tooltipRect.width >= viewportWidth) {
|
||||||
|
left = viewportWidth - tooltipRect.width - margin;
|
||||||
|
}
|
||||||
|
|
||||||
|
let top: number;
|
||||||
|
|
||||||
|
if (position === "bottom") {
|
||||||
|
top = item.top + item.height + margin;
|
||||||
|
if (top + tooltipRect.height >= viewportHeight) {
|
||||||
|
top = item.top - tooltipRect.height - margin;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
top = item.top - tooltipRect.height - margin;
|
||||||
|
if (top < 0) {
|
||||||
|
top = item.top + item.height + margin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.assign(tooltip.style, {
|
||||||
|
top: `${top}px`,
|
||||||
|
left: `${left}px`,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
const updateTooltip = (
|
const updateTooltip = (
|
||||||
item: HTMLDivElement,
|
item: HTMLDivElement,
|
||||||
tooltip: HTMLDivElement,
|
tooltip: HTMLDivElement,
|
||||||
@@ -27,49 +71,27 @@ const updateTooltip = (
|
|||||||
|
|
||||||
tooltip.textContent = label;
|
tooltip.textContent = label;
|
||||||
|
|
||||||
const {
|
const itemRect = item.getBoundingClientRect();
|
||||||
x: itemX,
|
updateTooltipPosition(tooltip, itemRect);
|
||||||
bottom: itemBottom,
|
|
||||||
top: itemTop,
|
|
||||||
width: itemWidth,
|
|
||||||
} = item.getBoundingClientRect();
|
|
||||||
|
|
||||||
const { width: labelWidth, height: labelHeight } =
|
|
||||||
tooltip.getBoundingClientRect();
|
|
||||||
|
|
||||||
const viewportWidth = window.innerWidth;
|
|
||||||
const viewportHeight = window.innerHeight;
|
|
||||||
|
|
||||||
const margin = 5;
|
|
||||||
|
|
||||||
const left = itemX + itemWidth / 2 - labelWidth / 2;
|
|
||||||
const offsetLeft =
|
|
||||||
left + labelWidth >= viewportWidth ? left + labelWidth - viewportWidth : 0;
|
|
||||||
|
|
||||||
const top = itemBottom + margin;
|
|
||||||
const offsetTop =
|
|
||||||
top + labelHeight >= viewportHeight
|
|
||||||
? itemBottom - itemTop + labelHeight + margin * 2
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
Object.assign(tooltip.style, {
|
|
||||||
top: `${top - offsetTop}px`,
|
|
||||||
left: `${left - offsetLeft}px`,
|
|
||||||
});
|
|
||||||
};
|
};
|
||||||
|
|
||||||
type TooltipProps = {
|
type TooltipProps = {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
label: string;
|
label: string;
|
||||||
long?: boolean;
|
long?: boolean;
|
||||||
|
style?: React.CSSProperties;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Tooltip = ({ children, label, long = false }: TooltipProps) => {
|
export const Tooltip = ({
|
||||||
|
children,
|
||||||
|
label,
|
||||||
|
long = false,
|
||||||
|
style,
|
||||||
|
}: TooltipProps) => {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () =>
|
return () =>
|
||||||
getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
|
getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="excalidraw-tooltip-wrapper"
|
className="excalidraw-tooltip-wrapper"
|
||||||
@@ -84,6 +106,7 @@ export const Tooltip = ({ children, label, long = false }: TooltipProps) => {
|
|||||||
onPointerLeave={() =>
|
onPointerLeave={() =>
|
||||||
getTooltipDiv().classList.remove("excalidraw-tooltip--visible")
|
getTooltipDiv().classList.remove("excalidraw-tooltip--visible")
|
||||||
}
|
}
|
||||||
|
style={style}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -7,6 +7,10 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
|
|
||||||
|
&:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.UserList > * {
|
.UserList > * {
|
||||||
|
|||||||
@@ -15,8 +15,9 @@ import { THEME } from "../constants";
|
|||||||
|
|
||||||
const activeElementColor = (theme: Theme) =>
|
const activeElementColor = (theme: Theme) =>
|
||||||
theme === THEME.LIGHT ? oc.orange[4] : oc.orange[9];
|
theme === THEME.LIGHT ? oc.orange[4] : oc.orange[9];
|
||||||
const iconFillColor = (theme: Theme) =>
|
|
||||||
theme === THEME.LIGHT ? oc.black : oc.gray[4];
|
const iconFillColor = (theme: Theme) => "var(--icon-fill-color)";
|
||||||
|
|
||||||
const handlerColor = (theme: Theme) =>
|
const handlerColor = (theme: Theme) =>
|
||||||
theme === THEME.LIGHT ? oc.white : "#1e1e1e";
|
theme === THEME.LIGHT ? oc.white : "#1e1e1e";
|
||||||
|
|
||||||
@@ -884,6 +885,40 @@ export const TextAlignRightIcon = React.memo(({ theme }: { theme: Theme }) =>
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const TextAlignTopIcon = React.memo(({ theme }: { theme: Theme }) =>
|
||||||
|
createIcon(
|
||||||
|
<path
|
||||||
|
d="m16,132l416,0c8.837,0 16,-7.163 16,-16l0,-40c0,-8.837 -7.163,-16 -16,-16l-416,0c-8.837,0 -16,7.163 -16,16l0,40c0,8.837 7.163,16 16,16zm0,160l416,0c8.837,0 16,-7.163 16,-16l0,-40c0,-8.837 -7.163,-16 -16,-16l-416,0c-8.837,0 -16,7.163 -16,16l0,40c0,8.837 7.163,16 16,16z"
|
||||||
|
fill={iconFillColor(theme)}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>,
|
||||||
|
{ width: 448, height: 512 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const TextAlignBottomIcon = React.memo(({ theme }: { theme: Theme }) =>
|
||||||
|
createIcon(
|
||||||
|
<path
|
||||||
|
d="M16,292L432,292C440.837,292 448,284.837 448,276L448,236C448,227.163 440.837,220 432,220L16,220C7.163,220 0,227.163 0,236L0,276C0,284.837 7.163,292 16,292ZM16,452L432,452C440.837,452 448,444.837 448,436L448,396C448,387.163 440.837,380 432,380L16,380C7.163,380 0,387.163 0,396L0,436C0,444.837 7.163,452 16,452Z"
|
||||||
|
fill={iconFillColor(theme)}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>,
|
||||||
|
{ width: 448, height: 512 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export const TextAlignMiddleIcon = React.memo(({ theme }: { theme: Theme }) =>
|
||||||
|
createIcon(
|
||||||
|
<path
|
||||||
|
transform="matrix(1,0,0,1,0,80)"
|
||||||
|
d="M16,132L432,132C440.837,132 448,124.837 448,116L448,76C448,67.163 440.837,60 432,60L16,60C7.163,60 0,67.163 0,76L0,116C0,124.837 7.163,132 16,132ZM16,292L432,292C440.837,292 448,284.837 448,276L448,236C448,227.163 440.837,220 432,220L16,220C7.163,220 0,227.163 0,236L0,276C0,284.837 7.163,292 16,292Z"
|
||||||
|
fill={iconFillColor(theme)}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>,
|
||||||
|
{ width: 448, height: 512 },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
export const publishIcon = createIcon(
|
export const publishIcon = createIcon(
|
||||||
<path
|
<path
|
||||||
d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z"
|
d="M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z"
|
||||||
@@ -891,3 +926,11 @@ export const publishIcon = createIcon(
|
|||||||
/>,
|
/>,
|
||||||
{ width: 640, height: 512 },
|
{ width: 640, height: 512 },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
export const editIcon = createIcon(
|
||||||
|
<path
|
||||||
|
fill="currentColor"
|
||||||
|
d="M402.3 344.9l32-32c5-5 13.7-1.5 13.7 5.7V464c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h273.5c7.1 0 10.7 8.6 5.7 13.7l-32 32c-1.5 1.5-3.5 2.3-5.7 2.3H48v352h352V350.5c0-2.1.8-4.1 2.3-5.6zm156.6-201.8L296.3 405.7l-90.4 10c-26.2 2.9-48.5-19.2-45.6-45.6l10-90.4L432.9 17.1c22.9-22.9 59.9-22.9 82.7 0l43.2 43.2c22.9 22.9 22.9 60 .1 82.8zM460.1 174L402 115.9 216.2 301.8l-7.3 65.3 65.3-7.3L460.1 174zm64.8-79.7l-43.2-43.2c-4.1-4.1-10.8-4.1-14.8 0L436 82l58.1 58.1 30.9-30.9c4-4.2 4-10.8-.1-14.9z"
|
||||||
|
></path>,
|
||||||
|
{ width: 640, height: 512 },
|
||||||
|
);
|
||||||
|
|||||||
+20
-7
@@ -24,7 +24,7 @@ export const POINTER_BUTTON = {
|
|||||||
WHEEL: 1,
|
WHEEL: 1,
|
||||||
SECONDARY: 2,
|
SECONDARY: 2,
|
||||||
TOUCH: -1,
|
TOUCH: -1,
|
||||||
};
|
} as const;
|
||||||
|
|
||||||
export enum EVENT {
|
export enum EVENT {
|
||||||
COPY = "copy",
|
COPY = "copy",
|
||||||
@@ -52,6 +52,8 @@ export enum EVENT {
|
|||||||
HASHCHANGE = "hashchange",
|
HASHCHANGE = "hashchange",
|
||||||
VISIBILITY_CHANGE = "visibilitychange",
|
VISIBILITY_CHANGE = "visibilitychange",
|
||||||
SCROLL = "scroll",
|
SCROLL = "scroll",
|
||||||
|
// custom events
|
||||||
|
EXCALIDRAW_LINK = "excalidraw-link",
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ENV = {
|
export const ENV = {
|
||||||
@@ -61,6 +63,8 @@ export const ENV = {
|
|||||||
|
|
||||||
export const CLASSES = {
|
export const CLASSES = {
|
||||||
SHAPE_ACTIONS_MENU: "App-menu__left",
|
SHAPE_ACTIONS_MENU: "App-menu__left",
|
||||||
|
SHAPE_ACTIONS_MOBILE_MENU: "App-mobile-menu",
|
||||||
|
MOBILE_TOOLBAR: "App-toolbar-content",
|
||||||
};
|
};
|
||||||
|
|
||||||
// 1-based in case we ever do `if(element.fontFamily)`
|
// 1-based in case we ever do `if(element.fontFamily)`
|
||||||
@@ -106,10 +110,6 @@ export const EXPORT_DATA_TYPES = {
|
|||||||
|
|
||||||
export const EXPORT_SOURCE = window.location.origin;
|
export const EXPORT_SOURCE = window.location.origin;
|
||||||
|
|
||||||
export const STORAGE_KEYS = {
|
|
||||||
LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
// time in milliseconds
|
// time in milliseconds
|
||||||
export const IMAGE_RENDER_TIMEOUT = 500;
|
export const IMAGE_RENDER_TIMEOUT = 500;
|
||||||
export const TAP_TWICE_TIMEOUT = 300;
|
export const TAP_TWICE_TIMEOUT = 300;
|
||||||
@@ -119,6 +119,7 @@ export const TOAST_TIMEOUT = 5000;
|
|||||||
export const VERSION_TIMEOUT = 30000;
|
export const VERSION_TIMEOUT = 30000;
|
||||||
export const SCROLL_TIMEOUT = 100;
|
export const SCROLL_TIMEOUT = 100;
|
||||||
export const ZOOM_STEP = 0.1;
|
export const ZOOM_STEP = 0.1;
|
||||||
|
export const HYPERLINK_TOOLTIP_DELAY = 300;
|
||||||
|
|
||||||
// Report a user inactive after IDLE_THRESHOLD milliseconds
|
// Report a user inactive after IDLE_THRESHOLD milliseconds
|
||||||
export const IDLE_THRESHOLD = 60_000;
|
export const IDLE_THRESHOLD = 60_000;
|
||||||
@@ -162,8 +163,7 @@ export const MAX_DECIMALS_FOR_SVG_EXPORT = 2;
|
|||||||
export const EXPORT_SCALES = [1, 2, 3];
|
export const EXPORT_SCALES = [1, 2, 3];
|
||||||
export const DEFAULT_EXPORT_PADDING = 10; // px
|
export const DEFAULT_EXPORT_PADDING = 10; // px
|
||||||
|
|
||||||
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_JPG = 10000;
|
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT = 1440;
|
||||||
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT_OTHER = 1440;
|
|
||||||
|
|
||||||
export const ALLOWED_IMAGE_MIME_TYPES = [
|
export const ALLOWED_IMAGE_MIME_TYPES = [
|
||||||
MIME_TYPES.png,
|
MIME_TYPES.png,
|
||||||
@@ -177,3 +177,16 @@ export const MAX_ALLOWED_FILE_BYTES = 2 * 1024 * 1024;
|
|||||||
export const SVG_NS = "http://www.w3.org/2000/svg";
|
export const SVG_NS = "http://www.w3.org/2000/svg";
|
||||||
|
|
||||||
export const ENCRYPTION_KEY_BITS = 128;
|
export const ENCRYPTION_KEY_BITS = 128;
|
||||||
|
|
||||||
|
export const VERSIONS = {
|
||||||
|
excalidraw: 2,
|
||||||
|
excalidrawLibrary: 2,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const BOUND_TEXT_PADDING = 5;
|
||||||
|
|
||||||
|
export const VERTICAL_ALIGN = {
|
||||||
|
TOP: "top",
|
||||||
|
MIDDLE: "middle",
|
||||||
|
BOTTOM: "bottom",
|
||||||
|
};
|
||||||
|
|||||||
+10
-8
@@ -180,7 +180,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.buttonList label:focus-within,
|
.buttonList label:focus-within,
|
||||||
input:focus {
|
input:focus-visible {
|
||||||
outline: transparent;
|
outline: transparent;
|
||||||
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
||||||
}
|
}
|
||||||
@@ -190,14 +190,14 @@
|
|||||||
user-select: none;
|
user-select: none;
|
||||||
background-color: var(--button-gray-1);
|
background-color: var(--button-gray-1);
|
||||||
border: 0;
|
border: 0;
|
||||||
border-radius: 4px;
|
border-radius: var(--border-radius-md);
|
||||||
margin: 0.125rem 0;
|
margin: 0.125rem 0;
|
||||||
padding: 0.25rem;
|
padding: 0.25rem;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
|
||||||
&:focus {
|
&:focus-visible {
|
||||||
outline: transparent;
|
outline: transparent;
|
||||||
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
box-shadow: 0 0 0 2px var(--focus-highlight-color);
|
||||||
}
|
}
|
||||||
@@ -217,14 +217,16 @@
|
|||||||
|
|
||||||
.active,
|
.active,
|
||||||
.buttonList label.active {
|
.buttonList label.active {
|
||||||
background-color: var(--button-gray-2);
|
background-color: var(--color-primary);
|
||||||
|
|
||||||
|
--icon-fill-color: #{$oc-white};
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: var(--button-gray-2);
|
background-color: var(--color-primary-darker);
|
||||||
}
|
}
|
||||||
|
|
||||||
&:active {
|
&:active {
|
||||||
background-color: var(--button-gray-3);
|
background-color: var(--color-primary-darkest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +236,7 @@
|
|||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
svg {
|
svg {
|
||||||
width: 36px;
|
width: 35px;
|
||||||
height: 14px;
|
height: 14px;
|
||||||
padding: 2px;
|
padding: 2px;
|
||||||
opacity: 0.6;
|
opacity: 0.6;
|
||||||
@@ -311,7 +313,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.App-menu_top {
|
.App-menu_top {
|
||||||
grid-template-columns: 1fr auto 1fr;
|
grid-template-columns: auto max-content auto;
|
||||||
grid-gap: 4px;
|
grid-gap: 4px;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
cursor: default;
|
cursor: default;
|
||||||
|
|||||||
+17
-3
@@ -12,7 +12,7 @@
|
|||||||
--dialog-border-color: #{$oc-gray-6};
|
--dialog-border-color: #{$oc-gray-6};
|
||||||
--dropdown-icon: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="292.4" height="292.4" viewBox="0 0 292 292"><path d="M287 197L159 69c-4-3-8-5-13-5s-9 2-13 5L5 197c-3 4-5 8-5 13s2 9 5 13c4 4 8 5 13 5h256c5 0 9-1 13-5s5-8 5-13-1-9-5-13z"/></svg>');
|
--dropdown-icon: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="292.4" height="292.4" viewBox="0 0 292 292"><path d="M287 197L159 69c-4-3-8-5-13-5s-9 2-13 5L5 197c-3 4-5 8-5 13s2 9 5 13c4 4 8 5 13 5h256c5 0 9-1 13-5s5-8 5-13-1-9-5-13z"/></svg>');
|
||||||
--focus-highlight-color: #{$oc-blue-2};
|
--focus-highlight-color: #{$oc-blue-2};
|
||||||
--icon-fill-color: #{$oc-black};
|
--icon-fill-color: #{$oc-gray-9};
|
||||||
--icon-green-fill-color: #{$oc-green-9};
|
--icon-green-fill-color: #{$oc-green-9};
|
||||||
--default-bg-color: #{$oc-white};
|
--default-bg-color: #{$oc-white};
|
||||||
--input-bg-color: #{$oc-white};
|
--input-bg-color: #{$oc-white};
|
||||||
@@ -32,10 +32,19 @@
|
|||||||
--sar: env(safe-area-inset-right);
|
--sar: env(safe-area-inset-right);
|
||||||
--sat: env(safe-area-inset-top);
|
--sat: env(safe-area-inset-top);
|
||||||
--select-highlight-color: #{$oc-blue-5};
|
--select-highlight-color: #{$oc-blue-5};
|
||||||
--shadow-island: 0 1px 5px #{transparentize($oc-black, 0.85)};
|
--shadow-island: 0 0 0 1px rgba(0, 0, 0, 0.01), 1px 1px 5px rgb(0 0 0 / 12%);
|
||||||
|
|
||||||
--space-factor: 0.25rem;
|
--space-factor: 0.25rem;
|
||||||
--text-primary-color: #{$oc-gray-8};
|
--text-primary-color: #{$oc-gray-8};
|
||||||
|
|
||||||
|
--color-primary: #6965db;
|
||||||
|
--color-primary-darker: #5b57d1;
|
||||||
|
--color-primary-darkest: #4a47b1;
|
||||||
|
--color-primary-light: #e2e1fc;
|
||||||
|
|
||||||
|
--border-radius-md: 0.375rem;
|
||||||
|
--border-radius-lg: 0.5rem;
|
||||||
|
|
||||||
&.theme--dark {
|
&.theme--dark {
|
||||||
background: $oc-black;
|
background: $oc-black;
|
||||||
|
|
||||||
@@ -71,7 +80,12 @@
|
|||||||
--popup-text-color: #{$oc-gray-4};
|
--popup-text-color: #{$oc-gray-4};
|
||||||
--popup-text-inverted-color: #2c2c2c;
|
--popup-text-inverted-color: #2c2c2c;
|
||||||
--select-highlight-color: #{$oc-blue-4};
|
--select-highlight-color: #{$oc-blue-4};
|
||||||
--shadow-island: 0 1px 5px #{transparentize($oc-black, 0.7)};
|
--shadow-island: 1px 1px 5px #{transparentize($oc-black, 0.7)};
|
||||||
--text-primary-color: #{$oc-gray-4};
|
--text-primary-color: #{$oc-gray-4};
|
||||||
|
|
||||||
|
--color-primary: #5650f0;
|
||||||
|
--color-primary-darker: #4b46d8;
|
||||||
|
--color-primary-darkest: #3e39be;
|
||||||
|
--color-primary-light: #3f3d64;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-3
@@ -271,8 +271,6 @@ export const resizeImageFile = async (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileType = file.type;
|
|
||||||
|
|
||||||
if (!isSupportedImageFile(file)) {
|
if (!isSupportedImageFile(file)) {
|
||||||
throw new Error(t("errors.unsupportedFileType"));
|
throw new Error(t("errors.unsupportedFileType"));
|
||||||
}
|
}
|
||||||
@@ -281,7 +279,7 @@ export const resizeImageFile = async (
|
|||||||
[await reduce.toBlob(file, { max: opts.maxWidthOrHeight })],
|
[await reduce.toBlob(file, { max: opts.maxWidthOrHeight })],
|
||||||
file.name,
|
file.name,
|
||||||
{
|
{
|
||||||
type: fileType,
|
type: opts.outputType || file.type,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
+13
-1
@@ -234,7 +234,19 @@ const splitBuffers = (concatenatedBuffer: Uint8Array) => {
|
|||||||
|
|
||||||
let cursor = 0;
|
let cursor = 0;
|
||||||
|
|
||||||
// first chunk is the version (ignored for now)
|
// first chunk is the version
|
||||||
|
const version = dataView(
|
||||||
|
concatenatedBuffer,
|
||||||
|
NEXT_CHUNK_SIZE_DATAVIEW_BYTES,
|
||||||
|
cursor,
|
||||||
|
);
|
||||||
|
// If version is outside of the supported versions, throw an error.
|
||||||
|
// This usually means the buffer wasn't encoded using this API, so we'd only
|
||||||
|
// waste compute.
|
||||||
|
if (version > CONCAT_BUFFERS_VERSION) {
|
||||||
|
throw new Error(`invalid version ${version}`);
|
||||||
|
}
|
||||||
|
|
||||||
cursor += VERSION_DATAVIEW_BYTES;
|
cursor += VERSION_DATAVIEW_BYTES;
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
|||||||
+3
-32
@@ -1,11 +1,8 @@
|
|||||||
import extractPngChunks from "png-chunks-extract";
|
import decodePng from "png-chunks-extract";
|
||||||
import tEXt from "png-chunk-text";
|
import tEXt from "png-chunk-text";
|
||||||
import encodePng from "png-chunks-encode";
|
import encodePng from "png-chunks-encode";
|
||||||
import { stringToBase64, encode, decode, base64ToString } from "./encode";
|
import { stringToBase64, encode, decode, base64ToString } from "./encode";
|
||||||
import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants";
|
import { EXPORT_DATA_TYPES, MIME_TYPES } from "../constants";
|
||||||
import { PngChunk } from "../types";
|
|
||||||
|
|
||||||
export { extractPngChunks };
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// PNG
|
// PNG
|
||||||
@@ -31,9 +28,7 @@ const blobToArrayBuffer = (blob: Blob): Promise<ArrayBuffer> => {
|
|||||||
export const getTEXtChunk = async (
|
export const getTEXtChunk = async (
|
||||||
blob: Blob,
|
blob: Blob,
|
||||||
): Promise<{ keyword: string; text: string } | null> => {
|
): Promise<{ keyword: string; text: string } | null> => {
|
||||||
const chunks = extractPngChunks(
|
const chunks = decodePng(new Uint8Array(await blobToArrayBuffer(blob)));
|
||||||
new Uint8Array(await blobToArrayBuffer(blob)),
|
|
||||||
);
|
|
||||||
const metadataChunk = chunks.find((chunk) => chunk.name === "tEXt");
|
const metadataChunk = chunks.find((chunk) => chunk.name === "tEXt");
|
||||||
if (metadataChunk) {
|
if (metadataChunk) {
|
||||||
return tEXt.decode(metadataChunk.data);
|
return tEXt.decode(metadataChunk.data);
|
||||||
@@ -41,28 +36,6 @@ export const getTEXtChunk = async (
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const findPngChunk = (
|
|
||||||
chunks: PngChunk[],
|
|
||||||
name: PngChunk["name"],
|
|
||||||
/** this makes the search stop before IDAT chunk (before which most
|
|
||||||
* metadata chunks reside). This is a perf optim. */
|
|
||||||
breakBeforeIDAT = true,
|
|
||||||
) => {
|
|
||||||
let i = 0;
|
|
||||||
const len = chunks.length;
|
|
||||||
while (i <= len) {
|
|
||||||
const chunk = chunks[i];
|
|
||||||
if (chunk.name === name) {
|
|
||||||
return chunk;
|
|
||||||
}
|
|
||||||
if (breakBeforeIDAT && chunk.name === "IDAT") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const encodePngMetadata = async ({
|
export const encodePngMetadata = async ({
|
||||||
blob,
|
blob,
|
||||||
metadata,
|
metadata,
|
||||||
@@ -70,9 +43,7 @@ export const encodePngMetadata = async ({
|
|||||||
blob: Blob;
|
blob: Blob;
|
||||||
metadata: string;
|
metadata: string;
|
||||||
}) => {
|
}) => {
|
||||||
const chunks = extractPngChunks(
|
const chunks = decodePng(new Uint8Array(await blobToArrayBuffer(blob)));
|
||||||
new Uint8Array(await blobToArrayBuffer(blob)),
|
|
||||||
);
|
|
||||||
|
|
||||||
const metadataChunk = tEXt.encode(
|
const metadataChunk = tEXt.encode(
|
||||||
MIME_TYPES.excalidraw,
|
MIME_TYPES.excalidraw,
|
||||||
|
|||||||
+8
-3
@@ -1,6 +1,11 @@
|
|||||||
import { fileOpen, fileSave } from "./filesystem";
|
import { fileOpen, fileSave } from "./filesystem";
|
||||||
import { cleanAppStateForExport, clearAppStateForDatabase } from "../appState";
|
import { cleanAppStateForExport, clearAppStateForDatabase } from "../appState";
|
||||||
import { EXPORT_DATA_TYPES, EXPORT_SOURCE, MIME_TYPES } from "../constants";
|
import {
|
||||||
|
EXPORT_DATA_TYPES,
|
||||||
|
EXPORT_SOURCE,
|
||||||
|
MIME_TYPES,
|
||||||
|
VERSIONS,
|
||||||
|
} from "../constants";
|
||||||
import { clearElementsForDatabase, clearElementsForExport } from "../element";
|
import { clearElementsForDatabase, clearElementsForExport } from "../element";
|
||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { AppState, BinaryFiles, LibraryItems } from "../types";
|
import { AppState, BinaryFiles, LibraryItems } from "../types";
|
||||||
@@ -42,7 +47,7 @@ export const serializeAsJSON = (
|
|||||||
): string => {
|
): string => {
|
||||||
const data: ExportedDataState = {
|
const data: ExportedDataState = {
|
||||||
type: EXPORT_DATA_TYPES.excalidraw,
|
type: EXPORT_DATA_TYPES.excalidraw,
|
||||||
version: 2,
|
version: VERSIONS.excalidraw,
|
||||||
source: EXPORT_SOURCE,
|
source: EXPORT_SOURCE,
|
||||||
elements:
|
elements:
|
||||||
type === "local"
|
type === "local"
|
||||||
@@ -121,7 +126,7 @@ export const isValidLibrary = (json: any) => {
|
|||||||
export const saveLibraryAsJSON = async (libraryItems: LibraryItems) => {
|
export const saveLibraryAsJSON = async (libraryItems: LibraryItems) => {
|
||||||
const data: ExportedLibraryData = {
|
const data: ExportedLibraryData = {
|
||||||
type: EXPORT_DATA_TYPES.excalidrawLibrary,
|
type: EXPORT_DATA_TYPES.excalidrawLibrary,
|
||||||
version: 2,
|
version: VERSIONS.excalidrawLibrary,
|
||||||
source: EXPORT_SOURCE,
|
source: EXPORT_SOURCE,
|
||||||
libraryItems,
|
libraryItems,
|
||||||
};
|
};
|
||||||
|
|||||||
+16
-10
@@ -10,11 +10,7 @@ import {
|
|||||||
NormalizedZoomValue,
|
NormalizedZoomValue,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import { ImportedDataState } from "./types";
|
import { ImportedDataState } from "./types";
|
||||||
import {
|
import { getNormalizedDimensions, isInvisiblySmallElement } from "../element";
|
||||||
getElementMap,
|
|
||||||
getNormalizedDimensions,
|
|
||||||
isInvisiblySmallElement,
|
|
||||||
} from "../element";
|
|
||||||
import { isLinearElementType } from "../element/typeChecks";
|
import { isLinearElementType } from "../element/typeChecks";
|
||||||
import { randomId } from "../random";
|
import { randomId } from "../random";
|
||||||
import {
|
import {
|
||||||
@@ -26,6 +22,8 @@ import {
|
|||||||
import { getDefaultAppState } from "../appState";
|
import { getDefaultAppState } from "../appState";
|
||||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||||
import { bumpVersion } from "../element/mutateElement";
|
import { bumpVersion } from "../element/mutateElement";
|
||||||
|
import { getUpdatedTimestamp } from "../utils";
|
||||||
|
import { arrayToMap } from "../utils";
|
||||||
|
|
||||||
type RestoredAppState = Omit<
|
type RestoredAppState = Omit<
|
||||||
AppState,
|
AppState,
|
||||||
@@ -66,7 +64,10 @@ const restoreElementWithProperties = <
|
|||||||
T extends ExcalidrawElement,
|
T extends ExcalidrawElement,
|
||||||
K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>,
|
K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>,
|
||||||
>(
|
>(
|
||||||
element: Required<T>,
|
element: Required<T> & {
|
||||||
|
/** @deprecated */
|
||||||
|
boundElementIds?: readonly ExcalidrawElement["id"][];
|
||||||
|
},
|
||||||
extra: Pick<
|
extra: Pick<
|
||||||
T,
|
T,
|
||||||
// This extra Pick<T, keyof K> ensure no excess properties are passed.
|
// This extra Pick<T, keyof K> ensure no excess properties are passed.
|
||||||
@@ -100,7 +101,11 @@ const restoreElementWithProperties = <
|
|||||||
strokeSharpness:
|
strokeSharpness:
|
||||||
element.strokeSharpness ??
|
element.strokeSharpness ??
|
||||||
(isLinearElementType(element.type) ? "round" : "sharp"),
|
(isLinearElementType(element.type) ? "round" : "sharp"),
|
||||||
boundElementIds: element.boundElementIds ?? [],
|
boundElements: element.boundElementIds
|
||||||
|
? element.boundElementIds.map((id) => ({ type: "arrow", id }))
|
||||||
|
: element.boundElements ?? [],
|
||||||
|
updated: element.updated ?? getUpdatedTimestamp(),
|
||||||
|
link: element.link ?? null,
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -131,6 +136,8 @@ const restoreElement = (
|
|||||||
baseline: element.baseline,
|
baseline: element.baseline,
|
||||||
textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
|
textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
|
||||||
verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
|
verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
|
||||||
|
containerId: element.containerId ?? null,
|
||||||
|
originalText: element.originalText || element.text,
|
||||||
});
|
});
|
||||||
case "freedraw": {
|
case "freedraw": {
|
||||||
return restoreElementWithProperties(element, {
|
return restoreElementWithProperties(element, {
|
||||||
@@ -204,14 +211,14 @@ export const restoreElements = (
|
|||||||
/** NOTE doesn't serve for reconciliation */
|
/** NOTE doesn't serve for reconciliation */
|
||||||
localElements: readonly ExcalidrawElement[] | null | undefined,
|
localElements: readonly ExcalidrawElement[] | null | undefined,
|
||||||
): ExcalidrawElement[] => {
|
): ExcalidrawElement[] => {
|
||||||
const localElementsMap = localElements ? getElementMap(localElements) : null;
|
const localElementsMap = localElements ? arrayToMap(localElements) : null;
|
||||||
return (elements || []).reduce((elements, element) => {
|
return (elements || []).reduce((elements, element) => {
|
||||||
// filtering out selection, which is legacy, no longer kept in elements,
|
// filtering out selection, which is legacy, no longer kept in elements,
|
||||||
// and causing issues if retained
|
// and causing issues if retained
|
||||||
if (element.type !== "selection" && !isInvisiblySmallElement(element)) {
|
if (element.type !== "selection" && !isInvisiblySmallElement(element)) {
|
||||||
let migratedElement: ExcalidrawElement | null = restoreElement(element);
|
let migratedElement: ExcalidrawElement | null = restoreElement(element);
|
||||||
if (migratedElement) {
|
if (migratedElement) {
|
||||||
const localElement = localElementsMap?.[element.id];
|
const localElement = localElementsMap?.get(element.id);
|
||||||
if (localElement && localElement.version > migratedElement.version) {
|
if (localElement && localElement.version > migratedElement.version) {
|
||||||
migratedElement = bumpVersion(migratedElement, localElement.version);
|
migratedElement = bumpVersion(migratedElement, localElement.version);
|
||||||
}
|
}
|
||||||
@@ -255,7 +262,6 @@ export const restoreAppState = (
|
|||||||
typeof appState.zoom === "number"
|
typeof appState.zoom === "number"
|
||||||
? {
|
? {
|
||||||
value: appState.zoom as NormalizedZoomValue,
|
value: appState.zoom as NormalizedZoomValue,
|
||||||
translation: defaultAppState.zoom.translation,
|
|
||||||
}
|
}
|
||||||
: appState.zoom || defaultAppState.zoom,
|
: appState.zoom || defaultAppState.zoom,
|
||||||
};
|
};
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { AppState, BinaryFiles, LibraryItems, LibraryItems_v1 } from "../types";
|
import { AppState, BinaryFiles, LibraryItems, LibraryItems_v1 } from "../types";
|
||||||
import type { cleanAppStateForExport } from "../appState";
|
import type { cleanAppStateForExport } from "../appState";
|
||||||
|
import { VERSIONS } from "../constants";
|
||||||
|
|
||||||
export interface ExportedDataState {
|
export interface ExportedDataState {
|
||||||
type: string;
|
type: string;
|
||||||
@@ -24,7 +25,7 @@ export interface ImportedDataState {
|
|||||||
|
|
||||||
export interface ExportedLibraryData {
|
export interface ExportedLibraryData {
|
||||||
type: string;
|
type: string;
|
||||||
version: 2;
|
version: typeof VERSIONS.excalidrawLibrary;
|
||||||
source: string;
|
source: string;
|
||||||
libraryItems: LibraryItems;
|
libraryItems: LibraryItems;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-48
@@ -1,17 +1,7 @@
|
|||||||
import { ExcalidrawElement } from "./element/types";
|
import { ExcalidrawElement } from "./element/types";
|
||||||
import { newElementWith } from "./element/mutateElement";
|
import { newElementWith } from "./element/mutateElement";
|
||||||
import { getCommonBounds } from "./element";
|
import { getMaximumGroups } from "./groups";
|
||||||
|
import { getCommonBoundingBox } from "./element/bounds";
|
||||||
interface Box {
|
|
||||||
minX: number;
|
|
||||||
minY: number;
|
|
||||||
maxX: number;
|
|
||||||
maxY: number;
|
|
||||||
midX: number;
|
|
||||||
midY: number;
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Distribution {
|
export interface Distribution {
|
||||||
space: "between";
|
space: "between";
|
||||||
@@ -98,39 +88,3 @@ export const distributeElements = (
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getMaximumGroups = (
|
|
||||||
elements: ExcalidrawElement[],
|
|
||||||
): ExcalidrawElement[][] => {
|
|
||||||
const groups: Map<String, ExcalidrawElement[]> = new Map<
|
|
||||||
String,
|
|
||||||
ExcalidrawElement[]
|
|
||||||
>();
|
|
||||||
|
|
||||||
elements.forEach((element: ExcalidrawElement) => {
|
|
||||||
const groupId =
|
|
||||||
element.groupIds.length === 0
|
|
||||||
? element.id
|
|
||||||
: element.groupIds[element.groupIds.length - 1];
|
|
||||||
|
|
||||||
const currentGroupMembers = groups.get(groupId) || [];
|
|
||||||
|
|
||||||
groups.set(groupId, [...currentGroupMembers, element]);
|
|
||||||
});
|
|
||||||
|
|
||||||
return Array.from(groups.values());
|
|
||||||
};
|
|
||||||
|
|
||||||
const getCommonBoundingBox = (elements: ExcalidrawElement[]): Box => {
|
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
|
||||||
return {
|
|
||||||
minX,
|
|
||||||
minY,
|
|
||||||
maxX,
|
|
||||||
maxY,
|
|
||||||
width: maxX - minX,
|
|
||||||
height: maxY - minY,
|
|
||||||
midX: (minX + maxX) / 2,
|
|
||||||
midY: (minY + maxY) / 2,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
@import "../css/variables.module";
|
||||||
|
|
||||||
|
.excalidraw-hyperlinkContainer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
position: absolute;
|
||||||
|
box-shadow: 0px 2px 4px 0 rgb(0 0 0 / 30%);
|
||||||
|
z-index: 100;
|
||||||
|
background: var(--island-bg-color);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
box-sizing: border-box;
|
||||||
|
// to account for LS due to rendering icons after new link created
|
||||||
|
min-height: 42px;
|
||||||
|
|
||||||
|
&-input,
|
||||||
|
button {
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
&-input,
|
||||||
|
&-link {
|
||||||
|
height: 24px;
|
||||||
|
padding: 0 8px;
|
||||||
|
line-height: 24px;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-family: var(--ui-font);
|
||||||
|
}
|
||||||
|
|
||||||
|
&-input {
|
||||||
|
width: 18rem;
|
||||||
|
border: none;
|
||||||
|
background-color: transparent;
|
||||||
|
color: var(--text-primary-color);
|
||||||
|
|
||||||
|
outline: none;
|
||||||
|
border: none;
|
||||||
|
box-shadow: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
&-link {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
max-width: 15rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
color: $oc-blue-6;
|
||||||
|
background-color: transparent !important;
|
||||||
|
font-weight: 500;
|
||||||
|
&.excalidraw-hyperlinkContainer--remove {
|
||||||
|
color: $oc-red-9;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.d-none {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
&--remove .ToolIcon__icon svg {
|
||||||
|
color: $oc-red-6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ToolIcon__icon {
|
||||||
|
width: 2rem;
|
||||||
|
height: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
&__buttons {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,465 @@
|
|||||||
|
import { AppState, ExcalidrawProps, Point } from "../types";
|
||||||
|
import {
|
||||||
|
getShortcutKey,
|
||||||
|
sceneCoordsToViewportCoords,
|
||||||
|
viewportCoordsToSceneCoords,
|
||||||
|
wrapEvent,
|
||||||
|
} from "../utils";
|
||||||
|
import { mutateElement } from "./mutateElement";
|
||||||
|
import { NonDeletedExcalidrawElement } from "./types";
|
||||||
|
|
||||||
|
import { register } from "../actions/register";
|
||||||
|
import { ToolButton } from "../components/ToolButton";
|
||||||
|
import { editIcon, link, trash } from "../components/icons";
|
||||||
|
import { t } from "../i18n";
|
||||||
|
import {
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useLayoutEffect,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from "react";
|
||||||
|
import clsx from "clsx";
|
||||||
|
import { KEYS } from "../keys";
|
||||||
|
import { DEFAULT_LINK_SIZE } from "../renderer/renderElement";
|
||||||
|
import { rotate } from "../math";
|
||||||
|
import { EVENT, HYPERLINK_TOOLTIP_DELAY, MIME_TYPES } from "../constants";
|
||||||
|
import { Bounds } from "./bounds";
|
||||||
|
import { getTooltipDiv, updateTooltipPosition } from "../components/Tooltip";
|
||||||
|
import { getSelectedElements } from "../scene";
|
||||||
|
import { isPointHittingElementBoundingBox } from "./collision";
|
||||||
|
import { getElementAbsoluteCoords } from "./";
|
||||||
|
|
||||||
|
import "./Hyperlink.scss";
|
||||||
|
import { trackEvent } from "../analytics";
|
||||||
|
|
||||||
|
const CONTAINER_WIDTH = 320;
|
||||||
|
const SPACE_BOTTOM = 85;
|
||||||
|
const CONTAINER_PADDING = 5;
|
||||||
|
const CONTAINER_HEIGHT = 42;
|
||||||
|
const AUTO_HIDE_TIMEOUT = 500;
|
||||||
|
|
||||||
|
export const EXTERNAL_LINK_IMG = document.createElement("img");
|
||||||
|
EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
|
||||||
|
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-external-link"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
|
||||||
|
)}`;
|
||||||
|
|
||||||
|
let IS_HYPERLINK_TOOLTIP_VISIBLE = false;
|
||||||
|
|
||||||
|
export const Hyperlink = ({
|
||||||
|
element,
|
||||||
|
appState,
|
||||||
|
setAppState,
|
||||||
|
onLinkOpen,
|
||||||
|
}: {
|
||||||
|
element: NonDeletedExcalidrawElement;
|
||||||
|
appState: AppState;
|
||||||
|
setAppState: React.Component<any, AppState>["setState"];
|
||||||
|
onLinkOpen: ExcalidrawProps["onLinkOpen"];
|
||||||
|
}) => {
|
||||||
|
const linkVal = element.link || "";
|
||||||
|
|
||||||
|
const [inputVal, setInputVal] = useState(linkVal);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const isEditing = appState.showHyperlinkPopup === "editor" || !linkVal;
|
||||||
|
|
||||||
|
const handleSubmit = useCallback(() => {
|
||||||
|
if (!inputRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = normalizeLink(inputRef.current.value);
|
||||||
|
|
||||||
|
if (!element.link && link) {
|
||||||
|
trackEvent("hyperlink", "create");
|
||||||
|
}
|
||||||
|
|
||||||
|
mutateElement(element, { link });
|
||||||
|
setAppState({ showHyperlinkPopup: "info" });
|
||||||
|
}, [element, setAppState]);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
return () => {
|
||||||
|
handleSubmit();
|
||||||
|
};
|
||||||
|
}, [handleSubmit]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let timeoutId: number | null = null;
|
||||||
|
const handlePointerMove = (event: PointerEvent) => {
|
||||||
|
if (isEditing) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (timeoutId) {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
const shouldHide = shouldHideLinkPopup(element, appState, [
|
||||||
|
event.clientX,
|
||||||
|
event.clientY,
|
||||||
|
]) as boolean;
|
||||||
|
if (shouldHide) {
|
||||||
|
timeoutId = window.setTimeout(() => {
|
||||||
|
setAppState({ showHyperlinkPopup: false });
|
||||||
|
}, AUTO_HIDE_TIMEOUT);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(EVENT.POINTER_MOVE, handlePointerMove, false);
|
||||||
|
if (timeoutId) {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [appState, element, isEditing, setAppState]);
|
||||||
|
|
||||||
|
const handleRemove = useCallback(() => {
|
||||||
|
trackEvent("hyperlink", "delete");
|
||||||
|
mutateElement(element, { link: null });
|
||||||
|
if (isEditing) {
|
||||||
|
inputRef.current!.value = "";
|
||||||
|
}
|
||||||
|
setAppState({ showHyperlinkPopup: false });
|
||||||
|
}, [setAppState, element, isEditing]);
|
||||||
|
|
||||||
|
const onEdit = () => {
|
||||||
|
trackEvent("hyperlink", "edit", "popup-ui");
|
||||||
|
setAppState({ showHyperlinkPopup: "editor" });
|
||||||
|
};
|
||||||
|
const { x, y } = getCoordsForPopover(element, appState);
|
||||||
|
if (
|
||||||
|
appState.draggingElement ||
|
||||||
|
appState.resizingElement ||
|
||||||
|
appState.isRotating ||
|
||||||
|
appState.openMenu
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="excalidraw-hyperlinkContainer"
|
||||||
|
style={{
|
||||||
|
top: `${y}px`,
|
||||||
|
left: `${x}px`,
|
||||||
|
width: CONTAINER_WIDTH,
|
||||||
|
padding: CONTAINER_PADDING,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isEditing ? (
|
||||||
|
<input
|
||||||
|
className={clsx("excalidraw-hyperlinkContainer-input")}
|
||||||
|
placeholder="Type or paste your link here"
|
||||||
|
ref={inputRef}
|
||||||
|
value={inputVal}
|
||||||
|
onChange={(event) => setInputVal(event.target.value)}
|
||||||
|
autoFocus
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
event.stopPropagation();
|
||||||
|
// prevent cmd/ctrl+k shortcut when editing link
|
||||||
|
if (event[KEYS.CTRL_OR_CMD] && event.key === KEYS.K) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
if (event.key === KEYS.ENTER || event.key === KEYS.ESCAPE) {
|
||||||
|
handleSubmit();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={element.link || ""}
|
||||||
|
className={clsx("excalidraw-hyperlinkContainer-link", {
|
||||||
|
"d-none": isEditing,
|
||||||
|
})}
|
||||||
|
target={isLocalLink(element.link) ? "_self" : "_blank"}
|
||||||
|
onClick={(event) => {
|
||||||
|
if (element.link && onLinkOpen) {
|
||||||
|
const customEvent = wrapEvent(
|
||||||
|
EVENT.EXCALIDRAW_LINK,
|
||||||
|
event.nativeEvent,
|
||||||
|
);
|
||||||
|
onLinkOpen(element, customEvent);
|
||||||
|
if (customEvent.defaultPrevented) {
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
>
|
||||||
|
{element.link}
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<div className="excalidraw-hyperlinkContainer__buttons">
|
||||||
|
{!isEditing && (
|
||||||
|
<ToolButton
|
||||||
|
type="button"
|
||||||
|
title={t("buttons.edit")}
|
||||||
|
aria-label={t("buttons.edit")}
|
||||||
|
label={t("buttons.edit")}
|
||||||
|
onClick={onEdit}
|
||||||
|
className="excalidraw-hyperlinkContainer--edit"
|
||||||
|
icon={editIcon}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{linkVal && (
|
||||||
|
<ToolButton
|
||||||
|
type="button"
|
||||||
|
title={t("buttons.remove")}
|
||||||
|
aria-label={t("buttons.remove")}
|
||||||
|
label={t("buttons.remove")}
|
||||||
|
onClick={handleRemove}
|
||||||
|
className="excalidraw-hyperlinkContainer--remove"
|
||||||
|
icon={trash}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCoordsForPopover = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
appState: AppState,
|
||||||
|
) => {
|
||||||
|
const [x1, y1] = getElementAbsoluteCoords(element);
|
||||||
|
const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
|
||||||
|
{ sceneX: x1 + element.width / 2, sceneY: y1 },
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
const x = viewportX - appState.offsetLeft - CONTAINER_WIDTH / 2;
|
||||||
|
const y = viewportY - appState.offsetTop - SPACE_BOTTOM;
|
||||||
|
return { x, y };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const normalizeLink = (link: string) => {
|
||||||
|
link = link.trim();
|
||||||
|
if (link) {
|
||||||
|
// prefix with protocol if not fully-qualified
|
||||||
|
if (!link.includes("://") && !/^[[\\/]/.test(link)) {
|
||||||
|
link = `https://${link}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return link;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isLocalLink = (link: string | null) => {
|
||||||
|
return !!(link?.includes(location.origin) || link?.startsWith("/"));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const actionLink = register({
|
||||||
|
name: "hyperlink",
|
||||||
|
perform: (elements, appState) => {
|
||||||
|
if (appState.showHyperlinkPopup === "editor") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
elements,
|
||||||
|
appState: {
|
||||||
|
...appState,
|
||||||
|
showHyperlinkPopup: "editor",
|
||||||
|
openMenu: null,
|
||||||
|
},
|
||||||
|
commitToHistory: true,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
trackEvent: (action, source) => {
|
||||||
|
trackEvent("hyperlink", "edit", source);
|
||||||
|
},
|
||||||
|
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.K,
|
||||||
|
contextItemLabel: (elements, appState) =>
|
||||||
|
getContextMenuLabel(elements, appState),
|
||||||
|
contextItemPredicate: (elements, appState) => {
|
||||||
|
const selectedElements = getSelectedElements(elements, appState);
|
||||||
|
return selectedElements.length === 1;
|
||||||
|
},
|
||||||
|
PanelComponent: ({ elements, appState, updateData }) => {
|
||||||
|
const selectedElements = getSelectedElements(elements, appState);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ToolButton
|
||||||
|
type="button"
|
||||||
|
icon={link}
|
||||||
|
aria-label={t(getContextMenuLabel(elements, appState))}
|
||||||
|
title={`${t("labels.link.label")} - ${getShortcutKey("CtrlOrCmd+K")}`}
|
||||||
|
onClick={() => updateData(null)}
|
||||||
|
selected={selectedElements.length === 1 && !!selectedElements[0].link}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getContextMenuLabel = (
|
||||||
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
|
appState: AppState,
|
||||||
|
) => {
|
||||||
|
const selectedElements = getSelectedElements(elements, appState);
|
||||||
|
const label = selectedElements[0]!.link
|
||||||
|
? "labels.link.edit"
|
||||||
|
: "labels.link.create";
|
||||||
|
return label;
|
||||||
|
};
|
||||||
|
export const getLinkHandleFromCoords = (
|
||||||
|
[x1, y1, x2, y2]: Bounds,
|
||||||
|
angle: number,
|
||||||
|
appState: AppState,
|
||||||
|
): [x: number, y: number, width: number, height: number] => {
|
||||||
|
const size = DEFAULT_LINK_SIZE;
|
||||||
|
const linkWidth = size / appState.zoom.value;
|
||||||
|
const linkHeight = size / appState.zoom.value;
|
||||||
|
const linkMarginY = size / appState.zoom.value;
|
||||||
|
const centerX = (x1 + x2) / 2;
|
||||||
|
const centerY = (y1 + y2) / 2;
|
||||||
|
const centeringOffset = (size - 8) / (2 * appState.zoom.value);
|
||||||
|
const dashedLineMargin = 4 / appState.zoom.value;
|
||||||
|
|
||||||
|
// Same as `ne` resize handle
|
||||||
|
const x = x2 + dashedLineMargin - centeringOffset;
|
||||||
|
const y = y1 - dashedLineMargin - linkMarginY + centeringOffset;
|
||||||
|
|
||||||
|
const [rotatedX, rotatedY] = rotate(
|
||||||
|
x + linkWidth / 2,
|
||||||
|
y + linkHeight / 2,
|
||||||
|
centerX,
|
||||||
|
centerY,
|
||||||
|
angle,
|
||||||
|
);
|
||||||
|
return [
|
||||||
|
rotatedX - linkWidth / 2,
|
||||||
|
rotatedY - linkHeight / 2,
|
||||||
|
linkWidth,
|
||||||
|
linkHeight,
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isPointHittingLinkIcon = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
appState: AppState,
|
||||||
|
[x, y]: Point,
|
||||||
|
isMobile: boolean,
|
||||||
|
) => {
|
||||||
|
const threshold = 4 / appState.zoom.value;
|
||||||
|
if (
|
||||||
|
!isMobile &&
|
||||||
|
appState.viewModeEnabled &&
|
||||||
|
isPointHittingElementBoundingBox(element, [x, y], threshold)
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||||
|
|
||||||
|
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
|
||||||
|
[x1, y1, x2, y2],
|
||||||
|
element.angle,
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
const hitLink =
|
||||||
|
x > linkX - threshold &&
|
||||||
|
x < linkX + threshold + linkWidth &&
|
||||||
|
y > linkY - threshold &&
|
||||||
|
y < linkY + linkHeight + threshold;
|
||||||
|
return hitLink;
|
||||||
|
};
|
||||||
|
|
||||||
|
let HYPERLINK_TOOLTIP_TIMEOUT_ID: number | null = null;
|
||||||
|
export const showHyperlinkTooltip = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
appState: AppState,
|
||||||
|
) => {
|
||||||
|
if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
|
||||||
|
clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
|
||||||
|
}
|
||||||
|
HYPERLINK_TOOLTIP_TIMEOUT_ID = window.setTimeout(
|
||||||
|
() => renderTooltip(element, appState),
|
||||||
|
HYPERLINK_TOOLTIP_DELAY,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderTooltip = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
appState: AppState,
|
||||||
|
) => {
|
||||||
|
if (!element.link) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tooltipDiv = getTooltipDiv();
|
||||||
|
|
||||||
|
tooltipDiv.classList.add("excalidraw-tooltip--visible");
|
||||||
|
tooltipDiv.style.maxWidth = "20rem";
|
||||||
|
tooltipDiv.textContent = element.link;
|
||||||
|
|
||||||
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||||
|
|
||||||
|
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
|
||||||
|
[x1, y1, x2, y2],
|
||||||
|
element.angle,
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
|
||||||
|
const linkViewportCoords = sceneCoordsToViewportCoords(
|
||||||
|
{ sceneX: linkX, sceneY: linkY },
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
|
||||||
|
updateTooltipPosition(
|
||||||
|
tooltipDiv,
|
||||||
|
{
|
||||||
|
left: linkViewportCoords.x,
|
||||||
|
top: linkViewportCoords.y,
|
||||||
|
width: linkWidth,
|
||||||
|
height: linkHeight,
|
||||||
|
},
|
||||||
|
"top",
|
||||||
|
);
|
||||||
|
trackEvent("hyperlink", "tooltip", "link-icon");
|
||||||
|
|
||||||
|
IS_HYPERLINK_TOOLTIP_VISIBLE = true;
|
||||||
|
};
|
||||||
|
export const hideHyperlinkToolip = () => {
|
||||||
|
if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
|
||||||
|
clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
|
||||||
|
}
|
||||||
|
if (IS_HYPERLINK_TOOLTIP_VISIBLE) {
|
||||||
|
IS_HYPERLINK_TOOLTIP_VISIBLE = false;
|
||||||
|
getTooltipDiv().classList.remove("excalidraw-tooltip--visible");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const shouldHideLinkPopup = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
appState: AppState,
|
||||||
|
[clientX, clientY]: Point,
|
||||||
|
): Boolean => {
|
||||||
|
const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
|
||||||
|
{ clientX, clientY },
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
|
||||||
|
const threshold = 15 / appState.zoom.value;
|
||||||
|
// hitbox to prevent hiding when hovered in element bounding box
|
||||||
|
if (isPointHittingElementBoundingBox(element, [sceneX, sceneY], threshold)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const [x1, y1, x2] = getElementAbsoluteCoords(element);
|
||||||
|
// hit box to prevent hiding when hovered in the vertical area between element and popover
|
||||||
|
if (
|
||||||
|
sceneX >= x1 &&
|
||||||
|
sceneX <= x2 &&
|
||||||
|
sceneY >= y1 - SPACE_BOTTOM &&
|
||||||
|
sceneY <= y1
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// hit box to prevent hiding when hovered around popover within threshold
|
||||||
|
const { x: popoverX, y: popoverY } = getCoordsForPopover(element, appState);
|
||||||
|
|
||||||
|
if (
|
||||||
|
clientX >= popoverX - threshold &&
|
||||||
|
clientX <= popoverX + CONTAINER_WIDTH + CONTAINER_PADDING * 2 + threshold &&
|
||||||
|
clientY >= popoverY - threshold &&
|
||||||
|
clientY <= popoverY + threshold + CONTAINER_PADDING * 2 + CONTAINER_HEIGHT
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
+90
-65
@@ -8,7 +8,11 @@ import {
|
|||||||
} from "./types";
|
} from "./types";
|
||||||
import { getElementAtPosition } from "../scene";
|
import { getElementAtPosition } from "../scene";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { isBindableElement, isBindingElement } from "./typeChecks";
|
import {
|
||||||
|
isBindableElement,
|
||||||
|
isBindingElement,
|
||||||
|
isLinearElement,
|
||||||
|
} from "./typeChecks";
|
||||||
import {
|
import {
|
||||||
bindingBorderTest,
|
bindingBorderTest,
|
||||||
distanceToBindableElement,
|
distanceToBindableElement,
|
||||||
@@ -20,7 +24,7 @@ import {
|
|||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import Scene from "../scene/Scene";
|
import Scene from "../scene/Scene";
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
import { LinearElementEditor } from "./linearElementEditor";
|
||||||
import { tupleToCoors } from "../utils";
|
import { arrayToMap, tupleToCoors } from "../utils";
|
||||||
import { KEYS } from "../keys";
|
import { KEYS } from "../keys";
|
||||||
|
|
||||||
export type SuggestedBinding =
|
export type SuggestedBinding =
|
||||||
@@ -74,8 +78,9 @@ export const bindOrUnbindLinearElement = (
|
|||||||
.getNonDeletedElements(onlyUnbound)
|
.getNonDeletedElements(onlyUnbound)
|
||||||
.forEach((element) => {
|
.forEach((element) => {
|
||||||
mutateElement(element, {
|
mutateElement(element, {
|
||||||
boundElementIds: element.boundElementIds?.filter(
|
boundElements: element.boundElements?.filter(
|
||||||
(id) => id !== linearElement.id,
|
(element) =>
|
||||||
|
element.type !== "arrow" || element.id !== linearElement.id,
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -180,11 +185,16 @@ const bindLinearElement = (
|
|||||||
...calculateFocusAndGap(linearElement, hoveredElement, startOrEnd),
|
...calculateFocusAndGap(linearElement, hoveredElement, startOrEnd),
|
||||||
} as PointBinding,
|
} as PointBinding,
|
||||||
});
|
});
|
||||||
mutateElement(hoveredElement, {
|
|
||||||
boundElementIds: Array.from(
|
const boundElementsMap = arrayToMap(hoveredElement.boundElements || []);
|
||||||
new Set([...(hoveredElement.boundElementIds ?? []), linearElement.id]),
|
if (!boundElementsMap.has(linearElement.id)) {
|
||||||
),
|
mutateElement(hoveredElement, {
|
||||||
});
|
boundElements: (hoveredElement.boundElements || []).concat({
|
||||||
|
id: linearElement.id,
|
||||||
|
type: "arrow",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Don't bind both ends of a simple segment
|
// Don't bind both ends of a simple segment
|
||||||
@@ -284,52 +294,56 @@ export const updateBoundElements = (
|
|||||||
newSize?: { width: number; height: number };
|
newSize?: { width: number; height: number };
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
const boundElementIds = changedElement.boundElementIds ?? [];
|
const boundLinearElements = (changedElement.boundElements ?? []).filter(
|
||||||
if (boundElementIds.length === 0) {
|
(el) => el.type === "arrow",
|
||||||
|
);
|
||||||
|
if (boundLinearElements.length === 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const { newSize, simultaneouslyUpdated } = options ?? {};
|
const { newSize, simultaneouslyUpdated } = options ?? {};
|
||||||
const simultaneouslyUpdatedElementIds = getSimultaneouslyUpdatedElementIds(
|
const simultaneouslyUpdatedElementIds = getSimultaneouslyUpdatedElementIds(
|
||||||
simultaneouslyUpdated,
|
simultaneouslyUpdated,
|
||||||
);
|
);
|
||||||
(
|
Scene.getScene(changedElement)!
|
||||||
Scene.getScene(changedElement)!.getNonDeletedElements(
|
.getNonDeletedElements(boundLinearElements.map((el) => el.id))
|
||||||
boundElementIds,
|
.forEach((element) => {
|
||||||
) as NonDeleted<ExcalidrawLinearElement>[]
|
if (!isLinearElement(element)) {
|
||||||
).forEach((linearElement) => {
|
return;
|
||||||
const bindableElement = changedElement as ExcalidrawBindableElement;
|
}
|
||||||
// In case the boundElementIds are stale
|
|
||||||
if (!doesNeedUpdate(linearElement, bindableElement)) {
|
const bindableElement = changedElement as ExcalidrawBindableElement;
|
||||||
return;
|
// In case the boundElements are stale
|
||||||
}
|
if (!doesNeedUpdate(element, bindableElement)) {
|
||||||
const startBinding = maybeCalculateNewGapWhenScaling(
|
return;
|
||||||
bindableElement,
|
}
|
||||||
linearElement.startBinding,
|
const startBinding = maybeCalculateNewGapWhenScaling(
|
||||||
newSize,
|
bindableElement,
|
||||||
);
|
element.startBinding,
|
||||||
const endBinding = maybeCalculateNewGapWhenScaling(
|
newSize,
|
||||||
bindableElement,
|
);
|
||||||
linearElement.endBinding,
|
const endBinding = maybeCalculateNewGapWhenScaling(
|
||||||
newSize,
|
bindableElement,
|
||||||
);
|
element.endBinding,
|
||||||
// `linearElement` is being moved/scaled already, just update the binding
|
newSize,
|
||||||
if (simultaneouslyUpdatedElementIds.has(linearElement.id)) {
|
);
|
||||||
mutateElement(linearElement, { startBinding, endBinding });
|
// `linearElement` is being moved/scaled already, just update the binding
|
||||||
return;
|
if (simultaneouslyUpdatedElementIds.has(element.id)) {
|
||||||
}
|
mutateElement(element, { startBinding, endBinding });
|
||||||
updateBoundPoint(
|
return;
|
||||||
linearElement,
|
}
|
||||||
"start",
|
updateBoundPoint(
|
||||||
startBinding,
|
element,
|
||||||
changedElement as ExcalidrawBindableElement,
|
"start",
|
||||||
);
|
startBinding,
|
||||||
updateBoundPoint(
|
changedElement as ExcalidrawBindableElement,
|
||||||
linearElement,
|
);
|
||||||
"end",
|
updateBoundPoint(
|
||||||
endBinding,
|
element,
|
||||||
changedElement as ExcalidrawBindableElement,
|
"end",
|
||||||
);
|
endBinding,
|
||||||
});
|
changedElement as ExcalidrawBindableElement,
|
||||||
|
);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const doesNeedUpdate = (
|
const doesNeedUpdate = (
|
||||||
@@ -401,10 +415,17 @@ const updateBoundPoint = (
|
|||||||
newEdgePoint = intersections[0];
|
newEdgePoint = intersections[0];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
LinearElementEditor.movePoint(
|
LinearElementEditor.movePoints(
|
||||||
linearElement,
|
linearElement,
|
||||||
edgePointIndex,
|
[
|
||||||
LinearElementEditor.pointFromAbsoluteCoords(linearElement, newEdgePoint),
|
{
|
||||||
|
index: edgePointIndex,
|
||||||
|
point: LinearElementEditor.pointFromAbsoluteCoords(
|
||||||
|
linearElement,
|
||||||
|
newEdgePoint,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
{ [startOrEnd === "start" ? "startBinding" : "endBinding"]: binding },
|
{ [startOrEnd === "start" ? "startBinding" : "endBinding"]: binding },
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -552,11 +573,11 @@ export const fixBindingsAfterDuplication = (
|
|||||||
const allBindableElementIds: Set<ExcalidrawElement["id"]> = new Set();
|
const allBindableElementIds: Set<ExcalidrawElement["id"]> = new Set();
|
||||||
const shouldReverseRoles = duplicatesServeAsOld === "duplicatesServeAsOld";
|
const shouldReverseRoles = duplicatesServeAsOld === "duplicatesServeAsOld";
|
||||||
oldElements.forEach((oldElement) => {
|
oldElements.forEach((oldElement) => {
|
||||||
const { boundElementIds } = oldElement;
|
const { boundElements } = oldElement;
|
||||||
if (boundElementIds != null && boundElementIds.length > 0) {
|
if (boundElements != null && boundElements.length > 0) {
|
||||||
boundElementIds.forEach((boundElementId) => {
|
boundElements.forEach((boundElement) => {
|
||||||
if (shouldReverseRoles && !oldIdToDuplicatedId.has(boundElementId)) {
|
if (shouldReverseRoles && !oldIdToDuplicatedId.has(boundElement.id)) {
|
||||||
allBoundElementIds.add(boundElementId);
|
allBoundElementIds.add(boundElement.id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
allBindableElementIds.add(oldIdToDuplicatedId.get(oldElement.id)!);
|
allBindableElementIds.add(oldIdToDuplicatedId.get(oldElement.id)!);
|
||||||
@@ -600,12 +621,16 @@ export const fixBindingsAfterDuplication = (
|
|||||||
sceneElements
|
sceneElements
|
||||||
.filter(({ id }) => allBindableElementIds.has(id))
|
.filter(({ id }) => allBindableElementIds.has(id))
|
||||||
.forEach((bindableElement) => {
|
.forEach((bindableElement) => {
|
||||||
const { boundElementIds } = bindableElement;
|
const { boundElements } = bindableElement;
|
||||||
if (boundElementIds != null && boundElementIds.length > 0) {
|
if (boundElements != null && boundElements.length > 0) {
|
||||||
mutateElement(bindableElement, {
|
mutateElement(bindableElement, {
|
||||||
boundElementIds: boundElementIds.map(
|
boundElements: boundElements.map((boundElement) =>
|
||||||
(boundElementId) =>
|
oldIdToDuplicatedId.has(boundElement.id)
|
||||||
oldIdToDuplicatedId.get(boundElementId) ?? boundElementId,
|
? {
|
||||||
|
id: oldIdToDuplicatedId.get(boundElement.id)!,
|
||||||
|
type: boundElement.type,
|
||||||
|
}
|
||||||
|
: boundElement,
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -638,9 +663,9 @@ export const fixBindingsAfterDeletion = (
|
|||||||
const boundElementIds: Set<ExcalidrawElement["id"]> = new Set();
|
const boundElementIds: Set<ExcalidrawElement["id"]> = new Set();
|
||||||
deletedElements.forEach((deletedElement) => {
|
deletedElements.forEach((deletedElement) => {
|
||||||
if (isBindableElement(deletedElement)) {
|
if (isBindableElement(deletedElement)) {
|
||||||
deletedElement.boundElementIds?.forEach((id) => {
|
deletedElement.boundElements?.forEach((element) => {
|
||||||
if (!deletedElementIds.has(id)) {
|
if (!deletedElementIds.has(element.id)) {
|
||||||
boundElementIds.add(id);
|
boundElementIds.add(element.id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-3
@@ -185,7 +185,7 @@ const getLinearElementAbsoluteCoords = (
|
|||||||
maxY + element.y,
|
maxY + element.y,
|
||||||
];
|
];
|
||||||
} else {
|
} else {
|
||||||
const shape = getShapeForElement(element) as Drawable[];
|
const shape = getShapeForElement(element)!;
|
||||||
|
|
||||||
// first element is always the curve
|
// first element is always the curve
|
||||||
const ops = getCurvePathOps(shape[0]);
|
const ops = getCurvePathOps(shape[0]);
|
||||||
@@ -326,7 +326,7 @@ const getLinearElementRotatedBounds = (
|
|||||||
return [minX, minY, maxX, maxY];
|
return [minX, minY, maxX, maxY];
|
||||||
}
|
}
|
||||||
|
|
||||||
const shape = getShapeForElement(element) as Drawable[];
|
const shape = getShapeForElement(element)!;
|
||||||
|
|
||||||
// first element is always the curve
|
// first element is always the curve
|
||||||
const ops = getCurvePathOps(shape[0]);
|
const ops = getCurvePathOps(shape[0]);
|
||||||
@@ -520,11 +520,24 @@ export interface Box {
|
|||||||
minY: number;
|
minY: number;
|
||||||
maxX: number;
|
maxX: number;
|
||||||
maxY: number;
|
maxY: number;
|
||||||
|
midX: number;
|
||||||
|
midY: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getCommonBoundingBox = (
|
export const getCommonBoundingBox = (
|
||||||
elements: ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[],
|
elements: ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[],
|
||||||
): Box => {
|
): Box => {
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
||||||
return { minX, minY, maxX, maxY };
|
return {
|
||||||
|
minX,
|
||||||
|
minY,
|
||||||
|
maxX,
|
||||||
|
maxY,
|
||||||
|
width: maxX - minX,
|
||||||
|
height: maxY - minY,
|
||||||
|
midX: (minX + maxX) / 2,
|
||||||
|
midY: (minY + maxY) / 2,
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+35
-18
@@ -24,6 +24,7 @@ import {
|
|||||||
NonDeleted,
|
NonDeleted,
|
||||||
ExcalidrawFreeDrawElement,
|
ExcalidrawFreeDrawElement,
|
||||||
ExcalidrawImageElement,
|
ExcalidrawImageElement,
|
||||||
|
ExcalidrawLinearElement,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
import { getElementAbsoluteCoords, getCurvePathOps, Bounds } from "./bounds";
|
import { getElementAbsoluteCoords, getCurvePathOps, Bounds } from "./bounds";
|
||||||
@@ -31,7 +32,9 @@ import { Point } from "../types";
|
|||||||
import { Drawable } from "roughjs/bin/core";
|
import { Drawable } from "roughjs/bin/core";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { getShapeForElement } from "../renderer/renderElement";
|
import { getShapeForElement } from "../renderer/renderElement";
|
||||||
import { isImageElement } from "./typeChecks";
|
import { hasBoundTextElement, isImageElement } from "./typeChecks";
|
||||||
|
import { isTextElement } from ".";
|
||||||
|
import { isTransparent } from "../utils";
|
||||||
|
|
||||||
const isElementDraggableFromInside = (
|
const isElementDraggableFromInside = (
|
||||||
element: NonDeletedExcalidrawElement,
|
element: NonDeletedExcalidrawElement,
|
||||||
@@ -43,9 +46,8 @@ const isElementDraggableFromInside = (
|
|||||||
if (element.type === "freedraw") {
|
if (element.type === "freedraw") {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
const isDraggableFromInside =
|
||||||
const isDraggableFromInside = element.backgroundColor !== "transparent";
|
!isTransparent(element.backgroundColor) || hasBoundTextElement(element);
|
||||||
|
|
||||||
if (element.type === "line") {
|
if (element.type === "line") {
|
||||||
return isDraggableFromInside && isPathALoop(element.points);
|
return isDraggableFromInside && isPathALoop(element.points);
|
||||||
}
|
}
|
||||||
@@ -83,20 +85,18 @@ export const isHittingElementBoundingBoxWithoutHittingElement = (
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const isHittingElementNotConsideringBoundingBox = (
|
export const isHittingElementNotConsideringBoundingBox = (
|
||||||
element: NonDeletedExcalidrawElement,
|
element: NonDeletedExcalidrawElement,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
point: Point,
|
point: Point,
|
||||||
): boolean => {
|
): boolean => {
|
||||||
const threshold = 10 / appState.zoom.value;
|
const threshold = 10 / appState.zoom.value;
|
||||||
|
|
||||||
const check =
|
const check = isTextElement(element)
|
||||||
element.type === "text"
|
? isStrictlyInside
|
||||||
? isStrictlyInside
|
: isElementDraggableFromInside(element)
|
||||||
: isElementDraggableFromInside(element)
|
? isInsideCheck
|
||||||
? isInsideCheck
|
: isNearCheck;
|
||||||
: isNearCheck;
|
|
||||||
|
|
||||||
return hitTestPointAgainstElement({ element, point, threshold, check });
|
return hitTestPointAgainstElement({ element, point, threshold, check });
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -105,7 +105,7 @@ const isElementSelected = (
|
|||||||
element: NonDeleted<ExcalidrawElement>,
|
element: NonDeleted<ExcalidrawElement>,
|
||||||
) => appState.selectedElementIds[element.id];
|
) => appState.selectedElementIds[element.id];
|
||||||
|
|
||||||
const isPointHittingElementBoundingBox = (
|
export const isPointHittingElementBoundingBox = (
|
||||||
element: NonDeleted<ExcalidrawElement>,
|
element: NonDeleted<ExcalidrawElement>,
|
||||||
[x, y]: Point,
|
[x, y]: Point,
|
||||||
threshold: number,
|
threshold: number,
|
||||||
@@ -362,6 +362,14 @@ const hitTestFreeDrawElement = (
|
|||||||
B = element.points[i + 1];
|
B = element.points[i + 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const shape = getShapeForElement(element);
|
||||||
|
|
||||||
|
// for filled freedraw shapes, support
|
||||||
|
// selecting from inside
|
||||||
|
if (shape && shape.sets.length) {
|
||||||
|
return hitTestRoughShape(shape, x, y, threshold);
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -384,7 +392,11 @@ const hitTestLinear = (args: HitTestArgs): boolean => {
|
|||||||
}
|
}
|
||||||
const [relX, relY] = GAPoint.toTuple(point);
|
const [relX, relY] = GAPoint.toTuple(point);
|
||||||
|
|
||||||
const shape = getShapeForElement(element) as Drawable[];
|
const shape = getShapeForElement(element as ExcalidrawLinearElement);
|
||||||
|
|
||||||
|
if (!shape) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
if (args.check === isInsideCheck) {
|
if (args.check === isInsideCheck) {
|
||||||
const hit = shape.some((subshape) =>
|
const hit = shape.some((subshape) =>
|
||||||
@@ -634,7 +646,7 @@ const getCorners = (
|
|||||||
|
|
||||||
// Returns intersection of `line` with `segment`, with `segment` moved by
|
// Returns intersection of `line` with `segment`, with `segment` moved by
|
||||||
// `gap` in its polar direction.
|
// `gap` in its polar direction.
|
||||||
// If intersection conincides with second segment point returns empty array.
|
// If intersection coincides with second segment point returns empty array.
|
||||||
const intersectSegment = (
|
const intersectSegment = (
|
||||||
line: GA.Line,
|
line: GA.Line,
|
||||||
segment: [GA.Point, GA.Point],
|
segment: [GA.Point, GA.Point],
|
||||||
@@ -822,7 +834,7 @@ const hitTestCurveInside = (
|
|||||||
sharpness: ExcalidrawElement["strokeSharpness"],
|
sharpness: ExcalidrawElement["strokeSharpness"],
|
||||||
) => {
|
) => {
|
||||||
const ops = getCurvePathOps(drawable);
|
const ops = getCurvePathOps(drawable);
|
||||||
const points: Point[] = [];
|
const points: Mutable<Point>[] = [];
|
||||||
let odd = false; // select one line out of double lines
|
let odd = false; // select one line out of double lines
|
||||||
for (const operation of ops) {
|
for (const operation of ops) {
|
||||||
if (operation.op === "move") {
|
if (operation.op === "move") {
|
||||||
@@ -836,13 +848,17 @@ const hitTestCurveInside = (
|
|||||||
points.push([operation.data[2], operation.data[3]]);
|
points.push([operation.data[2], operation.data[3]]);
|
||||||
points.push([operation.data[4], operation.data[5]]);
|
points.push([operation.data[4], operation.data[5]]);
|
||||||
}
|
}
|
||||||
|
} else if (operation.op === "lineTo") {
|
||||||
|
if (odd) {
|
||||||
|
points.push([operation.data[0], operation.data[1]]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (points.length >= 4) {
|
if (points.length >= 4) {
|
||||||
if (sharpness === "sharp") {
|
if (sharpness === "sharp") {
|
||||||
return isPointInPolygon(points, x, y);
|
return isPointInPolygon(points, x, y);
|
||||||
}
|
}
|
||||||
const polygonPoints = pointsOnBezierCurves(points as any, 10, 5);
|
const polygonPoints = pointsOnBezierCurves(points, 10, 5);
|
||||||
return isPointInPolygon(polygonPoints, x, y);
|
return isPointInPolygon(polygonPoints, x, y);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@@ -897,9 +913,10 @@ const hitTestRoughShape = (
|
|||||||
// position of the previous operation
|
// position of the previous operation
|
||||||
return retVal;
|
return retVal;
|
||||||
} else if (op === "lineTo") {
|
} else if (op === "lineTo") {
|
||||||
// TODO: Implement this
|
return hitTestCurveInside(drawable, x, y, "sharp");
|
||||||
} else if (op === "qcurveTo") {
|
} else if (op === "qcurveTo") {
|
||||||
// TODO: Implement this
|
// TODO: Implement this
|
||||||
|
console.warn("qcurveTo is not implemented yet");
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
+58
-20
@@ -3,47 +3,85 @@ import { updateBoundElements } from "./binding";
|
|||||||
import { getCommonBounds } from "./bounds";
|
import { getCommonBounds } from "./bounds";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import { getPerfectElementSize } from "./sizeHelpers";
|
import { getPerfectElementSize } from "./sizeHelpers";
|
||||||
import Scene from "../scene/Scene";
|
|
||||||
import { NonDeletedExcalidrawElement } from "./types";
|
import { NonDeletedExcalidrawElement } from "./types";
|
||||||
import { PointerDownState } from "../types";
|
import { AppState, PointerDownState } from "../types";
|
||||||
|
import { getBoundTextElement } from "./textElement";
|
||||||
|
import { isSelectedViaGroup } from "../groups";
|
||||||
|
|
||||||
export const dragSelectedElements = (
|
export const dragSelectedElements = (
|
||||||
pointerDownState: PointerDownState,
|
pointerDownState: PointerDownState,
|
||||||
selectedElements: NonDeletedExcalidrawElement[],
|
selectedElements: NonDeletedExcalidrawElement[],
|
||||||
pointerX: number,
|
pointerX: number,
|
||||||
pointerY: number,
|
pointerY: number,
|
||||||
scene: Scene,
|
|
||||||
lockDirection: boolean = false,
|
lockDirection: boolean = false,
|
||||||
distanceX: number = 0,
|
distanceX: number = 0,
|
||||||
distanceY: number = 0,
|
distanceY: number = 0,
|
||||||
|
appState: AppState,
|
||||||
) => {
|
) => {
|
||||||
const [x1, y1] = getCommonBounds(selectedElements);
|
const [x1, y1] = getCommonBounds(selectedElements);
|
||||||
const offset = { x: pointerX - x1, y: pointerY - y1 };
|
const offset = { x: pointerX - x1, y: pointerY - y1 };
|
||||||
selectedElements.forEach((element) => {
|
selectedElements.forEach((element) => {
|
||||||
let x: number;
|
updateElementCoords(
|
||||||
let y: number;
|
lockDirection,
|
||||||
if (lockDirection) {
|
distanceX,
|
||||||
const lockX = lockDirection && distanceX < distanceY;
|
distanceY,
|
||||||
const lockY = lockDirection && distanceX > distanceY;
|
pointerDownState,
|
||||||
const original = pointerDownState.originalElements.get(element.id);
|
element,
|
||||||
x = lockX && original ? original.x : element.x + offset.x;
|
offset,
|
||||||
y = lockY && original ? original.y : element.y + offset.y;
|
);
|
||||||
} else {
|
// update coords of bound text only if we're dragging the container directly
|
||||||
x = element.x + offset.x;
|
// (we don't drag the group that it's part of)
|
||||||
y = element.y + offset.y;
|
if (
|
||||||
|
// container isn't part of any group
|
||||||
|
// (perf optim so we don't check `isSelectedViaGroup()` in every case)
|
||||||
|
!element.groupIds.length ||
|
||||||
|
// container is part of a group, but we're dragging the container directly
|
||||||
|
(appState.editingGroupId && !isSelectedViaGroup(appState, element))
|
||||||
|
) {
|
||||||
|
const textElement = getBoundTextElement(element);
|
||||||
|
if (textElement) {
|
||||||
|
updateElementCoords(
|
||||||
|
lockDirection,
|
||||||
|
distanceX,
|
||||||
|
distanceY,
|
||||||
|
pointerDownState,
|
||||||
|
textElement,
|
||||||
|
offset,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
mutateElement(element, {
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
});
|
|
||||||
|
|
||||||
updateBoundElements(element, {
|
updateBoundElements(element, {
|
||||||
simultaneouslyUpdated: selectedElements,
|
simultaneouslyUpdated: selectedElements,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const updateElementCoords = (
|
||||||
|
lockDirection: boolean,
|
||||||
|
distanceX: number,
|
||||||
|
distanceY: number,
|
||||||
|
pointerDownState: PointerDownState,
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
offset: { x: number; y: number },
|
||||||
|
) => {
|
||||||
|
let x: number;
|
||||||
|
let y: number;
|
||||||
|
if (lockDirection) {
|
||||||
|
const lockX = lockDirection && distanceX < distanceY;
|
||||||
|
const lockY = lockDirection && distanceX > distanceY;
|
||||||
|
const original = pointerDownState.originalElements.get(element.id);
|
||||||
|
x = lockX && original ? original.x : element.x + offset.x;
|
||||||
|
y = lockY && original ? original.y : element.y + offset.y;
|
||||||
|
} else {
|
||||||
|
x = element.x + offset.x;
|
||||||
|
y = element.y + offset.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
mutateElement(element, {
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
});
|
||||||
|
};
|
||||||
export const getDragOffsetXY = (
|
export const getDragOffsetXY = (
|
||||||
selectedElements: NonDeletedExcalidrawElement[],
|
selectedElements: NonDeletedExcalidrawElement[],
|
||||||
x: number,
|
x: number,
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
import { MIME_TYPES, SVG_NS } from "../constants";
|
import { MIME_TYPES, SVG_NS } from "../constants";
|
||||||
import { getDataURL } from "../data/blob";
|
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { AppClassProperties, DataURL, BinaryFiles } from "../types";
|
import { AppClassProperties, DataURL, BinaryFiles } from "../types";
|
||||||
import { isInitializedImageElement } from "./typeChecks";
|
import { isInitializedImageElement } from "./typeChecks";
|
||||||
@@ -110,81 +109,3 @@ export const normalizeSVG = async (SVGString: string) => {
|
|||||||
return svg.outerHTML;
|
return svg.outerHTML;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* To improve perf, uses `createImageBitmap` is available. But there are
|
|
||||||
* quality issues across browsers, so don't use this API where quality matters.
|
|
||||||
*/
|
|
||||||
export const speedyImageToCanvas = async (imageFile: Blob | File) => {
|
|
||||||
let imageSrc: HTMLImageElement | ImageBitmap;
|
|
||||||
if (
|
|
||||||
typeof ImageBitmap !== "undefined" &&
|
|
||||||
ImageBitmap.prototype &&
|
|
||||||
ImageBitmap.prototype.close &&
|
|
||||||
window.createImageBitmap
|
|
||||||
) {
|
|
||||||
imageSrc = await window.createImageBitmap(imageFile);
|
|
||||||
} else {
|
|
||||||
imageSrc = await loadHTMLImageElement(await getDataURL(imageFile));
|
|
||||||
}
|
|
||||||
const { width, height } = imageSrc;
|
|
||||||
|
|
||||||
const canvas = document.createElement("canvas");
|
|
||||||
canvas.height = height;
|
|
||||||
canvas.width = width;
|
|
||||||
const context = canvas.getContext("2d")!;
|
|
||||||
context.drawImage(imageSrc, 0, 0, width, height);
|
|
||||||
|
|
||||||
if (typeof ImageBitmap !== "undefined" && imageSrc instanceof ImageBitmap) {
|
|
||||||
imageSrc.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
return { canvas, context, width, height };
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Does its best at figuring out if an image (PNG) has any (semi)transparent
|
|
||||||
* pixels. If not PNG, always returns false.
|
|
||||||
*/
|
|
||||||
export const hasTransparentPixels = async (imageFile: Blob | File) => {
|
|
||||||
if (imageFile.type !== MIME_TYPES.png) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const { findPngChunk, extractPngChunks } = await import("../data/image");
|
|
||||||
|
|
||||||
const buffer = await imageFile.arrayBuffer();
|
|
||||||
const chunks = extractPngChunks(new Uint8Array(buffer));
|
|
||||||
|
|
||||||
// early exit if tRNS not found and IHDR states no support for alpha
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
|
|
||||||
const IHDR = findPngChunk(chunks, "IHDR");
|
|
||||||
|
|
||||||
if (
|
|
||||||
IHDR &&
|
|
||||||
IHDR.data[9] !== 4 &&
|
|
||||||
IHDR.data[9] !== 6 &&
|
|
||||||
!findPngChunk(chunks, "tRNS")
|
|
||||||
) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// otherwise loop through pixels to check if there's any actually
|
|
||||||
// (semi)transparent pixel
|
|
||||||
// -----------------------------------------------------------------------
|
|
||||||
|
|
||||||
const { width, height, context } = await speedyImageToCanvas(imageFile);
|
|
||||||
{
|
|
||||||
const { data } = context.getImageData(0, 0, width, height);
|
|
||||||
const len = data.byteLength;
|
|
||||||
let i = 3;
|
|
||||||
while (i <= len) {
|
|
||||||
if (data[i] !== 255) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
i += 4;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -59,15 +59,6 @@ export {
|
|||||||
} from "./sizeHelpers";
|
} from "./sizeHelpers";
|
||||||
export { showSelectedShapeActions } from "./showSelectedShapeActions";
|
export { showSelectedShapeActions } from "./showSelectedShapeActions";
|
||||||
|
|
||||||
export const getElementMap = (elements: readonly ExcalidrawElement[]) =>
|
|
||||||
elements.reduce(
|
|
||||||
(acc: { [key: string]: ExcalidrawElement }, element: ExcalidrawElement) => {
|
|
||||||
acc[element.id] = element;
|
|
||||||
return acc;
|
|
||||||
},
|
|
||||||
{},
|
|
||||||
);
|
|
||||||
|
|
||||||
export const getSceneVersion = (elements: readonly ExcalidrawElement[]) =>
|
export const getSceneVersion = (elements: readonly ExcalidrawElement[]) =>
|
||||||
elements.reduce((acc, el) => acc + el.version, 0);
|
elements.reduce((acc, el) => acc + el.version, 0);
|
||||||
|
|
||||||
|
|||||||
+418
-103
@@ -25,11 +25,19 @@ export class LinearElementEditor {
|
|||||||
public elementId: ExcalidrawElement["id"] & {
|
public elementId: ExcalidrawElement["id"] & {
|
||||||
_brand: "excalidrawLinearElementId";
|
_brand: "excalidrawLinearElementId";
|
||||||
};
|
};
|
||||||
public activePointIndex: number | null;
|
/** indices */
|
||||||
|
public selectedPointsIndices: readonly number[] | null;
|
||||||
|
|
||||||
|
public pointerDownState: Readonly<{
|
||||||
|
prevSelectedPointsIndices: readonly number[] | null;
|
||||||
|
/** index */
|
||||||
|
lastClickedPoint: number;
|
||||||
|
}>;
|
||||||
|
|
||||||
/** whether you're dragging a point */
|
/** whether you're dragging a point */
|
||||||
public isDragging: boolean;
|
public isDragging: boolean;
|
||||||
public lastUncommittedPoint: Point | null;
|
public lastUncommittedPoint: Point | null;
|
||||||
public pointerOffset: { x: number; y: number };
|
public pointerOffset: Readonly<{ x: number; y: number }>;
|
||||||
public startBindingElement: ExcalidrawBindableElement | null | "keep";
|
public startBindingElement: ExcalidrawBindableElement | null | "keep";
|
||||||
public endBindingElement: ExcalidrawBindableElement | null | "keep";
|
public endBindingElement: ExcalidrawBindableElement | null | "keep";
|
||||||
|
|
||||||
@@ -40,12 +48,16 @@ export class LinearElementEditor {
|
|||||||
Scene.mapElementToScene(this.elementId, scene);
|
Scene.mapElementToScene(this.elementId, scene);
|
||||||
LinearElementEditor.normalizePoints(element);
|
LinearElementEditor.normalizePoints(element);
|
||||||
|
|
||||||
this.activePointIndex = null;
|
this.selectedPointsIndices = null;
|
||||||
this.lastUncommittedPoint = null;
|
this.lastUncommittedPoint = null;
|
||||||
this.isDragging = false;
|
this.isDragging = false;
|
||||||
this.pointerOffset = { x: 0, y: 0 };
|
this.pointerOffset = { x: 0, y: 0 };
|
||||||
this.startBindingElement = "keep";
|
this.startBindingElement = "keep";
|
||||||
this.endBindingElement = "keep";
|
this.endBindingElement = "keep";
|
||||||
|
this.pointerDownState = {
|
||||||
|
prevSelectedPointsIndices: null,
|
||||||
|
lastClickedPoint: -1,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -66,6 +78,58 @@ export class LinearElementEditor {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static handleBoxSelection(
|
||||||
|
event: PointerEvent,
|
||||||
|
appState: AppState,
|
||||||
|
setState: React.Component<any, AppState>["setState"],
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
!appState.editingLinearElement ||
|
||||||
|
appState.draggingElement?.type !== "selection"
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const { editingLinearElement } = appState;
|
||||||
|
const { selectedPointsIndices, elementId } = editingLinearElement;
|
||||||
|
|
||||||
|
const element = LinearElementEditor.getElement(elementId);
|
||||||
|
if (!element) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [selectionX1, selectionY1, selectionX2, selectionY2] =
|
||||||
|
getElementAbsoluteCoords(appState.draggingElement);
|
||||||
|
|
||||||
|
const pointsSceneCoords =
|
||||||
|
LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||||
|
|
||||||
|
const nextSelectedPoints = pointsSceneCoords.reduce(
|
||||||
|
(acc: number[], point, index) => {
|
||||||
|
if (
|
||||||
|
(point[0] >= selectionX1 &&
|
||||||
|
point[0] <= selectionX2 &&
|
||||||
|
point[1] >= selectionY1 &&
|
||||||
|
point[1] <= selectionY2) ||
|
||||||
|
(event.shiftKey && selectedPointsIndices?.includes(index))
|
||||||
|
) {
|
||||||
|
acc.push(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
setState({
|
||||||
|
editingLinearElement: {
|
||||||
|
...editingLinearElement,
|
||||||
|
selectedPointsIndices: nextSelectedPoints.length
|
||||||
|
? nextSelectedPoints
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** @returns whether point was dragged */
|
/** @returns whether point was dragged */
|
||||||
static handlePointDragging(
|
static handlePointDragging(
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
@@ -74,21 +138,27 @@ export class LinearElementEditor {
|
|||||||
scenePointerY: number,
|
scenePointerY: number,
|
||||||
maybeSuggestBinding: (
|
maybeSuggestBinding: (
|
||||||
element: NonDeleted<ExcalidrawLinearElement>,
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
startOrEnd: "start" | "end",
|
pointSceneCoords: { x: number; y: number }[],
|
||||||
) => void,
|
) => void,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (!appState.editingLinearElement) {
|
if (!appState.editingLinearElement) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const { editingLinearElement } = appState;
|
const { editingLinearElement } = appState;
|
||||||
const { activePointIndex, elementId, isDragging } = editingLinearElement;
|
const { selectedPointsIndices, elementId, isDragging } =
|
||||||
|
editingLinearElement;
|
||||||
|
|
||||||
const element = LinearElementEditor.getElement(elementId);
|
const element = LinearElementEditor.getElement(elementId);
|
||||||
if (!element) {
|
if (!element) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (activePointIndex != null && activePointIndex > -1) {
|
// point that's being dragged (out of all selected points)
|
||||||
|
const draggingPoint = element.points[
|
||||||
|
editingLinearElement.pointerDownState.lastClickedPoint
|
||||||
|
] as [number, number] | undefined;
|
||||||
|
|
||||||
|
if (selectedPointsIndices && draggingPoint) {
|
||||||
if (isDragging === false) {
|
if (isDragging === false) {
|
||||||
setState({
|
setState({
|
||||||
editingLinearElement: {
|
editingLinearElement: {
|
||||||
@@ -98,18 +168,79 @@ export class LinearElementEditor {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const newPoint = LinearElementEditor.createPointAt(
|
const newDraggingPointPosition = LinearElementEditor.createPointAt(
|
||||||
element,
|
element,
|
||||||
scenePointerX - editingLinearElement.pointerOffset.x,
|
scenePointerX - editingLinearElement.pointerOffset.x,
|
||||||
scenePointerY - editingLinearElement.pointerOffset.y,
|
scenePointerY - editingLinearElement.pointerOffset.y,
|
||||||
appState.gridSize,
|
appState.gridSize,
|
||||||
);
|
);
|
||||||
LinearElementEditor.movePoint(element, activePointIndex, newPoint);
|
|
||||||
|
const deltaX = newDraggingPointPosition[0] - draggingPoint[0];
|
||||||
|
const deltaY = newDraggingPointPosition[1] - draggingPoint[1];
|
||||||
|
|
||||||
|
LinearElementEditor.movePoints(
|
||||||
|
element,
|
||||||
|
selectedPointsIndices.map((pointIndex) => {
|
||||||
|
const newPointPosition =
|
||||||
|
pointIndex ===
|
||||||
|
editingLinearElement.pointerDownState.lastClickedPoint
|
||||||
|
? LinearElementEditor.createPointAt(
|
||||||
|
element,
|
||||||
|
scenePointerX - editingLinearElement.pointerOffset.x,
|
||||||
|
scenePointerY - editingLinearElement.pointerOffset.y,
|
||||||
|
appState.gridSize,
|
||||||
|
)
|
||||||
|
: ([
|
||||||
|
element.points[pointIndex][0] + deltaX,
|
||||||
|
element.points[pointIndex][1] + deltaY,
|
||||||
|
] as const);
|
||||||
|
return {
|
||||||
|
index: pointIndex,
|
||||||
|
point: newPointPosition,
|
||||||
|
isDragging:
|
||||||
|
pointIndex ===
|
||||||
|
editingLinearElement.pointerDownState.lastClickedPoint,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
// suggest bindings for first and last point if selected
|
||||||
if (isBindingElement(element)) {
|
if (isBindingElement(element)) {
|
||||||
maybeSuggestBinding(element, activePointIndex === 0 ? "start" : "end");
|
const coords: { x: number; y: number }[] = [];
|
||||||
|
|
||||||
|
const firstSelectedIndex = selectedPointsIndices[0];
|
||||||
|
if (firstSelectedIndex === 0) {
|
||||||
|
coords.push(
|
||||||
|
tupleToCoors(
|
||||||
|
LinearElementEditor.getPointGlobalCoordinates(
|
||||||
|
element,
|
||||||
|
element.points[0],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastSelectedIndex =
|
||||||
|
selectedPointsIndices[selectedPointsIndices.length - 1];
|
||||||
|
if (lastSelectedIndex === element.points.length - 1) {
|
||||||
|
coords.push(
|
||||||
|
tupleToCoors(
|
||||||
|
LinearElementEditor.getPointGlobalCoordinates(
|
||||||
|
element,
|
||||||
|
element.points[lastSelectedIndex],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coords.length) {
|
||||||
|
maybeSuggestBinding(element, coords);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,45 +249,79 @@ export class LinearElementEditor {
|
|||||||
editingLinearElement: LinearElementEditor,
|
editingLinearElement: LinearElementEditor,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
): LinearElementEditor {
|
): LinearElementEditor {
|
||||||
const { elementId, activePointIndex, isDragging } = editingLinearElement;
|
const { elementId, selectedPointsIndices, isDragging, pointerDownState } =
|
||||||
|
editingLinearElement;
|
||||||
const element = LinearElementEditor.getElement(elementId);
|
const element = LinearElementEditor.getElement(elementId);
|
||||||
if (!element) {
|
if (!element) {
|
||||||
return editingLinearElement;
|
return editingLinearElement;
|
||||||
}
|
}
|
||||||
|
|
||||||
let binding = {};
|
const bindings: Partial<
|
||||||
if (
|
Pick<
|
||||||
isDragging &&
|
InstanceType<typeof LinearElementEditor>,
|
||||||
(activePointIndex === 0 || activePointIndex === element.points.length - 1)
|
"startBindingElement" | "endBindingElement"
|
||||||
) {
|
>
|
||||||
if (isPathALoop(element.points, appState.zoom.value)) {
|
> = {};
|
||||||
LinearElementEditor.movePoint(
|
|
||||||
element,
|
if (isDragging && selectedPointsIndices) {
|
||||||
activePointIndex,
|
for (const selectedPoint of selectedPointsIndices) {
|
||||||
activePointIndex === 0
|
if (
|
||||||
? element.points[element.points.length - 1]
|
selectedPoint === 0 ||
|
||||||
: element.points[0],
|
selectedPoint === element.points.length - 1
|
||||||
);
|
) {
|
||||||
|
if (isPathALoop(element.points, appState.zoom.value)) {
|
||||||
|
LinearElementEditor.movePoints(element, [
|
||||||
|
{
|
||||||
|
index: selectedPoint,
|
||||||
|
point:
|
||||||
|
selectedPoint === 0
|
||||||
|
? element.points[element.points.length - 1]
|
||||||
|
: element.points[0],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const bindingElement = isBindingEnabled(appState)
|
||||||
|
? getHoveredElementForBinding(
|
||||||
|
tupleToCoors(
|
||||||
|
LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||||
|
element,
|
||||||
|
selectedPoint!,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Scene.getScene(element)!,
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
bindings[
|
||||||
|
selectedPoint === 0 ? "startBindingElement" : "endBindingElement"
|
||||||
|
] = bindingElement;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
const bindingElement = isBindingEnabled(appState)
|
|
||||||
? getHoveredElementForBinding(
|
|
||||||
tupleToCoors(
|
|
||||||
LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
|
||||||
element,
|
|
||||||
activePointIndex!,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Scene.getScene(element)!,
|
|
||||||
)
|
|
||||||
: null;
|
|
||||||
binding = {
|
|
||||||
[activePointIndex === 0 ? "startBindingElement" : "endBindingElement"]:
|
|
||||||
bindingElement,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...editingLinearElement,
|
...editingLinearElement,
|
||||||
...binding,
|
...bindings,
|
||||||
|
// if clicking without previously dragging a point(s), and not holding
|
||||||
|
// shift, deselect all points except the one clicked. If holding shift,
|
||||||
|
// toggle the point.
|
||||||
|
selectedPointsIndices:
|
||||||
|
isDragging || event.shiftKey
|
||||||
|
? !isDragging &&
|
||||||
|
event.shiftKey &&
|
||||||
|
pointerDownState.prevSelectedPointsIndices?.includes(
|
||||||
|
pointerDownState.lastClickedPoint,
|
||||||
|
)
|
||||||
|
? selectedPointsIndices &&
|
||||||
|
selectedPointsIndices.filter(
|
||||||
|
(pointIndex) =>
|
||||||
|
pointIndex !== pointerDownState.lastClickedPoint,
|
||||||
|
)
|
||||||
|
: selectedPointsIndices
|
||||||
|
: selectedPointsIndices?.includes(pointerDownState.lastClickedPoint)
|
||||||
|
? [pointerDownState.lastClickedPoint]
|
||||||
|
: selectedPointsIndices,
|
||||||
isDragging: false,
|
isDragging: false,
|
||||||
pointerOffset: { x: 0, y: 0 },
|
pointerOffset: { x: 0, y: 0 },
|
||||||
};
|
};
|
||||||
@@ -206,7 +371,12 @@ export class LinearElementEditor {
|
|||||||
setState({
|
setState({
|
||||||
editingLinearElement: {
|
editingLinearElement: {
|
||||||
...appState.editingLinearElement,
|
...appState.editingLinearElement,
|
||||||
activePointIndex: element.points.length - 1,
|
pointerDownState: {
|
||||||
|
prevSelectedPointsIndices:
|
||||||
|
appState.editingLinearElement.selectedPointsIndices,
|
||||||
|
lastClickedPoint: -1,
|
||||||
|
},
|
||||||
|
selectedPointsIndices: [element.points.length - 1],
|
||||||
lastUncommittedPoint: null,
|
lastUncommittedPoint: null,
|
||||||
endBindingElement: getHoveredElementForBinding(
|
endBindingElement: getHoveredElementForBinding(
|
||||||
scenePointer,
|
scenePointer,
|
||||||
@@ -231,7 +401,7 @@ export class LinearElementEditor {
|
|||||||
ret.hitElement = element;
|
ret.hitElement = element;
|
||||||
} else {
|
} else {
|
||||||
// You might be wandering why we are storing the binding elements on
|
// You might be wandering why we are storing the binding elements on
|
||||||
// LinearElementEditor and passing them in, insted of calculating them
|
// LinearElementEditor and passing them in, instead of calculating them
|
||||||
// from the end points of the `linearElement` - this is to allow disabling
|
// from the end points of the `linearElement` - this is to allow disabling
|
||||||
// binding (which needs to happen at the point the user finishes moving
|
// binding (which needs to happen at the point the user finishes moving
|
||||||
// the point).
|
// the point).
|
||||||
@@ -259,10 +429,28 @@ export class LinearElementEditor {
|
|||||||
element.angle,
|
element.angle,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const nextSelectedPointsIndices =
|
||||||
|
clickedPointIndex > -1 || event.shiftKey
|
||||||
|
? event.shiftKey ||
|
||||||
|
appState.editingLinearElement.selectedPointsIndices?.includes(
|
||||||
|
clickedPointIndex,
|
||||||
|
)
|
||||||
|
? normalizeSelectedPoints([
|
||||||
|
...(appState.editingLinearElement.selectedPointsIndices || []),
|
||||||
|
clickedPointIndex,
|
||||||
|
])
|
||||||
|
: [clickedPointIndex]
|
||||||
|
: null;
|
||||||
|
|
||||||
setState({
|
setState({
|
||||||
editingLinearElement: {
|
editingLinearElement: {
|
||||||
...appState.editingLinearElement,
|
...appState.editingLinearElement,
|
||||||
activePointIndex: clickedPointIndex > -1 ? clickedPointIndex : null,
|
pointerDownState: {
|
||||||
|
prevSelectedPointsIndices:
|
||||||
|
appState.editingLinearElement.selectedPointsIndices,
|
||||||
|
lastClickedPoint: clickedPointIndex,
|
||||||
|
},
|
||||||
|
selectedPointsIndices: nextSelectedPointsIndices,
|
||||||
pointerOffset: targetPoint
|
pointerOffset: targetPoint
|
||||||
? {
|
? {
|
||||||
x: scenePointer.x - targetPoint[0],
|
x: scenePointer.x - targetPoint[0],
|
||||||
@@ -292,7 +480,7 @@ export class LinearElementEditor {
|
|||||||
|
|
||||||
if (!event.altKey) {
|
if (!event.altKey) {
|
||||||
if (lastPoint === lastUncommittedPoint) {
|
if (lastPoint === lastUncommittedPoint) {
|
||||||
LinearElementEditor.movePoint(element, points.length - 1, "delete");
|
LinearElementEditor.deletePoints(element, [points.length - 1]);
|
||||||
}
|
}
|
||||||
return { ...editingLinearElement, lastUncommittedPoint: null };
|
return { ...editingLinearElement, lastUncommittedPoint: null };
|
||||||
}
|
}
|
||||||
@@ -305,13 +493,14 @@ export class LinearElementEditor {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (lastPoint === lastUncommittedPoint) {
|
if (lastPoint === lastUncommittedPoint) {
|
||||||
LinearElementEditor.movePoint(
|
LinearElementEditor.movePoints(element, [
|
||||||
element,
|
{
|
||||||
element.points.length - 1,
|
index: element.points.length - 1,
|
||||||
newPoint,
|
point: newPoint,
|
||||||
);
|
},
|
||||||
|
]);
|
||||||
} else {
|
} else {
|
||||||
LinearElementEditor.movePoint(element, "new", newPoint);
|
LinearElementEditor.addPoints(element, [{ point: newPoint }]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -320,6 +509,21 @@ export class LinearElementEditor {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** scene coords */
|
||||||
|
static getPointGlobalCoordinates(
|
||||||
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
point: Point,
|
||||||
|
) {
|
||||||
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||||
|
const cx = (x1 + x2) / 2;
|
||||||
|
const cy = (y1 + y2) / 2;
|
||||||
|
|
||||||
|
let { x, y } = element;
|
||||||
|
[x, y] = rotate(x + point[0], y + point[1], cx, cy, element.angle);
|
||||||
|
return [x, y] as const;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** scene coords */
|
||||||
static getPointsGlobalCoordinates(
|
static getPointsGlobalCoordinates(
|
||||||
element: NonDeleted<ExcalidrawLinearElement>,
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
) {
|
) {
|
||||||
@@ -439,22 +643,122 @@ export class LinearElementEditor {
|
|||||||
mutateElement(element, LinearElementEditor.getNormalizedPoints(element));
|
mutateElement(element, LinearElementEditor.getNormalizedPoints(element));
|
||||||
}
|
}
|
||||||
|
|
||||||
static movePointByOffset(
|
static duplicateSelectedPoints(appState: AppState) {
|
||||||
element: NonDeleted<ExcalidrawLinearElement>,
|
if (!appState.editingLinearElement) {
|
||||||
pointIndex: number,
|
return false;
|
||||||
offset: { x: number; y: number },
|
}
|
||||||
) {
|
|
||||||
const [x, y] = element.points[pointIndex];
|
const { selectedPointsIndices, elementId } = appState.editingLinearElement;
|
||||||
LinearElementEditor.movePoint(element, pointIndex, [
|
|
||||||
x + offset.x,
|
const element = LinearElementEditor.getElement(elementId);
|
||||||
y + offset.y,
|
|
||||||
]);
|
if (!element || selectedPointsIndices === null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { points } = element;
|
||||||
|
|
||||||
|
const nextSelectedIndices: number[] = [];
|
||||||
|
|
||||||
|
let pointAddedToEnd = false;
|
||||||
|
let indexCursor = -1;
|
||||||
|
const nextPoints = points.reduce((acc: Point[], point, index) => {
|
||||||
|
++indexCursor;
|
||||||
|
acc.push(point);
|
||||||
|
|
||||||
|
const isSelected = selectedPointsIndices.includes(index);
|
||||||
|
if (isSelected) {
|
||||||
|
const nextPoint = points[index + 1];
|
||||||
|
|
||||||
|
if (!nextPoint) {
|
||||||
|
pointAddedToEnd = true;
|
||||||
|
}
|
||||||
|
acc.push(
|
||||||
|
nextPoint
|
||||||
|
? [(point[0] + nextPoint[0]) / 2, (point[1] + nextPoint[1]) / 2]
|
||||||
|
: [point[0], point[1]],
|
||||||
|
);
|
||||||
|
|
||||||
|
nextSelectedIndices.push(indexCursor + 1);
|
||||||
|
++indexCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
mutateElement(element, { points: nextPoints });
|
||||||
|
|
||||||
|
// temp hack to ensure the line doesn't move when adding point to the end,
|
||||||
|
// potentially expanding the bounding box
|
||||||
|
if (pointAddedToEnd) {
|
||||||
|
const lastPoint = element.points[element.points.length - 1];
|
||||||
|
LinearElementEditor.movePoints(element, [
|
||||||
|
{
|
||||||
|
index: element.points.length - 1,
|
||||||
|
point: [lastPoint[0] + 30, lastPoint[1] + 30],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
appState: {
|
||||||
|
...appState,
|
||||||
|
editingLinearElement: {
|
||||||
|
...appState.editingLinearElement,
|
||||||
|
selectedPointsIndices: nextSelectedIndices,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
static movePoint(
|
static deletePoints(
|
||||||
element: NonDeleted<ExcalidrawLinearElement>,
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
pointIndex: number | "new",
|
pointIndices: readonly number[],
|
||||||
targetPosition: Point | "delete",
|
) {
|
||||||
|
let offsetX = 0;
|
||||||
|
let offsetY = 0;
|
||||||
|
|
||||||
|
const isDeletingOriginPoint = pointIndices.includes(0);
|
||||||
|
|
||||||
|
// if deleting first point, make the next to be [0,0] and recalculate
|
||||||
|
// positions of the rest with respect to it
|
||||||
|
if (isDeletingOriginPoint) {
|
||||||
|
const firstNonDeletedPoint = element.points.find((point, idx) => {
|
||||||
|
return !pointIndices.includes(idx);
|
||||||
|
});
|
||||||
|
if (firstNonDeletedPoint) {
|
||||||
|
offsetX = firstNonDeletedPoint[0];
|
||||||
|
offsetY = firstNonDeletedPoint[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextPoints = element.points.reduce((acc: Point[], point, idx) => {
|
||||||
|
if (!pointIndices.includes(idx)) {
|
||||||
|
acc.push(
|
||||||
|
!acc.length ? [0, 0] : [point[0] - offsetX, point[1] - offsetY],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return acc;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
LinearElementEditor._updatePoints(element, nextPoints, offsetX, offsetY);
|
||||||
|
}
|
||||||
|
|
||||||
|
static addPoints(
|
||||||
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
targetPoints: { point: Point }[],
|
||||||
|
) {
|
||||||
|
const offsetX = 0;
|
||||||
|
const offsetY = 0;
|
||||||
|
|
||||||
|
const nextPoints = [...element.points, ...targetPoints.map((x) => x.point)];
|
||||||
|
|
||||||
|
LinearElementEditor._updatePoints(element, nextPoints, offsetX, offsetY);
|
||||||
|
}
|
||||||
|
|
||||||
|
static movePoints(
|
||||||
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
targetPoints: { index: number; point: Point; isDragging?: boolean }[],
|
||||||
otherUpdates?: { startBinding?: PointBinding; endBinding?: PointBinding },
|
otherUpdates?: { startBinding?: PointBinding; endBinding?: PointBinding },
|
||||||
) {
|
) {
|
||||||
const { points } = element;
|
const { points } = element;
|
||||||
@@ -467,49 +771,50 @@ export class LinearElementEditor {
|
|||||||
let offsetX = 0;
|
let offsetX = 0;
|
||||||
let offsetY = 0;
|
let offsetY = 0;
|
||||||
|
|
||||||
let nextPoints: (readonly [number, number])[];
|
const selectedOriginPoint = targetPoints.find(({ index }) => index === 0);
|
||||||
if (targetPosition === "delete") {
|
|
||||||
// remove point
|
|
||||||
if (pointIndex === "new") {
|
|
||||||
throw new Error("invalid args in movePoint");
|
|
||||||
}
|
|
||||||
nextPoints = points.slice();
|
|
||||||
nextPoints.splice(pointIndex, 1);
|
|
||||||
if (pointIndex === 0) {
|
|
||||||
// if deleting first point, make the next to be [0,0] and recalculate
|
|
||||||
// positions of the rest with respect to it
|
|
||||||
offsetX = nextPoints[0][0];
|
|
||||||
offsetY = nextPoints[0][1];
|
|
||||||
nextPoints = nextPoints.map((point, idx) => {
|
|
||||||
if (idx === 0) {
|
|
||||||
return [0, 0];
|
|
||||||
}
|
|
||||||
return [point[0] - offsetX, point[1] - offsetY];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if (pointIndex === "new") {
|
|
||||||
nextPoints = [...points, targetPosition];
|
|
||||||
} else {
|
|
||||||
const deltaX = targetPosition[0] - points[pointIndex][0];
|
|
||||||
const deltaY = targetPosition[1] - points[pointIndex][1];
|
|
||||||
nextPoints = points.map((point, idx) => {
|
|
||||||
if (idx === pointIndex) {
|
|
||||||
if (idx === 0) {
|
|
||||||
offsetX = deltaX;
|
|
||||||
offsetY = deltaY;
|
|
||||||
return point;
|
|
||||||
}
|
|
||||||
offsetX = 0;
|
|
||||||
offsetY = 0;
|
|
||||||
|
|
||||||
return [point[0] + deltaX, point[1] + deltaY] as const;
|
if (selectedOriginPoint) {
|
||||||
}
|
offsetX =
|
||||||
return offsetX || offsetY
|
selectedOriginPoint.point[0] - points[selectedOriginPoint.index][0];
|
||||||
? ([point[0] - offsetX, point[1] - offsetY] as const)
|
offsetY =
|
||||||
: point;
|
selectedOriginPoint.point[1] - points[selectedOriginPoint.index][1];
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const nextPoints = points.map((point, idx) => {
|
||||||
|
const selectedPointData = targetPoints.find((p) => p.index === idx);
|
||||||
|
if (selectedPointData) {
|
||||||
|
if (selectedOriginPoint) {
|
||||||
|
return point;
|
||||||
|
}
|
||||||
|
|
||||||
|
const deltaX =
|
||||||
|
selectedPointData.point[0] - points[selectedPointData.index][0];
|
||||||
|
const deltaY =
|
||||||
|
selectedPointData.point[1] - points[selectedPointData.index][1];
|
||||||
|
|
||||||
|
return [point[0] + deltaX, point[1] + deltaY] as const;
|
||||||
|
}
|
||||||
|
return offsetX || offsetY
|
||||||
|
? ([point[0] - offsetX, point[1] - offsetY] as const)
|
||||||
|
: point;
|
||||||
|
});
|
||||||
|
|
||||||
|
LinearElementEditor._updatePoints(
|
||||||
|
element,
|
||||||
|
nextPoints,
|
||||||
|
offsetX,
|
||||||
|
offsetY,
|
||||||
|
otherUpdates,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static _updatePoints(
|
||||||
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
nextPoints: readonly Point[],
|
||||||
|
offsetX: number,
|
||||||
|
offsetY: number,
|
||||||
|
otherUpdates?: { startBinding?: PointBinding; endBinding?: PointBinding },
|
||||||
|
) {
|
||||||
const nextCoords = getElementPointsCoords(
|
const nextCoords = getElementPointsCoords(
|
||||||
element,
|
element,
|
||||||
nextPoints,
|
nextPoints,
|
||||||
@@ -517,7 +822,7 @@ export class LinearElementEditor {
|
|||||||
);
|
);
|
||||||
const prevCoords = getElementPointsCoords(
|
const prevCoords = getElementPointsCoords(
|
||||||
element,
|
element,
|
||||||
points,
|
element.points,
|
||||||
element.strokeSharpness || "round",
|
element.strokeSharpness || "round",
|
||||||
);
|
);
|
||||||
const nextCenterX = (nextCoords[0] + nextCoords[2]) / 2;
|
const nextCenterX = (nextCoords[0] + nextCoords[2]) / 2;
|
||||||
@@ -536,3 +841,13 @@ export class LinearElementEditor {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const normalizeSelectedPoints = (
|
||||||
|
points: (number | null)[],
|
||||||
|
): number[] | null => {
|
||||||
|
let nextPoints = [
|
||||||
|
...new Set(points.filter((p) => p !== null && p !== -1)),
|
||||||
|
] as number[];
|
||||||
|
nextPoints = nextPoints.sort((a, b) => a - b);
|
||||||
|
return nextPoints.length ? nextPoints : null;
|
||||||
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import Scene from "../scene/Scene";
|
|||||||
import { getSizeFromPoints } from "../points";
|
import { getSizeFromPoints } from "../points";
|
||||||
import { randomInteger } from "../random";
|
import { randomInteger } from "../random";
|
||||||
import { Point } from "../types";
|
import { Point } from "../types";
|
||||||
|
import { getUpdatedTimestamp } from "../utils";
|
||||||
|
|
||||||
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
||||||
Partial<TElement>,
|
Partial<TElement>,
|
||||||
@@ -92,6 +93,7 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|||||||
|
|
||||||
element.version++;
|
element.version++;
|
||||||
element.versionNonce = randomInteger();
|
element.versionNonce = randomInteger();
|
||||||
|
element.updated = getUpdatedTimestamp();
|
||||||
|
|
||||||
if (informMutation) {
|
if (informMutation) {
|
||||||
Scene.getScene(element)?.informMutation();
|
Scene.getScene(element)?.informMutation();
|
||||||
@@ -126,13 +128,14 @@ export const newElementWith = <TElement extends ExcalidrawElement>(
|
|||||||
return {
|
return {
|
||||||
...element,
|
...element,
|
||||||
...updates,
|
...updates,
|
||||||
|
updated: getUpdatedTimestamp(),
|
||||||
version: element.version + 1,
|
version: element.version + 1,
|
||||||
versionNonce: randomInteger(),
|
versionNonce: randomInteger(),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mutates element and updates `version` & `versionNonce`.
|
* Mutates element, bumping `version`, `versionNonce`, and `updated`.
|
||||||
*
|
*
|
||||||
* NOTE: does not trigger re-render.
|
* NOTE: does not trigger re-render.
|
||||||
*/
|
*/
|
||||||
@@ -142,5 +145,6 @@ export const bumpVersion = (
|
|||||||
) => {
|
) => {
|
||||||
element.version = (version ?? element.version) + 1;
|
element.version = (version ?? element.version) + 1;
|
||||||
element.versionNonce = randomInteger();
|
element.versionNonce = randomInteger();
|
||||||
|
element.updated = getUpdatedTimestamp();
|
||||||
return element;
|
return element;
|
||||||
};
|
};
|
||||||
|
|||||||
+90
-36
@@ -11,26 +11,30 @@ import {
|
|||||||
Arrowhead,
|
Arrowhead,
|
||||||
ExcalidrawFreeDrawElement,
|
ExcalidrawFreeDrawElement,
|
||||||
FontFamilyValues,
|
FontFamilyValues,
|
||||||
|
ExcalidrawRectangleElement,
|
||||||
} from "../element/types";
|
} from "../element/types";
|
||||||
import { measureText, getFontString } from "../utils";
|
import { getFontString, getUpdatedTimestamp, isTestEnv } from "../utils";
|
||||||
import { randomInteger, randomId } from "../random";
|
import { randomInteger, randomId } from "../random";
|
||||||
import { newElementWith } from "./mutateElement";
|
import { mutateElement, newElementWith } from "./mutateElement";
|
||||||
import { getNewGroupIdsForDuplication } from "../groups";
|
import { getNewGroupIdsForDuplication } from "../groups";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
import { getElementAbsoluteCoords } from ".";
|
import { getElementAbsoluteCoords } from ".";
|
||||||
import { adjustXYWithRotation } from "../math";
|
import { adjustXYWithRotation } from "../math";
|
||||||
import { getResizedElementAbsoluteCoords } from "./bounds";
|
import { getResizedElementAbsoluteCoords } from "./bounds";
|
||||||
|
import { getContainerElement, measureText, wrapText } from "./textElement";
|
||||||
|
import { BOUND_TEXT_PADDING, VERTICAL_ALIGN } from "../constants";
|
||||||
|
|
||||||
type ElementConstructorOpts = MarkOptional<
|
type ElementConstructorOpts = MarkOptional<
|
||||||
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted">,
|
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">,
|
||||||
| "width"
|
| "width"
|
||||||
| "height"
|
| "height"
|
||||||
| "angle"
|
| "angle"
|
||||||
| "groupIds"
|
| "groupIds"
|
||||||
| "boundElementIds"
|
| "boundElements"
|
||||||
| "seed"
|
| "seed"
|
||||||
| "version"
|
| "version"
|
||||||
| "versionNonce"
|
| "versionNonce"
|
||||||
|
| "link"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
const _newElementBase = <T extends ExcalidrawElement>(
|
const _newElementBase = <T extends ExcalidrawElement>(
|
||||||
@@ -50,32 +54,38 @@ const _newElementBase = <T extends ExcalidrawElement>(
|
|||||||
angle = 0,
|
angle = 0,
|
||||||
groupIds = [],
|
groupIds = [],
|
||||||
strokeSharpness,
|
strokeSharpness,
|
||||||
boundElementIds = null,
|
boundElements = null,
|
||||||
|
link = null,
|
||||||
...rest
|
...rest
|
||||||
}: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">,
|
}: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">,
|
||||||
) => ({
|
) => {
|
||||||
id: rest.id || randomId(),
|
const element = {
|
||||||
type,
|
id: rest.id || randomId(),
|
||||||
x,
|
type,
|
||||||
y,
|
x,
|
||||||
width,
|
y,
|
||||||
height,
|
width,
|
||||||
angle,
|
height,
|
||||||
strokeColor,
|
angle,
|
||||||
backgroundColor,
|
strokeColor,
|
||||||
fillStyle,
|
backgroundColor,
|
||||||
strokeWidth,
|
fillStyle,
|
||||||
strokeStyle,
|
strokeWidth,
|
||||||
roughness,
|
strokeStyle,
|
||||||
opacity,
|
roughness,
|
||||||
groupIds,
|
opacity,
|
||||||
strokeSharpness,
|
groupIds,
|
||||||
seed: rest.seed ?? randomInteger(),
|
strokeSharpness,
|
||||||
version: rest.version || 1,
|
seed: rest.seed ?? randomInteger(),
|
||||||
versionNonce: rest.versionNonce ?? 0,
|
version: rest.version || 1,
|
||||||
isDeleted: false as false,
|
versionNonce: rest.versionNonce ?? 0,
|
||||||
boundElementIds,
|
isDeleted: false as false,
|
||||||
});
|
boundElements,
|
||||||
|
updated: getUpdatedTimestamp(),
|
||||||
|
link,
|
||||||
|
};
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
|
||||||
export const newElement = (
|
export const newElement = (
|
||||||
opts: {
|
opts: {
|
||||||
@@ -113,6 +123,7 @@ export const newTextElement = (
|
|||||||
fontFamily: FontFamilyValues;
|
fontFamily: FontFamilyValues;
|
||||||
textAlign: TextAlign;
|
textAlign: TextAlign;
|
||||||
verticalAlign: VerticalAlign;
|
verticalAlign: VerticalAlign;
|
||||||
|
containerId?: ExcalidrawRectangleElement["id"];
|
||||||
} & ElementConstructorOpts,
|
} & ElementConstructorOpts,
|
||||||
): NonDeleted<ExcalidrawTextElement> => {
|
): NonDeleted<ExcalidrawTextElement> => {
|
||||||
const metrics = measureText(opts.text, getFontString(opts));
|
const metrics = measureText(opts.text, getFontString(opts));
|
||||||
@@ -130,6 +141,8 @@ export const newTextElement = (
|
|||||||
width: metrics.width,
|
width: metrics.width,
|
||||||
height: metrics.height,
|
height: metrics.height,
|
||||||
baseline: metrics.baseline,
|
baseline: metrics.baseline,
|
||||||
|
containerId: opts.containerId || null,
|
||||||
|
originalText: opts.text,
|
||||||
},
|
},
|
||||||
{},
|
{},
|
||||||
);
|
);
|
||||||
@@ -146,18 +159,29 @@ const getAdjustedDimensions = (
|
|||||||
height: number;
|
height: number;
|
||||||
baseline: number;
|
baseline: number;
|
||||||
} => {
|
} => {
|
||||||
|
let maxWidth = null;
|
||||||
|
const container = getContainerElement(element);
|
||||||
|
if (container) {
|
||||||
|
maxWidth = container.width - BOUND_TEXT_PADDING * 2;
|
||||||
|
}
|
||||||
const {
|
const {
|
||||||
width: nextWidth,
|
width: nextWidth,
|
||||||
height: nextHeight,
|
height: nextHeight,
|
||||||
baseline: nextBaseline,
|
baseline: nextBaseline,
|
||||||
} = measureText(nextText, getFontString(element));
|
} = measureText(nextText, getFontString(element), maxWidth);
|
||||||
const { textAlign, verticalAlign } = element;
|
const { textAlign, verticalAlign } = element;
|
||||||
|
|
||||||
let x: number;
|
let x: number;
|
||||||
let y: number;
|
let y: number;
|
||||||
|
if (
|
||||||
if (textAlign === "center" && verticalAlign === "middle") {
|
textAlign === "center" &&
|
||||||
const prevMetrics = measureText(element.text, getFontString(element));
|
verticalAlign === VERTICAL_ALIGN.MIDDLE &&
|
||||||
|
!element.containerId
|
||||||
|
) {
|
||||||
|
const prevMetrics = measureText(
|
||||||
|
element.text,
|
||||||
|
getFontString(element),
|
||||||
|
maxWidth,
|
||||||
|
);
|
||||||
const offsets = getTextElementPositionOffsets(element, {
|
const offsets = getTextElementPositionOffsets(element, {
|
||||||
width: nextWidth - prevMetrics.width,
|
width: nextWidth - prevMetrics.width,
|
||||||
height: nextHeight - prevMetrics.height,
|
height: nextHeight - prevMetrics.height,
|
||||||
@@ -194,6 +218,21 @@ const getAdjustedDimensions = (
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// make sure container dimensions are set properly when
|
||||||
|
// text editor overflows beyond viewport dimensions
|
||||||
|
if (container) {
|
||||||
|
let height = container.height;
|
||||||
|
let width = container.width;
|
||||||
|
if (nextHeight > height - BOUND_TEXT_PADDING * 2) {
|
||||||
|
height = nextHeight + BOUND_TEXT_PADDING * 2;
|
||||||
|
}
|
||||||
|
if (nextWidth > width - BOUND_TEXT_PADDING * 2) {
|
||||||
|
width = nextWidth + BOUND_TEXT_PADDING * 2;
|
||||||
|
}
|
||||||
|
if (height !== container.height || width !== container.width) {
|
||||||
|
mutateElement(container, { height, width });
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
width: nextWidth,
|
width: nextWidth,
|
||||||
height: nextHeight,
|
height: nextHeight,
|
||||||
@@ -205,12 +244,26 @@ const getAdjustedDimensions = (
|
|||||||
|
|
||||||
export const updateTextElement = (
|
export const updateTextElement = (
|
||||||
element: ExcalidrawTextElement,
|
element: ExcalidrawTextElement,
|
||||||
{ text, isDeleted }: { text: string; isDeleted?: boolean },
|
{
|
||||||
|
text,
|
||||||
|
isDeleted,
|
||||||
|
originalText,
|
||||||
|
}: {
|
||||||
|
text: string;
|
||||||
|
isDeleted?: boolean;
|
||||||
|
originalText: string;
|
||||||
|
},
|
||||||
): ExcalidrawTextElement => {
|
): ExcalidrawTextElement => {
|
||||||
|
const container = getContainerElement(element);
|
||||||
|
if (container) {
|
||||||
|
text = wrapText(text, getFontString(element), container.width);
|
||||||
|
}
|
||||||
|
const dimensions = getAdjustedDimensions(element, text);
|
||||||
return newElementWith(element, {
|
return newElementWith(element, {
|
||||||
text,
|
text,
|
||||||
|
originalText,
|
||||||
isDeleted: isDeleted ?? element.isDeleted,
|
isDeleted: isDeleted ?? element.isDeleted,
|
||||||
...getAdjustedDimensions(element, text),
|
...dimensions,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -324,7 +377,7 @@ export const duplicateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|||||||
overrides?: Partial<TElement>,
|
overrides?: Partial<TElement>,
|
||||||
): TElement => {
|
): TElement => {
|
||||||
let copy: TElement = deepCopyElement(element);
|
let copy: TElement = deepCopyElement(element);
|
||||||
if (process.env.NODE_ENV === "test") {
|
if (isTestEnv()) {
|
||||||
copy.id = `${copy.id}_copy`;
|
copy.id = `${copy.id}_copy`;
|
||||||
// `window.h` may not be defined in some unit tests
|
// `window.h` may not be defined in some unit tests
|
||||||
if (
|
if (
|
||||||
@@ -337,6 +390,7 @@ export const duplicateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|||||||
} else {
|
} else {
|
||||||
copy.id = randomId();
|
copy.id = randomId();
|
||||||
}
|
}
|
||||||
|
copy.updated = getUpdatedTimestamp();
|
||||||
copy.seed = randomInteger();
|
copy.seed = randomInteger();
|
||||||
copy.groupIds = getNewGroupIdsForDuplication(
|
copy.groupIds = getNewGroupIdsForDuplication(
|
||||||
copy.groupIds,
|
copy.groupIds,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SHIFT_LOCKING_ANGLE } from "../constants";
|
import { BOUND_TEXT_PADDING, SHIFT_LOCKING_ANGLE } from "../constants";
|
||||||
import { rescalePoints } from "../points";
|
import { rescalePoints } from "../points";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
@@ -25,7 +25,7 @@ import {
|
|||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import { getPerfectElementSize } from "./sizeHelpers";
|
import { getPerfectElementSize } from "./sizeHelpers";
|
||||||
import { measureText, getFontString } from "../utils";
|
import { getFontString } from "../utils";
|
||||||
import { updateBoundElements } from "./binding";
|
import { updateBoundElements } from "./binding";
|
||||||
import {
|
import {
|
||||||
TransformHandleType,
|
TransformHandleType,
|
||||||
@@ -33,6 +33,15 @@ import {
|
|||||||
TransformHandleDirection,
|
TransformHandleDirection,
|
||||||
} from "./transformHandles";
|
} from "./transformHandles";
|
||||||
import { Point, PointerDownState } from "../types";
|
import { Point, PointerDownState } from "../types";
|
||||||
|
import Scene from "../scene/Scene";
|
||||||
|
import {
|
||||||
|
getApproxMinLineHeight,
|
||||||
|
getApproxMinLineWidth,
|
||||||
|
getBoundTextElement,
|
||||||
|
getBoundTextElementId,
|
||||||
|
handleBindTextResize,
|
||||||
|
measureText,
|
||||||
|
} from "./textElement";
|
||||||
|
|
||||||
export const normalizeAngle = (angle: number): number => {
|
export const normalizeAngle = (angle: number): number => {
|
||||||
if (angle >= 2 * Math.PI) {
|
if (angle >= 2 * Math.PI) {
|
||||||
@@ -97,7 +106,7 @@ export const transformElements = (
|
|||||||
updateBoundElements(element);
|
updateBoundElements(element);
|
||||||
} else if (transformHandleType) {
|
} else if (transformHandleType) {
|
||||||
resizeSingleElement(
|
resizeSingleElement(
|
||||||
pointerDownState.originalElements.get(element.id) as typeof element,
|
pointerDownState.originalElements,
|
||||||
shouldMaintainAspectRatio,
|
shouldMaintainAspectRatio,
|
||||||
element,
|
element,
|
||||||
transformHandleType,
|
transformHandleType,
|
||||||
@@ -154,6 +163,11 @@ const rotateSingleElement = (
|
|||||||
}
|
}
|
||||||
angle = normalizeAngle(angle);
|
angle = normalizeAngle(angle);
|
||||||
mutateElement(element, { angle });
|
mutateElement(element, { angle });
|
||||||
|
const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
if (boundTextElementId) {
|
||||||
|
const textElement = Scene.getScene(element)!.getElement(boundTextElementId);
|
||||||
|
mutateElement(textElement!, { angle });
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// used in DEV only
|
// used in DEV only
|
||||||
@@ -272,6 +286,7 @@ const measureFontSizeFromWH = (
|
|||||||
const metrics = measureText(
|
const metrics = measureText(
|
||||||
element.text,
|
element.text,
|
||||||
getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }),
|
getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }),
|
||||||
|
element.containerId ? element.width : null,
|
||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
size: nextFontSize,
|
size: nextFontSize,
|
||||||
@@ -382,7 +397,7 @@ const resizeSingleTextElement = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const resizeSingleElement = (
|
export const resizeSingleElement = (
|
||||||
stateAtResizeStart: NonDeletedExcalidrawElement,
|
originalElements: PointerDownState["originalElements"],
|
||||||
shouldMaintainAspectRatio: boolean,
|
shouldMaintainAspectRatio: boolean,
|
||||||
element: NonDeletedExcalidrawElement,
|
element: NonDeletedExcalidrawElement,
|
||||||
transformHandleDirection: TransformHandleDirection,
|
transformHandleDirection: TransformHandleDirection,
|
||||||
@@ -390,6 +405,7 @@ export const resizeSingleElement = (
|
|||||||
pointerX: number,
|
pointerX: number,
|
||||||
pointerY: number,
|
pointerY: number,
|
||||||
) => {
|
) => {
|
||||||
|
const stateAtResizeStart = originalElements.get(element.id)!;
|
||||||
// Gets bounds corners
|
// Gets bounds corners
|
||||||
const [x1, y1, x2, y2] = getResizedElementAbsoluteCoords(
|
const [x1, y1, x2, y2] = getResizedElementAbsoluteCoords(
|
||||||
stateAtResizeStart,
|
stateAtResizeStart,
|
||||||
@@ -413,6 +429,7 @@ export const resizeSingleElement = (
|
|||||||
element.width,
|
element.width,
|
||||||
element.height,
|
element.height,
|
||||||
);
|
);
|
||||||
|
|
||||||
const boundsCurrentWidth = esx2 - esx1;
|
const boundsCurrentWidth = esx2 - esx1;
|
||||||
const boundsCurrentHeight = esy2 - esy1;
|
const boundsCurrentHeight = esy2 - esy1;
|
||||||
|
|
||||||
@@ -423,6 +440,9 @@ export const resizeSingleElement = (
|
|||||||
let scaleX = atStartBoundsWidth / boundsCurrentWidth;
|
let scaleX = atStartBoundsWidth / boundsCurrentWidth;
|
||||||
let scaleY = atStartBoundsHeight / boundsCurrentHeight;
|
let scaleY = atStartBoundsHeight / boundsCurrentHeight;
|
||||||
|
|
||||||
|
let boundTextFont: { fontSize?: number; baseline?: number } = {};
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
|
||||||
if (transformHandleDirection.includes("e")) {
|
if (transformHandleDirection.includes("e")) {
|
||||||
scaleX = (rotatedPointer[0] - startTopLeft[0]) / boundsCurrentWidth;
|
scaleX = (rotatedPointer[0] - startTopLeft[0]) / boundsCurrentWidth;
|
||||||
}
|
}
|
||||||
@@ -435,6 +455,7 @@ export const resizeSingleElement = (
|
|||||||
if (transformHandleDirection.includes("n")) {
|
if (transformHandleDirection.includes("n")) {
|
||||||
scaleY = (startBottomRight[1] - rotatedPointer[1]) / boundsCurrentHeight;
|
scaleY = (startBottomRight[1] - rotatedPointer[1]) / boundsCurrentHeight;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Linear elements dimensions differ from bounds dimensions
|
// Linear elements dimensions differ from bounds dimensions
|
||||||
const eleInitialWidth = stateAtResizeStart.width;
|
const eleInitialWidth = stateAtResizeStart.width;
|
||||||
const eleInitialHeight = stateAtResizeStart.height;
|
const eleInitialHeight = stateAtResizeStart.height;
|
||||||
@@ -464,6 +485,37 @@ export const resizeSingleElement = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (boundTextElement) {
|
||||||
|
const stateOfBoundTextElementAtResize = originalElements.get(
|
||||||
|
boundTextElement.id,
|
||||||
|
) as typeof boundTextElement | undefined;
|
||||||
|
if (stateOfBoundTextElementAtResize) {
|
||||||
|
boundTextFont = {
|
||||||
|
fontSize: stateOfBoundTextElementAtResize.fontSize,
|
||||||
|
baseline: stateOfBoundTextElementAtResize.baseline,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (shouldMaintainAspectRatio) {
|
||||||
|
const nextFont = measureFontSizeFromWH(
|
||||||
|
boundTextElement,
|
||||||
|
eleNewWidth - BOUND_TEXT_PADDING * 2,
|
||||||
|
eleNewHeight - BOUND_TEXT_PADDING * 2,
|
||||||
|
);
|
||||||
|
if (nextFont === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
boundTextFont = {
|
||||||
|
fontSize: nextFont.size,
|
||||||
|
baseline: nextFont.baseline,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
const minWidth = getApproxMinLineWidth(getFontString(boundTextElement));
|
||||||
|
const minHeight = getApproxMinLineHeight(getFontString(boundTextElement));
|
||||||
|
eleNewWidth = Math.ceil(Math.max(eleNewWidth, minWidth));
|
||||||
|
eleNewHeight = Math.ceil(Math.max(eleNewHeight, minHeight));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const [newBoundsX1, newBoundsY1, newBoundsX2, newBoundsY2] =
|
const [newBoundsX1, newBoundsY1, newBoundsX2, newBoundsY2] =
|
||||||
getResizedElementAbsoluteCoords(
|
getResizedElementAbsoluteCoords(
|
||||||
stateAtResizeStart,
|
stateAtResizeStart,
|
||||||
@@ -576,6 +628,10 @@ export const resizeSingleElement = (
|
|||||||
newSize: { width: resizedElement.width, height: resizedElement.height },
|
newSize: { width: resizedElement.width, height: resizedElement.height },
|
||||||
});
|
});
|
||||||
mutateElement(element, resizedElement);
|
mutateElement(element, resizedElement);
|
||||||
|
if (boundTextElement && boundTextFont) {
|
||||||
|
mutateElement(boundTextElement, { fontSize: boundTextFont.fontSize });
|
||||||
|
}
|
||||||
|
handleBindTextResize(element, transformHandleDirection);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -646,8 +702,26 @@ const resizeMultipleElements = (
|
|||||||
}
|
}
|
||||||
const width = element.width * scale;
|
const width = element.width * scale;
|
||||||
const height = element.height * scale;
|
const height = element.height * scale;
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
let font: { fontSize?: number; baseline?: number } = {};
|
let font: { fontSize?: number; baseline?: number } = {};
|
||||||
if (element.type === "text") {
|
|
||||||
|
if (boundTextElement) {
|
||||||
|
const nextFont = measureFontSizeFromWH(
|
||||||
|
boundTextElement,
|
||||||
|
width - BOUND_TEXT_PADDING * 2,
|
||||||
|
height - BOUND_TEXT_PADDING * 2,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (nextFont === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
font = {
|
||||||
|
fontSize: nextFont.size,
|
||||||
|
baseline: nextFont.baseline,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTextElement(element)) {
|
||||||
const nextFont = measureFontSizeFromWH(element, width, height);
|
const nextFont = measureFontSizeFromWH(element, width, height);
|
||||||
if (nextFont === null) {
|
if (nextFont === null) {
|
||||||
return null;
|
return null;
|
||||||
@@ -690,6 +764,15 @@ const resizeMultipleElements = (
|
|||||||
if (updates) {
|
if (updates) {
|
||||||
elements.forEach((element, index) => {
|
elements.forEach((element, index) => {
|
||||||
mutateElement(element, updates[index]);
|
mutateElement(element, updates[index]);
|
||||||
|
const boundTextElement = getBoundTextElement(element);
|
||||||
|
|
||||||
|
if (boundTextElement) {
|
||||||
|
mutateElement(boundTextElement, {
|
||||||
|
fontSize: updates[index].fontSize,
|
||||||
|
baseline: updates[index].baseline,
|
||||||
|
});
|
||||||
|
handleBindTextResize(element, transformHandleType);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -728,6 +811,16 @@ const rotateMultipleElements = (
|
|||||||
y: element.y + (rotatedCY - cy),
|
y: element.y + (rotatedCY - cy),
|
||||||
angle: normalizeAngle(centerAngle + origAngle),
|
angle: normalizeAngle(centerAngle + origAngle),
|
||||||
});
|
});
|
||||||
|
const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
if (boundTextElementId) {
|
||||||
|
const textElement =
|
||||||
|
Scene.getScene(element)!.getElement(boundTextElementId)!;
|
||||||
|
mutateElement(textElement, {
|
||||||
|
x: textElement.x + (rotatedCX - cx),
|
||||||
|
y: textElement.y + (rotatedCY - cy),
|
||||||
|
angle: normalizeAngle(centerAngle + origAngle),
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ describe("getPerfectElementSize", () => {
|
|||||||
expect(width).toEqual(135);
|
expect(width).toEqual(135);
|
||||||
expect(height).toEqual(135);
|
expect(height).toEqual(135);
|
||||||
});
|
});
|
||||||
it("should return height:0 and width:0 when width and heigh are 0", () => {
|
it("should return height:0 and width:0 when width and height are 0", () => {
|
||||||
const { height, width } = getPerfectElementSize("arrow", 0, 0);
|
const { height, width } = getPerfectElementSize("arrow", 0, 0);
|
||||||
expect(width).toEqual(0);
|
expect(width).toEqual(0);
|
||||||
expect(height).toEqual(0);
|
expect(height).toEqual(0);
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { wrapText } from "./textElement";
|
||||||
|
import { FontString } from "./types";
|
||||||
|
|
||||||
|
describe("Test wrapText", () => {
|
||||||
|
const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
|
||||||
|
|
||||||
|
describe("When text doesn't contain new lines", () => {
|
||||||
|
const text = "Hello whats up";
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "break all words when width of each word is less than container width",
|
||||||
|
width: 90,
|
||||||
|
res: `Hello
|
||||||
|
whats
|
||||||
|
up`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break all characters when width of each character is less than container width",
|
||||||
|
width: 25,
|
||||||
|
res: `H
|
||||||
|
e
|
||||||
|
l
|
||||||
|
l
|
||||||
|
o
|
||||||
|
w
|
||||||
|
h
|
||||||
|
a
|
||||||
|
t
|
||||||
|
s
|
||||||
|
u
|
||||||
|
p`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break words as per the width",
|
||||||
|
|
||||||
|
width: 150,
|
||||||
|
res: `Hello whats
|
||||||
|
up`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the container",
|
||||||
|
|
||||||
|
width: 250,
|
||||||
|
res: "Hello whats up",
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
describe("When text contain new lines", () => {
|
||||||
|
const text = `Hello
|
||||||
|
whats up`;
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "break all words when width of each word is less than container width",
|
||||||
|
width: 90,
|
||||||
|
res: `Hello
|
||||||
|
whats
|
||||||
|
up`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break all characters when width of each character is less than container width",
|
||||||
|
width: 25,
|
||||||
|
res: `H
|
||||||
|
e
|
||||||
|
l
|
||||||
|
l
|
||||||
|
o
|
||||||
|
w
|
||||||
|
h
|
||||||
|
a
|
||||||
|
t
|
||||||
|
s
|
||||||
|
u
|
||||||
|
p`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "break words as per the width",
|
||||||
|
|
||||||
|
width: 150,
|
||||||
|
res: `Hello
|
||||||
|
whats up`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the container",
|
||||||
|
|
||||||
|
width: 250,
|
||||||
|
res: `Hello
|
||||||
|
whats up`,
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should respect new lines and ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
describe("When text is long", () => {
|
||||||
|
const text = `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg break it now`;
|
||||||
|
[
|
||||||
|
{
|
||||||
|
desc: "fit characters of long string as per container width",
|
||||||
|
width: 170,
|
||||||
|
res: `hellolongtextth
|
||||||
|
isiswhatsupwith
|
||||||
|
youIamtypingggg
|
||||||
|
gandtypinggg
|
||||||
|
break it now`,
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
desc: "fit characters of long string as per container width and break words as per the width",
|
||||||
|
|
||||||
|
width: 130,
|
||||||
|
res: `hellolongte
|
||||||
|
xtthisiswha
|
||||||
|
tsupwithyou
|
||||||
|
Iamtypinggg
|
||||||
|
ggandtyping
|
||||||
|
gg break it
|
||||||
|
now`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
desc: "fit the long text when container width is greater than text length and move the rest to next line",
|
||||||
|
|
||||||
|
width: 600,
|
||||||
|
res: `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg
|
||||||
|
break it now`,
|
||||||
|
},
|
||||||
|
].forEach((data) => {
|
||||||
|
it(`should ${data.desc}`, () => {
|
||||||
|
const res = wrapText(text, font, data.width);
|
||||||
|
expect(res).toEqual(data.res);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
+470
-4
@@ -1,12 +1,478 @@
|
|||||||
import { measureText, getFontString } from "../utils";
|
import { getFontString, arrayToMap, isTestEnv } from "../utils";
|
||||||
import { ExcalidrawTextElement } from "./types";
|
import {
|
||||||
|
ExcalidrawElement,
|
||||||
|
ExcalidrawTextElement,
|
||||||
|
ExcalidrawTextElementWithContainer,
|
||||||
|
FontString,
|
||||||
|
NonDeletedExcalidrawElement,
|
||||||
|
} from "./types";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
|
import { BOUND_TEXT_PADDING, VERTICAL_ALIGN } from "../constants";
|
||||||
|
import { MaybeTransformHandleType } from "./transformHandles";
|
||||||
|
import Scene from "../scene/Scene";
|
||||||
|
import { AppState } from "../types";
|
||||||
|
import { isTextElement } from ".";
|
||||||
|
|
||||||
|
export const redrawTextBoundingBox = (
|
||||||
|
element: ExcalidrawTextElement,
|
||||||
|
container: ExcalidrawElement | null,
|
||||||
|
appState: AppState,
|
||||||
|
) => {
|
||||||
|
const maxWidth = container
|
||||||
|
? container.width - BOUND_TEXT_PADDING * 2
|
||||||
|
: undefined;
|
||||||
|
let text = element.text;
|
||||||
|
|
||||||
|
if (container) {
|
||||||
|
text = wrapText(
|
||||||
|
element.originalText,
|
||||||
|
getFontString(element),
|
||||||
|
container.width,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const metrics = measureText(
|
||||||
|
element.originalText,
|
||||||
|
getFontString(element),
|
||||||
|
maxWidth,
|
||||||
|
);
|
||||||
|
|
||||||
|
let coordY = element.y;
|
||||||
|
// Resize container and vertically center align the text
|
||||||
|
if (container) {
|
||||||
|
let nextHeight = container.height;
|
||||||
|
|
||||||
|
if (element.verticalAlign === VERTICAL_ALIGN.TOP) {
|
||||||
|
coordY = container.y + BOUND_TEXT_PADDING;
|
||||||
|
} else if (element.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
||||||
|
coordY =
|
||||||
|
container.y + container.height - metrics.height - BOUND_TEXT_PADDING;
|
||||||
|
} else {
|
||||||
|
coordY = container.y + container.height / 2 - metrics.height / 2;
|
||||||
|
if (metrics.height > container.height - BOUND_TEXT_PADDING * 2) {
|
||||||
|
nextHeight = metrics.height + BOUND_TEXT_PADDING * 2;
|
||||||
|
coordY = container.y + nextHeight / 2 - metrics.height / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mutateElement(container, { height: nextHeight });
|
||||||
|
}
|
||||||
|
|
||||||
export const redrawTextBoundingBox = (element: ExcalidrawTextElement) => {
|
|
||||||
const metrics = measureText(element.text, getFontString(element));
|
|
||||||
mutateElement(element, {
|
mutateElement(element, {
|
||||||
width: metrics.width,
|
width: metrics.width,
|
||||||
height: metrics.height,
|
height: metrics.height,
|
||||||
baseline: metrics.baseline,
|
baseline: metrics.baseline,
|
||||||
|
y: coordY,
|
||||||
|
text,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const bindTextToShapeAfterDuplication = (
|
||||||
|
sceneElements: ExcalidrawElement[],
|
||||||
|
oldElements: ExcalidrawElement[],
|
||||||
|
oldIdToDuplicatedId: Map<ExcalidrawElement["id"], ExcalidrawElement["id"]>,
|
||||||
|
): void => {
|
||||||
|
const sceneElementMap = arrayToMap(sceneElements) as Map<
|
||||||
|
ExcalidrawElement["id"],
|
||||||
|
ExcalidrawElement
|
||||||
|
>;
|
||||||
|
oldElements.forEach((element) => {
|
||||||
|
const newElementId = oldIdToDuplicatedId.get(element.id) as string;
|
||||||
|
const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
|
||||||
|
if (boundTextElementId) {
|
||||||
|
const newTextElementId = oldIdToDuplicatedId.get(boundTextElementId);
|
||||||
|
if (newTextElementId) {
|
||||||
|
const newContainer = sceneElementMap.get(newElementId);
|
||||||
|
if (newContainer) {
|
||||||
|
mutateElement(newContainer, {
|
||||||
|
boundElements: element.boundElements?.concat({
|
||||||
|
type: "text",
|
||||||
|
id: newTextElementId,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const newTextElement = sceneElementMap.get(newTextElementId);
|
||||||
|
if (newTextElement && isTextElement(newTextElement)) {
|
||||||
|
mutateElement(newTextElement, {
|
||||||
|
containerId: newContainer ? newElementId : null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const handleBindTextResize = (
|
||||||
|
element: NonDeletedExcalidrawElement,
|
||||||
|
transformHandleType: MaybeTransformHandleType,
|
||||||
|
) => {
|
||||||
|
const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
if (boundTextElementId) {
|
||||||
|
const textElement = Scene.getScene(element)!.getElement(
|
||||||
|
boundTextElementId,
|
||||||
|
) as ExcalidrawTextElement;
|
||||||
|
if (textElement && textElement.text) {
|
||||||
|
if (!element) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let text = textElement.text;
|
||||||
|
let nextHeight = textElement.height;
|
||||||
|
let containerHeight = element.height;
|
||||||
|
let nextBaseLine = textElement.baseline;
|
||||||
|
if (transformHandleType !== "n" && transformHandleType !== "s") {
|
||||||
|
if (text) {
|
||||||
|
text = wrapText(
|
||||||
|
textElement.originalText,
|
||||||
|
getFontString(textElement),
|
||||||
|
element.width,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const dimensions = measureText(
|
||||||
|
text,
|
||||||
|
getFontString(textElement),
|
||||||
|
element.width,
|
||||||
|
);
|
||||||
|
nextHeight = dimensions.height;
|
||||||
|
nextBaseLine = dimensions.baseline;
|
||||||
|
}
|
||||||
|
// increase height in case text element height exceeds
|
||||||
|
if (nextHeight > element.height - BOUND_TEXT_PADDING * 2) {
|
||||||
|
containerHeight = nextHeight + BOUND_TEXT_PADDING * 2;
|
||||||
|
const diff = containerHeight - element.height;
|
||||||
|
// fix the y coord when resizing from ne/nw/n
|
||||||
|
const updatedY =
|
||||||
|
transformHandleType === "ne" ||
|
||||||
|
transformHandleType === "nw" ||
|
||||||
|
transformHandleType === "n"
|
||||||
|
? element.y - diff
|
||||||
|
: element.y;
|
||||||
|
mutateElement(element, {
|
||||||
|
height: containerHeight,
|
||||||
|
y: updatedY,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let updatedY;
|
||||||
|
if (textElement.verticalAlign === VERTICAL_ALIGN.TOP) {
|
||||||
|
updatedY = element.y + BOUND_TEXT_PADDING;
|
||||||
|
} else if (textElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
||||||
|
updatedY = element.y + element.height - nextHeight - BOUND_TEXT_PADDING;
|
||||||
|
} else {
|
||||||
|
updatedY = element.y + element.height / 2 - nextHeight / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
mutateElement(textElement, {
|
||||||
|
text,
|
||||||
|
// preserve padding and set width correctly
|
||||||
|
width: element.width - BOUND_TEXT_PADDING * 2,
|
||||||
|
height: nextHeight,
|
||||||
|
x: element.x + BOUND_TEXT_PADDING,
|
||||||
|
y: updatedY,
|
||||||
|
baseline: nextBaseLine,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js
|
||||||
|
export const measureText = (
|
||||||
|
text: string,
|
||||||
|
font: FontString,
|
||||||
|
maxWidth?: number | null,
|
||||||
|
) => {
|
||||||
|
text = text
|
||||||
|
.split("\n")
|
||||||
|
// replace empty lines with single space because leading/trailing empty
|
||||||
|
// lines would be stripped from computation
|
||||||
|
.map((x) => x || " ")
|
||||||
|
.join("\n");
|
||||||
|
const container = document.createElement("div");
|
||||||
|
container.style.position = "absolute";
|
||||||
|
container.style.whiteSpace = "pre";
|
||||||
|
container.style.font = font;
|
||||||
|
container.style.minHeight = "1em";
|
||||||
|
if (maxWidth) {
|
||||||
|
const lineHeight = getApproxLineHeight(font);
|
||||||
|
container.style.width = `${String(maxWidth)}px`;
|
||||||
|
container.style.maxWidth = `${String(maxWidth)}px`;
|
||||||
|
container.style.overflow = "hidden";
|
||||||
|
container.style.wordBreak = "break-word";
|
||||||
|
container.style.lineHeight = `${String(lineHeight)}px`;
|
||||||
|
container.style.whiteSpace = "pre-wrap";
|
||||||
|
}
|
||||||
|
document.body.appendChild(container);
|
||||||
|
container.innerText = text;
|
||||||
|
|
||||||
|
const span = document.createElement("span");
|
||||||
|
span.style.display = "inline-block";
|
||||||
|
span.style.overflow = "hidden";
|
||||||
|
span.style.width = "1px";
|
||||||
|
span.style.height = "1px";
|
||||||
|
container.appendChild(span);
|
||||||
|
// Baseline is important for positioning text on canvas
|
||||||
|
const baseline = span.offsetTop + span.offsetHeight;
|
||||||
|
const width = container.offsetWidth;
|
||||||
|
|
||||||
|
const height = container.offsetHeight;
|
||||||
|
document.body.removeChild(container);
|
||||||
|
|
||||||
|
return { width, height, baseline };
|
||||||
|
};
|
||||||
|
|
||||||
|
const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
|
||||||
|
const cacheApproxLineHeight: { [key: FontString]: number } = {};
|
||||||
|
|
||||||
|
export const getApproxLineHeight = (font: FontString) => {
|
||||||
|
if (cacheApproxLineHeight[font]) {
|
||||||
|
return cacheApproxLineHeight[font];
|
||||||
|
}
|
||||||
|
cacheApproxLineHeight[font] = measureText(DUMMY_TEXT, font, null).height;
|
||||||
|
return cacheApproxLineHeight[font];
|
||||||
|
};
|
||||||
|
|
||||||
|
let canvas: HTMLCanvasElement | undefined;
|
||||||
|
const getTextWidth = (text: string, font: FontString) => {
|
||||||
|
if (!canvas) {
|
||||||
|
canvas = document.createElement("canvas");
|
||||||
|
}
|
||||||
|
const canvas2dContext = canvas.getContext("2d")!;
|
||||||
|
canvas2dContext.font = font;
|
||||||
|
|
||||||
|
const metrics = canvas2dContext.measureText(text);
|
||||||
|
// since in test env the canvas measureText algo
|
||||||
|
// doesn't measure text and instead just returns number of
|
||||||
|
// characters hence we assume that each letteris 10px
|
||||||
|
if (isTestEnv()) {
|
||||||
|
return metrics.width * 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
return metrics.width;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const wrapText = (
|
||||||
|
text: string,
|
||||||
|
font: FontString,
|
||||||
|
containerWidth: number,
|
||||||
|
) => {
|
||||||
|
const maxWidth = containerWidth - BOUND_TEXT_PADDING * 2;
|
||||||
|
|
||||||
|
const lines: Array<string> = [];
|
||||||
|
const originalLines = text.split("\n");
|
||||||
|
const spaceWidth = getTextWidth(" ", font);
|
||||||
|
originalLines.forEach((originalLine) => {
|
||||||
|
const words = originalLine.split(" ");
|
||||||
|
// This means its newline so push it
|
||||||
|
if (words.length === 1 && words[0] === "") {
|
||||||
|
lines.push(words[0]);
|
||||||
|
} else {
|
||||||
|
let currentLine = "";
|
||||||
|
let currentLineWidthTillNow = 0;
|
||||||
|
|
||||||
|
let index = 0;
|
||||||
|
while (index < words.length) {
|
||||||
|
const currentWordWidth = getTextWidth(words[index], font);
|
||||||
|
|
||||||
|
// Start breaking longer words exceeding max width
|
||||||
|
if (currentWordWidth >= maxWidth) {
|
||||||
|
// push current line since the current word exceeds the max width
|
||||||
|
// so will be appended in next line
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
}
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
while (words[index].length > 0) {
|
||||||
|
const currentChar = words[index][0];
|
||||||
|
const width = charWidth.calculate(currentChar, font);
|
||||||
|
currentLineWidthTillNow += width;
|
||||||
|
words[index] = words[index].slice(1);
|
||||||
|
|
||||||
|
if (currentLineWidthTillNow >= maxWidth) {
|
||||||
|
// only remove last trailing space which we have added when joining words
|
||||||
|
if (currentLine.slice(-1) === " ") {
|
||||||
|
currentLine = currentLine.slice(0, -1);
|
||||||
|
}
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLine = currentChar;
|
||||||
|
currentLineWidthTillNow = width;
|
||||||
|
if (currentLineWidthTillNow === maxWidth) {
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentLine += currentChar;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// push current line if appending space exceeds max width
|
||||||
|
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
} else {
|
||||||
|
// space needs to be appended before next word
|
||||||
|
// as currentLine contains chars which couldn't be appended
|
||||||
|
// to previous line
|
||||||
|
currentLine += " ";
|
||||||
|
currentLineWidthTillNow += spaceWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
index++;
|
||||||
|
} else {
|
||||||
|
// Start appending words in a line till max width reached
|
||||||
|
while (currentLineWidthTillNow < maxWidth && index < words.length) {
|
||||||
|
const word = words[index];
|
||||||
|
currentLineWidthTillNow = getTextWidth(currentLine + word, font);
|
||||||
|
|
||||||
|
if (currentLineWidthTillNow >= maxWidth) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
currentLine = "";
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
currentLine += `${word} `;
|
||||||
|
|
||||||
|
// Push the word if appending space exceeds max width
|
||||||
|
if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
|
||||||
|
lines.push(currentLine.slice(0, -1));
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentLineWidthTillNow === maxWidth) {
|
||||||
|
currentLine = "";
|
||||||
|
currentLineWidthTillNow = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentLine) {
|
||||||
|
// only remove last trailing space which we have added when joining words
|
||||||
|
if (currentLine.slice(-1) === " ") {
|
||||||
|
currentLine = currentLine.slice(0, -1);
|
||||||
|
}
|
||||||
|
lines.push(currentLine);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return lines.join("\n");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const charWidth = (() => {
|
||||||
|
const cachedCharWidth: { [key: FontString]: Array<number> } = {};
|
||||||
|
|
||||||
|
const calculate = (char: string, font: FontString) => {
|
||||||
|
const ascii = char.charCodeAt(0);
|
||||||
|
if (!cachedCharWidth[font]) {
|
||||||
|
cachedCharWidth[font] = [];
|
||||||
|
}
|
||||||
|
if (!cachedCharWidth[font][ascii]) {
|
||||||
|
const width = getTextWidth(char, font);
|
||||||
|
cachedCharWidth[font][ascii] = width;
|
||||||
|
}
|
||||||
|
|
||||||
|
return cachedCharWidth[font][ascii];
|
||||||
|
};
|
||||||
|
|
||||||
|
const getCache = (font: FontString) => {
|
||||||
|
return cachedCharWidth[font];
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
calculate,
|
||||||
|
getCache,
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
export const getApproxMinLineWidth = (font: FontString) => {
|
||||||
|
const maxCharWidth = getMaxCharWidth(font);
|
||||||
|
if (maxCharWidth === 0) {
|
||||||
|
return (
|
||||||
|
measureText(DUMMY_TEXT.split("").join("\n"), font).width +
|
||||||
|
BOUND_TEXT_PADDING * 2
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return maxCharWidth + BOUND_TEXT_PADDING * 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getApproxMinLineHeight = (font: FontString) => {
|
||||||
|
return getApproxLineHeight(font) + BOUND_TEXT_PADDING * 2;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMinCharWidth = (font: FontString) => {
|
||||||
|
const cache = charWidth.getCache(font);
|
||||||
|
if (!cache) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const cacheWithOutEmpty = cache.filter((val) => val !== undefined);
|
||||||
|
|
||||||
|
return Math.min(...cacheWithOutEmpty);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMaxCharWidth = (font: FontString) => {
|
||||||
|
const cache = charWidth.getCache(font);
|
||||||
|
if (!cache) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const cacheWithOutEmpty = cache.filter((val) => val !== undefined);
|
||||||
|
return Math.max(...cacheWithOutEmpty);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getApproxCharsToFitInWidth = (font: FontString, width: number) => {
|
||||||
|
// Generally lower case is used so converting to lower case
|
||||||
|
const dummyText = DUMMY_TEXT.toLocaleLowerCase();
|
||||||
|
const batchLength = 6;
|
||||||
|
let index = 0;
|
||||||
|
let widthTillNow = 0;
|
||||||
|
let str = "";
|
||||||
|
while (widthTillNow <= width) {
|
||||||
|
const batch = dummyText.substr(index, index + batchLength);
|
||||||
|
str += batch;
|
||||||
|
widthTillNow += getTextWidth(str, font);
|
||||||
|
if (index === dummyText.length - 1) {
|
||||||
|
index = 0;
|
||||||
|
}
|
||||||
|
index = index + batchLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (widthTillNow > width) {
|
||||||
|
str = str.substr(0, str.length - 1);
|
||||||
|
widthTillNow = getTextWidth(str, font);
|
||||||
|
}
|
||||||
|
return str.length;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getBoundTextElementId = (container: ExcalidrawElement | null) => {
|
||||||
|
return container?.boundElements?.length
|
||||||
|
? container?.boundElements?.filter((ele) => ele.type === "text")[0]?.id ||
|
||||||
|
null
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getBoundTextElement = (element: ExcalidrawElement | null) => {
|
||||||
|
if (!element) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
if (boundTextElementId) {
|
||||||
|
return (
|
||||||
|
(Scene.getScene(element)?.getElement(
|
||||||
|
boundTextElementId,
|
||||||
|
) as ExcalidrawTextElementWithContainer) || null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getContainerElement = (
|
||||||
|
element:
|
||||||
|
| (ExcalidrawElement & { containerId: ExcalidrawElement["id"] | null })
|
||||||
|
| null,
|
||||||
|
) => {
|
||||||
|
if (!element) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (element.containerId) {
|
||||||
|
return Scene.getScene(element)?.getElement(element.containerId) || null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|||||||
+716
-136
@@ -1,169 +1,749 @@
|
|||||||
import ReactDOM from "react-dom";
|
import ReactDOM from "react-dom";
|
||||||
import ExcalidrawApp from "../excalidraw-app";
|
import ExcalidrawApp from "../excalidraw-app";
|
||||||
import { render } from "../tests/test-utils";
|
import { GlobalTestState, render, screen } from "../tests/test-utils";
|
||||||
import { Pointer, UI } from "../tests/helpers/ui";
|
import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
|
||||||
import { KEYS } from "../keys";
|
import { CODES, KEYS } from "../keys";
|
||||||
|
import { fireEvent } from "../tests/test-utils";
|
||||||
|
import { queryByText } from "@testing-library/react";
|
||||||
|
|
||||||
|
import { BOUND_TEXT_PADDING, FONT_FAMILY } from "../constants";
|
||||||
|
import {
|
||||||
|
ExcalidrawTextElement,
|
||||||
|
ExcalidrawTextElementWithContainer,
|
||||||
|
} from "./types";
|
||||||
|
import * as textElementUtils from "./textElement";
|
||||||
|
import { API } from "../tests/helpers/api";
|
||||||
|
import { mutateElement } from "./mutateElement";
|
||||||
// Unmount ReactDOM from root
|
// Unmount ReactDOM from root
|
||||||
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
|
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
|
||||||
|
|
||||||
const tab = " ";
|
const tab = " ";
|
||||||
|
const mouse = new Pointer("mouse");
|
||||||
|
|
||||||
describe("textWysiwyg", () => {
|
describe("textWysiwyg", () => {
|
||||||
let textarea: HTMLTextAreaElement;
|
describe("start text editing", () => {
|
||||||
beforeEach(async () => {
|
const { h } = window;
|
||||||
await render(<ExcalidrawApp />);
|
beforeEach(async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
const element = UI.createElement("text");
|
h.elements = [];
|
||||||
|
|
||||||
new Pointer("mouse").clickOn(element);
|
|
||||||
textarea = document.querySelector(
|
|
||||||
".excalidraw-textEditorContainer > textarea",
|
|
||||||
)!;
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should add a tab at the start of the first line", () => {
|
|
||||||
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
|
||||||
textarea.value = "Line#1\nLine#2";
|
|
||||||
// cursor: "|Line#1\nLine#2"
|
|
||||||
textarea.selectionStart = 0;
|
|
||||||
textarea.selectionEnd = 0;
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
|
|
||||||
// cursor: " |Line#1\nLine#2"
|
|
||||||
expect(textarea.selectionStart).toEqual(4);
|
|
||||||
expect(textarea.selectionEnd).toEqual(4);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should add a tab at the start of the second line", () => {
|
|
||||||
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
|
||||||
textarea.value = "Line#1\nLine#2";
|
|
||||||
// cursor: "Line#1\nLin|e#2"
|
|
||||||
textarea.selectionStart = 10;
|
|
||||||
textarea.selectionEnd = 10;
|
|
||||||
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
|
|
||||||
|
|
||||||
// cursor: "Line#1\n Lin|e#2"
|
|
||||||
expect(textarea.selectionStart).toEqual(14);
|
|
||||||
expect(textarea.selectionEnd).toEqual(14);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should add a tab at the start of the first and second line", () => {
|
|
||||||
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
|
||||||
textarea.value = "Line#1\nLine#2\nLine#3";
|
|
||||||
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
|
|
||||||
textarea.selectionStart = 2;
|
|
||||||
textarea.selectionEnd = 9;
|
|
||||||
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
|
|
||||||
|
|
||||||
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
|
|
||||||
expect(textarea.selectionStart).toEqual(6);
|
|
||||||
expect(textarea.selectionEnd).toEqual(17);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should remove a tab at the start of the first line", () => {
|
|
||||||
const event = new KeyboardEvent("keydown", {
|
|
||||||
key: KEYS.TAB,
|
|
||||||
shiftKey: true,
|
|
||||||
});
|
});
|
||||||
textarea.value = `${tab}Line#1\nLine#2`;
|
|
||||||
// cursor: "| Line#1\nLine#2"
|
|
||||||
textarea.selectionStart = 0;
|
|
||||||
textarea.selectionEnd = 0;
|
|
||||||
|
|
||||||
textarea.dispatchEvent(event);
|
it("should prefer editing selected text element (non-bindable container present)", async () => {
|
||||||
|
const line = API.createElement({
|
||||||
|
type: "line",
|
||||||
|
width: 100,
|
||||||
|
height: 0,
|
||||||
|
points: [
|
||||||
|
[0, 0],
|
||||||
|
[100, 0],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const textSize = 20;
|
||||||
|
const text = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: line.width / 2 - textSize / 2,
|
||||||
|
y: -textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
});
|
||||||
|
h.elements = [text, line];
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
API.setSelectedElements([text]);
|
||||||
|
|
||||||
// cursor: "|Line#1\nLine#2"
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
expect(textarea.selectionStart).toEqual(0);
|
|
||||||
expect(textarea.selectionEnd).toEqual(0);
|
expect(h.state.editingElement?.id).toBe(text.id);
|
||||||
|
expect(
|
||||||
|
(h.state.editingElement as ExcalidrawTextElement).containerId,
|
||||||
|
).toBe(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should prefer editing selected text element (bindable container present)", async () => {
|
||||||
|
const container = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
width: 100,
|
||||||
|
boundElements: [],
|
||||||
|
});
|
||||||
|
const textSize = 20;
|
||||||
|
|
||||||
|
const boundText = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: container.width / 2 - textSize / 2,
|
||||||
|
y: container.height / 2 - textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
containerId: container.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const boundText2 = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: container.width / 2 - textSize / 2,
|
||||||
|
y: container.height / 2 - textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
containerId: container.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.elements = [container, boundText, boundText2];
|
||||||
|
|
||||||
|
mutateElement(container, {
|
||||||
|
boundElements: [{ type: "text", id: boundText.id }],
|
||||||
|
});
|
||||||
|
|
||||||
|
API.setSelectedElements([boundText2]);
|
||||||
|
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
|
||||||
|
expect(h.state.editingElement?.id).toBe(boundText2.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should not create bound text on ENTER if text exists at container center", () => {
|
||||||
|
const container = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
width: 100,
|
||||||
|
});
|
||||||
|
const textSize = 20;
|
||||||
|
const text = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: container.width / 2 - textSize / 2,
|
||||||
|
y: container.height / 2 - textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
containerId: container.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.elements = [container, text];
|
||||||
|
|
||||||
|
API.setSelectedElements([container]);
|
||||||
|
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
|
||||||
|
expect(h.state.editingElement?.id).toBe(text.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should edit existing bound text on ENTER even if higher z-index unbound text exists at container center", () => {
|
||||||
|
const container = API.createElement({
|
||||||
|
type: "rectangle",
|
||||||
|
width: 100,
|
||||||
|
boundElements: [],
|
||||||
|
});
|
||||||
|
const textSize = 20;
|
||||||
|
|
||||||
|
const boundText = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: container.width / 2 - textSize / 2,
|
||||||
|
y: container.height / 2 - textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
containerId: container.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const boundText2 = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: container.width / 2 - textSize / 2,
|
||||||
|
y: container.height / 2 - textSize / 2,
|
||||||
|
width: textSize,
|
||||||
|
height: textSize,
|
||||||
|
containerId: container.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.elements = [container, boundText, boundText2];
|
||||||
|
|
||||||
|
mutateElement(container, {
|
||||||
|
boundElements: [{ type: "text", id: boundText.id }],
|
||||||
|
});
|
||||||
|
|
||||||
|
API.setSelectedElements([container]);
|
||||||
|
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
|
||||||
|
expect(h.state.editingElement?.id).toBe(boundText.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should edit text under cursor when clicked with text tool", () => {
|
||||||
|
const text = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: 60,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.elements = [text];
|
||||||
|
UI.clickTool("text");
|
||||||
|
|
||||||
|
mouse.clickAt(text.x + 50, text.y + 50);
|
||||||
|
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
expect(editor).not.toBe(null);
|
||||||
|
expect(h.state.editingElement?.id).toBe(text.id);
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should edit text under cursor when double-clicked with selection tool", () => {
|
||||||
|
const text = API.createElement({
|
||||||
|
type: "text",
|
||||||
|
text: "ola",
|
||||||
|
x: 60,
|
||||||
|
y: 0,
|
||||||
|
width: 100,
|
||||||
|
height: 100,
|
||||||
|
});
|
||||||
|
|
||||||
|
h.elements = [text];
|
||||||
|
UI.clickTool("selection");
|
||||||
|
|
||||||
|
mouse.doubleClickAt(text.x + 50, text.y + 50);
|
||||||
|
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
expect(editor).not.toBe(null);
|
||||||
|
expect(h.state.editingElement?.id).toBe(text.id);
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should remove a tab at the start of the second line", () => {
|
describe("Test container-unbound text", () => {
|
||||||
const event = new KeyboardEvent("keydown", {
|
const { h } = window;
|
||||||
key: KEYS.TAB,
|
|
||||||
shiftKey: true,
|
let textarea: HTMLTextAreaElement;
|
||||||
|
let textElement: ExcalidrawTextElement;
|
||||||
|
beforeEach(async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
|
||||||
|
textElement = UI.createElement("text");
|
||||||
|
|
||||||
|
mouse.clickOn(textElement);
|
||||||
|
textarea = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
)!;
|
||||||
});
|
});
|
||||||
// cursor: "Line#1\n Lin|e#2"
|
|
||||||
textarea.value = `Line#1\n${tab}Line#2`;
|
|
||||||
textarea.selectionStart = 15;
|
|
||||||
textarea.selectionEnd = 15;
|
|
||||||
|
|
||||||
textarea.dispatchEvent(event);
|
it("should add a tab at the start of the first line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
||||||
|
textarea.value = "Line#1\nLine#2";
|
||||||
|
// cursor: "|Line#1\nLine#2"
|
||||||
|
textarea.selectionStart = 0;
|
||||||
|
textarea.selectionEnd = 0;
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
expect(textarea.value).toEqual(`${tab}Line#1\nLine#2`);
|
||||||
// cursor: "Line#1\nLin|e#2"
|
// cursor: " |Line#1\nLine#2"
|
||||||
expect(textarea.selectionStart).toEqual(11);
|
expect(textarea.selectionStart).toEqual(4);
|
||||||
expect(textarea.selectionEnd).toEqual(11);
|
expect(textarea.selectionEnd).toEqual(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should add a tab at the start of the second line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
||||||
|
textarea.value = "Line#1\nLine#2";
|
||||||
|
// cursor: "Line#1\nLin|e#2"
|
||||||
|
textarea.selectionStart = 10;
|
||||||
|
textarea.selectionEnd = 10;
|
||||||
|
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\n${tab}Line#2`);
|
||||||
|
|
||||||
|
// cursor: "Line#1\n Lin|e#2"
|
||||||
|
expect(textarea.selectionStart).toEqual(14);
|
||||||
|
expect(textarea.selectionEnd).toEqual(14);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should add a tab at the start of the first and second line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
|
||||||
|
textarea.value = "Line#1\nLine#2\nLine#3";
|
||||||
|
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
|
||||||
|
textarea.selectionStart = 2;
|
||||||
|
textarea.selectionEnd = 9;
|
||||||
|
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`${tab}Line#1\n${tab}Line#2\nLine#3`);
|
||||||
|
|
||||||
|
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
|
||||||
|
expect(textarea.selectionStart).toEqual(6);
|
||||||
|
expect(textarea.selectionEnd).toEqual(17);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove a tab at the start of the first line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
textarea.value = `${tab}Line#1\nLine#2`;
|
||||||
|
// cursor: "| Line#1\nLine#2"
|
||||||
|
textarea.selectionStart = 0;
|
||||||
|
textarea.selectionEnd = 0;
|
||||||
|
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
||||||
|
|
||||||
|
// cursor: "|Line#1\nLine#2"
|
||||||
|
expect(textarea.selectionStart).toEqual(0);
|
||||||
|
expect(textarea.selectionEnd).toEqual(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove a tab at the start of the second line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
// cursor: "Line#1\n Lin|e#2"
|
||||||
|
textarea.value = `Line#1\n${tab}Line#2`;
|
||||||
|
textarea.selectionStart = 15;
|
||||||
|
textarea.selectionEnd = 15;
|
||||||
|
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
||||||
|
// cursor: "Line#1\nLin|e#2"
|
||||||
|
expect(textarea.selectionStart).toEqual(11);
|
||||||
|
expect(textarea.selectionEnd).toEqual(11);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove a tab at the start of the first and second line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
|
||||||
|
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
|
||||||
|
textarea.selectionStart = 6;
|
||||||
|
textarea.selectionEnd = 17;
|
||||||
|
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
|
||||||
|
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
|
||||||
|
expect(textarea.selectionStart).toEqual(2);
|
||||||
|
expect(textarea.selectionEnd).toEqual(9);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
// cursor: "Line#1\n | Line#2"
|
||||||
|
textarea.value = `Line#1\n${tab}Line#2`;
|
||||||
|
textarea.selectionStart = 9;
|
||||||
|
textarea.selectionEnd = 9;
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
// cursor: "Line#1\n|Line#2"
|
||||||
|
expect(textarea.selectionStart).toEqual(7);
|
||||||
|
// expect(textarea.selectionEnd).toEqual(7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove partial tabs", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
// cursor: "Line#1\n Line#|2"
|
||||||
|
textarea.value = `Line#1\n Line#2`;
|
||||||
|
textarea.selectionStart = 15;
|
||||||
|
textarea.selectionEnd = 15;
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should remove nothing", () => {
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.TAB,
|
||||||
|
shiftKey: true,
|
||||||
|
});
|
||||||
|
// cursor: "Line#1\n Li|ne#2"
|
||||||
|
textarea.value = `Line#1\nLine#2`;
|
||||||
|
textarea.selectionStart = 9;
|
||||||
|
textarea.selectionEnd = 9;
|
||||||
|
textarea.dispatchEvent(event);
|
||||||
|
|
||||||
|
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should resize text via shortcuts while in wysiwyg", () => {
|
||||||
|
textarea.value = "abc def";
|
||||||
|
const origFontSize = textElement.fontSize;
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.CHEVRON_RIGHT,
|
||||||
|
ctrlKey: true,
|
||||||
|
shiftKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(textElement.fontSize).toBe(origFontSize * 1.1);
|
||||||
|
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
key: KEYS.CHEVRON_LEFT,
|
||||||
|
ctrlKey: true,
|
||||||
|
shiftKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(textElement.fontSize).toBe(origFontSize);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("zooming via keyboard should zoom canvas", () => {
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
code: CODES.MINUS,
|
||||||
|
ctrlKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(h.state.zoom.value).toBe(0.9);
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
code: CODES.NUM_SUBTRACT,
|
||||||
|
ctrlKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(h.state.zoom.value).toBe(0.8);
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
code: CODES.NUM_ADD,
|
||||||
|
ctrlKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(h.state.zoom.value).toBe(0.9);
|
||||||
|
textarea.dispatchEvent(
|
||||||
|
new KeyboardEvent("keydown", {
|
||||||
|
code: CODES.EQUAL,
|
||||||
|
ctrlKey: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(h.state.zoom.value).toBe(1);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should remove a tab at the start of the first and second line", () => {
|
describe("Test container-bound text", () => {
|
||||||
const event = new KeyboardEvent("keydown", {
|
let rectangle: any;
|
||||||
key: KEYS.TAB,
|
const { h } = window;
|
||||||
shiftKey: true,
|
|
||||||
|
const DUMMY_HEIGHT = 240;
|
||||||
|
const DUMMY_WIDTH = 160;
|
||||||
|
const APPROX_LINE_HEIGHT = 25;
|
||||||
|
const INITIAL_WIDTH = 10;
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
jest
|
||||||
|
.spyOn(textElementUtils, "getApproxLineHeight")
|
||||||
|
.mockReturnValue(APPROX_LINE_HEIGHT);
|
||||||
});
|
});
|
||||||
// cursor: " Li|ne#1\n Li|ne#2\nLine#3"
|
|
||||||
textarea.value = `${tab}Line#1\n${tab}Line#2\nLine#3`;
|
|
||||||
textarea.selectionStart = 6;
|
|
||||||
textarea.selectionEnd = 17;
|
|
||||||
|
|
||||||
textarea.dispatchEvent(event);
|
beforeEach(async () => {
|
||||||
|
await render(<ExcalidrawApp />);
|
||||||
|
h.elements = [];
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\nLine#2\nLine#3`);
|
rectangle = UI.createElement("rectangle", {
|
||||||
// cursor: "Li|ne#1\nLi|ne#2\nLine#3"
|
x: 10,
|
||||||
expect(textarea.selectionStart).toEqual(2);
|
y: 20,
|
||||||
expect(textarea.selectionEnd).toEqual(9);
|
width: 90,
|
||||||
});
|
height: 75,
|
||||||
|
});
|
||||||
it("should remove a tab at the start of the second line and cursor stay on this line", () => {
|
|
||||||
const event = new KeyboardEvent("keydown", {
|
|
||||||
key: KEYS.TAB,
|
|
||||||
shiftKey: true,
|
|
||||||
});
|
});
|
||||||
// cursor: "Line#1\n | Line#2"
|
|
||||||
textarea.value = `Line#1\n${tab}Line#2`;
|
|
||||||
textarea.selectionStart = 9;
|
|
||||||
textarea.selectionEnd = 9;
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
// cursor: "Line#1\n|Line#2"
|
it("should bind text to container when double clicked on center", async () => {
|
||||||
expect(textarea.selectionStart).toEqual(7);
|
expect(h.elements.length).toBe(1);
|
||||||
// expect(textarea.selectionEnd).toEqual(7);
|
expect(h.elements[0].id).toBe(rectangle.id);
|
||||||
});
|
|
||||||
|
|
||||||
it("should remove partial tabs", () => {
|
mouse.doubleClickAt(
|
||||||
const event = new KeyboardEvent("keydown", {
|
rectangle.x + rectangle.width / 2,
|
||||||
key: KEYS.TAB,
|
rectangle.y + rectangle.height / 2,
|
||||||
shiftKey: true,
|
);
|
||||||
|
expect(h.elements.length).toBe(2);
|
||||||
|
|
||||||
|
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
expect(text.type).toBe("text");
|
||||||
|
expect(text.containerId).toBe(rectangle.id);
|
||||||
|
mouse.down();
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
fireEvent.change(editor, { target: { value: "Hello World!" } });
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
editor.blur();
|
||||||
|
expect(rectangle.boundElements).toStrictEqual([
|
||||||
|
{ id: text.id, type: "text" },
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
// cursor: "Line#1\n Line#|2"
|
|
||||||
textarea.value = `Line#1\n Line#2`;
|
|
||||||
textarea.selectionStart = 15;
|
|
||||||
textarea.selectionEnd = 15;
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
it("should bind text to container when clicked on container and enter pressed", async () => {
|
||||||
});
|
expect(h.elements.length).toBe(1);
|
||||||
|
expect(h.elements[0].id).toBe(rectangle.id);
|
||||||
|
|
||||||
it("should remove nothing", () => {
|
Keyboard.withModifierKeys({}, () => {
|
||||||
const event = new KeyboardEvent("keydown", {
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
key: KEYS.TAB,
|
});
|
||||||
shiftKey: true,
|
|
||||||
|
expect(h.elements.length).toBe(2);
|
||||||
|
|
||||||
|
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
expect(text.type).toBe("text");
|
||||||
|
expect(text.containerId).toBe(rectangle.id);
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
|
||||||
|
fireEvent.change(editor, { target: { value: "Hello World!" } });
|
||||||
|
editor.blur();
|
||||||
|
expect(rectangle.boundElements).toStrictEqual([
|
||||||
|
{ id: text.id, type: "text" },
|
||||||
|
]);
|
||||||
});
|
});
|
||||||
// cursor: "Line#1\n Li|ne#2"
|
|
||||||
textarea.value = `Line#1\nLine#2`;
|
|
||||||
textarea.selectionStart = 9;
|
|
||||||
textarea.selectionEnd = 9;
|
|
||||||
textarea.dispatchEvent(event);
|
|
||||||
|
|
||||||
expect(textarea.value).toEqual(`Line#1\nLine#2`);
|
it("shouldn't bind to non-text-bindable containers", async () => {
|
||||||
|
const line = API.createElement({
|
||||||
|
type: "line",
|
||||||
|
width: 100,
|
||||||
|
height: 0,
|
||||||
|
points: [
|
||||||
|
[0, 0],
|
||||||
|
[100, 0],
|
||||||
|
],
|
||||||
|
});
|
||||||
|
h.elements = [line];
|
||||||
|
|
||||||
|
UI.clickTool("text");
|
||||||
|
|
||||||
|
mouse.clickAt(line.x + line.width / 2, line.y + line.height / 2);
|
||||||
|
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
fireEvent.change(editor, {
|
||||||
|
target: {
|
||||||
|
value: "Hello World!",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
fireEvent.keyDown(editor, { key: KEYS.ESCAPE });
|
||||||
|
editor.dispatchEvent(new Event("input"));
|
||||||
|
|
||||||
|
expect(line.boundElements).toBe(null);
|
||||||
|
expect(h.elements[1].type).toBe("text");
|
||||||
|
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
|
||||||
|
mouse.doubleClickAt(
|
||||||
|
rectangle.x + rectangle.width / 2,
|
||||||
|
rectangle.y + rectangle.height / 2,
|
||||||
|
);
|
||||||
|
mouse.down();
|
||||||
|
|
||||||
|
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
let editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
fireEvent.change(editor, { target: { value: "Hello World!" } });
|
||||||
|
editor.blur();
|
||||||
|
expect(text.fontFamily).toEqual(FONT_FAMILY.Virgil);
|
||||||
|
UI.clickTool("text");
|
||||||
|
|
||||||
|
mouse.clickAt(
|
||||||
|
rectangle.x + rectangle.width / 2,
|
||||||
|
rectangle.y + rectangle.height / 2,
|
||||||
|
);
|
||||||
|
mouse.down();
|
||||||
|
editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
editor.select();
|
||||||
|
fireEvent.click(screen.getByTitle(/code/i));
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
editor.blur();
|
||||||
|
expect(
|
||||||
|
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
|
||||||
|
).toEqual(FONT_FAMILY.Cascadia);
|
||||||
|
|
||||||
|
//undo
|
||||||
|
Keyboard.withModifierKeys({ ctrl: true }, () => {
|
||||||
|
Keyboard.keyPress(KEYS.Z);
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
|
||||||
|
).toEqual(FONT_FAMILY.Virgil);
|
||||||
|
|
||||||
|
//redo
|
||||||
|
Keyboard.withModifierKeys({ ctrl: true, shift: true }, () => {
|
||||||
|
Keyboard.keyPress(KEYS.Z);
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
|
||||||
|
).toEqual(FONT_FAMILY.Cascadia);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should wrap text and vertcially center align once text submitted", async () => {
|
||||||
|
jest
|
||||||
|
.spyOn(textElementUtils, "measureText")
|
||||||
|
.mockImplementation((text, font, maxWidth) => {
|
||||||
|
let width = INITIAL_WIDTH;
|
||||||
|
let height = APPROX_LINE_HEIGHT;
|
||||||
|
let baseline = 10;
|
||||||
|
if (!text) {
|
||||||
|
return {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
baseline,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
baseline = 30;
|
||||||
|
width = DUMMY_WIDTH;
|
||||||
|
if (text === "Hello \nWorld!") {
|
||||||
|
height = APPROX_LINE_HEIGHT * 2;
|
||||||
|
}
|
||||||
|
if (maxWidth) {
|
||||||
|
width = maxWidth;
|
||||||
|
// To capture cases where maxWidth passed is initial width
|
||||||
|
// due to which the text is not wrapped correctly
|
||||||
|
if (maxWidth === INITIAL_WIDTH) {
|
||||||
|
height = DUMMY_HEIGHT;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
baseline,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
|
||||||
|
Keyboard.keyDown(KEYS.ENTER);
|
||||||
|
let text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
let editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
// mock scroll height
|
||||||
|
jest
|
||||||
|
.spyOn(editor, "scrollHeight", "get")
|
||||||
|
.mockImplementation(() => APPROX_LINE_HEIGHT * 2);
|
||||||
|
|
||||||
|
fireEvent.change(editor, {
|
||||||
|
target: {
|
||||||
|
value: "Hello World!",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
editor.dispatchEvent(new Event("input"));
|
||||||
|
|
||||||
|
await new Promise((cb) => setTimeout(cb, 0));
|
||||||
|
editor.blur();
|
||||||
|
text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
expect(text.text).toBe("Hello \nWorld!");
|
||||||
|
expect(text.originalText).toBe("Hello World!");
|
||||||
|
expect(text.y).toBe(
|
||||||
|
rectangle.y + rectangle.height / 2 - (APPROX_LINE_HEIGHT * 2) / 2,
|
||||||
|
);
|
||||||
|
expect(text.x).toBe(rectangle.x + BOUND_TEXT_PADDING);
|
||||||
|
expect(text.height).toBe(APPROX_LINE_HEIGHT * 2);
|
||||||
|
expect(text.width).toBe(rectangle.width - BOUND_TEXT_PADDING * 2);
|
||||||
|
|
||||||
|
// Edit and text by removing second line and it should
|
||||||
|
// still vertically align correctly
|
||||||
|
mouse.select(rectangle);
|
||||||
|
Keyboard.withModifierKeys({}, () => {
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
});
|
||||||
|
editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
fireEvent.change(editor, {
|
||||||
|
target: {
|
||||||
|
value: "Hello",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// mock scroll height
|
||||||
|
jest
|
||||||
|
.spyOn(editor, "scrollHeight", "get")
|
||||||
|
.mockImplementation(() => APPROX_LINE_HEIGHT);
|
||||||
|
editor.style.height = "25px";
|
||||||
|
editor.dispatchEvent(new Event("input"));
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
|
||||||
|
editor.blur();
|
||||||
|
text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
|
||||||
|
expect(text.text).toBe("Hello");
|
||||||
|
expect(text.originalText).toBe("Hello");
|
||||||
|
expect(text.y).toBe(
|
||||||
|
rectangle.y + rectangle.height / 2 - APPROX_LINE_HEIGHT / 2,
|
||||||
|
);
|
||||||
|
expect(text.x).toBe(rectangle.x + BOUND_TEXT_PADDING);
|
||||||
|
expect(text.height).toBe(APPROX_LINE_HEIGHT);
|
||||||
|
expect(text.width).toBe(rectangle.width - BOUND_TEXT_PADDING * 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should unbind bound text when unbind action from context menu is triggred", async () => {
|
||||||
|
expect(h.elements.length).toBe(1);
|
||||||
|
expect(h.elements[0].id).toBe(rectangle.id);
|
||||||
|
|
||||||
|
Keyboard.withModifierKeys({}, () => {
|
||||||
|
Keyboard.keyPress(KEYS.ENTER);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(h.elements.length).toBe(2);
|
||||||
|
|
||||||
|
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
|
||||||
|
expect(text.containerId).toBe(rectangle.id);
|
||||||
|
|
||||||
|
const editor = document.querySelector(
|
||||||
|
".excalidraw-textEditorContainer > textarea",
|
||||||
|
) as HTMLTextAreaElement;
|
||||||
|
|
||||||
|
await new Promise((r) => setTimeout(r, 0));
|
||||||
|
|
||||||
|
fireEvent.change(editor, { target: { value: "Hello World!" } });
|
||||||
|
editor.blur();
|
||||||
|
expect(rectangle.boundElements).toStrictEqual([
|
||||||
|
{ id: text.id, type: "text" },
|
||||||
|
]);
|
||||||
|
mouse.reset();
|
||||||
|
UI.clickTool("selection");
|
||||||
|
mouse.clickAt(10, 20);
|
||||||
|
mouse.down();
|
||||||
|
mouse.up();
|
||||||
|
fireEvent.contextMenu(GlobalTestState.canvas, {
|
||||||
|
button: 2,
|
||||||
|
clientX: 20,
|
||||||
|
clientY: 30,
|
||||||
|
});
|
||||||
|
const contextMenu = document.querySelector(".context-menu");
|
||||||
|
fireEvent.click(queryByText(contextMenu as HTMLElement, "Unbind text")!);
|
||||||
|
expect(h.elements[0].boundElements).toEqual([]);
|
||||||
|
expect((h.elements[1] as ExcalidrawTextElement).containerId).toEqual(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+327
-50
@@ -1,10 +1,32 @@
|
|||||||
import { CODES, KEYS } from "../keys";
|
import { CODES, KEYS } from "../keys";
|
||||||
import { isWritableElement, getFontString } from "../utils";
|
import {
|
||||||
|
isWritableElement,
|
||||||
|
getFontString,
|
||||||
|
getFontFamilyString,
|
||||||
|
isTestEnv,
|
||||||
|
} from "../utils";
|
||||||
import Scene from "../scene/Scene";
|
import Scene from "../scene/Scene";
|
||||||
import { isTextElement } from "./typeChecks";
|
import { isBoundToContainer, isTextElement } from "./typeChecks";
|
||||||
import { CLASSES } from "../constants";
|
import { CLASSES, BOUND_TEXT_PADDING, VERTICAL_ALIGN } from "../constants";
|
||||||
import { ExcalidrawElement } from "./types";
|
import {
|
||||||
|
ExcalidrawElement,
|
||||||
|
ExcalidrawTextElement,
|
||||||
|
ExcalidrawLinearElement,
|
||||||
|
} from "./types";
|
||||||
import { AppState } from "../types";
|
import { AppState } from "../types";
|
||||||
|
import { mutateElement } from "./mutateElement";
|
||||||
|
import {
|
||||||
|
getApproxLineHeight,
|
||||||
|
getBoundTextElementId,
|
||||||
|
getContainerElement,
|
||||||
|
wrapText,
|
||||||
|
} from "./textElement";
|
||||||
|
import {
|
||||||
|
actionDecreaseFontSize,
|
||||||
|
actionIncreaseFontSize,
|
||||||
|
} from "../actions/actionProperties";
|
||||||
|
import { actionZoomIn, actionZoomOut } from "../actions/actionCanvas";
|
||||||
|
import App from "../components/App";
|
||||||
|
|
||||||
const normalizeText = (text: string) => {
|
const normalizeText = (text: string) => {
|
||||||
return (
|
return (
|
||||||
@@ -22,82 +44,194 @@ const getTransform = (
|
|||||||
angle: number,
|
angle: number,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
maxWidth: number,
|
maxWidth: number,
|
||||||
|
maxHeight: number,
|
||||||
) => {
|
) => {
|
||||||
const { zoom, offsetTop, offsetLeft } = appState;
|
const { zoom } = appState;
|
||||||
const degree = (180 * angle) / Math.PI;
|
const degree = (180 * angle) / Math.PI;
|
||||||
// offsets must be multiplied by 2 to account for the division by 2 of
|
let translateX = (width * (zoom.value - 1)) / 2;
|
||||||
// the whole expression afterwards
|
let translateY = (height * (zoom.value - 1)) / 2;
|
||||||
let translateX = ((width - offsetLeft * 2) * (zoom.value - 1)) / 2;
|
|
||||||
const translateY = ((height - offsetTop * 2) * (zoom.value - 1)) / 2;
|
|
||||||
if (width > maxWidth && zoom.value !== 1) {
|
if (width > maxWidth && zoom.value !== 1) {
|
||||||
translateX = (maxWidth / 2) * (zoom.value - 1);
|
translateX = (maxWidth * (zoom.value - 1)) / 2;
|
||||||
|
}
|
||||||
|
if (height > maxHeight && zoom.value !== 1) {
|
||||||
|
translateY = (maxHeight * (zoom.value - 1)) / 2;
|
||||||
}
|
}
|
||||||
return `translate(${translateX}px, ${translateY}px) scale(${zoom.value}) rotate(${degree}deg)`;
|
return `translate(${translateX}px, ${translateY}px) scale(${zoom.value}) rotate(${degree}deg)`;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const textWysiwyg = ({
|
export const textWysiwyg = ({
|
||||||
id,
|
id,
|
||||||
appState,
|
|
||||||
onChange,
|
onChange,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
getViewportCoords,
|
getViewportCoords,
|
||||||
element,
|
element,
|
||||||
canvas,
|
canvas,
|
||||||
excalidrawContainer,
|
excalidrawContainer,
|
||||||
|
app,
|
||||||
}: {
|
}: {
|
||||||
id: ExcalidrawElement["id"];
|
id: ExcalidrawElement["id"];
|
||||||
appState: AppState;
|
|
||||||
onChange?: (text: string) => void;
|
onChange?: (text: string) => void;
|
||||||
onSubmit: (data: { text: string; viaKeyboard: boolean }) => void;
|
onSubmit: (data: {
|
||||||
|
text: string;
|
||||||
|
viaKeyboard: boolean;
|
||||||
|
originalText: string;
|
||||||
|
}) => void;
|
||||||
getViewportCoords: (x: number, y: number) => [number, number];
|
getViewportCoords: (x: number, y: number) => [number, number];
|
||||||
element: ExcalidrawElement;
|
element: ExcalidrawTextElement;
|
||||||
canvas: HTMLCanvasElement | null;
|
canvas: HTMLCanvasElement | null;
|
||||||
excalidrawContainer: HTMLDivElement | null;
|
excalidrawContainer: HTMLDivElement | null;
|
||||||
|
app: App;
|
||||||
}) => {
|
}) => {
|
||||||
|
const textPropertiesUpdated = (
|
||||||
|
updatedElement: ExcalidrawTextElement,
|
||||||
|
editable: HTMLTextAreaElement,
|
||||||
|
) => {
|
||||||
|
const currentFont = editable.style.fontFamily.replace(/"/g, "");
|
||||||
|
if (
|
||||||
|
getFontFamilyString({ fontFamily: updatedElement.fontFamily }) !==
|
||||||
|
currentFont
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (`${updatedElement.fontSize}px` !== editable.style.fontSize) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let originalContainerHeight: number;
|
||||||
|
|
||||||
const updateWysiwygStyle = () => {
|
const updateWysiwygStyle = () => {
|
||||||
const updatedElement = Scene.getScene(element)?.getElement(id);
|
const appState = app.state;
|
||||||
|
const updatedElement = Scene.getScene(element)?.getElement(
|
||||||
|
id,
|
||||||
|
) as ExcalidrawTextElement;
|
||||||
|
const { textAlign, verticalAlign } = updatedElement;
|
||||||
|
|
||||||
|
const approxLineHeight = getApproxLineHeight(getFontString(updatedElement));
|
||||||
if (updatedElement && isTextElement(updatedElement)) {
|
if (updatedElement && isTextElement(updatedElement)) {
|
||||||
const [viewportX, viewportY] = getViewportCoords(
|
let coordX = updatedElement.x;
|
||||||
updatedElement.x,
|
let coordY = updatedElement.y;
|
||||||
updatedElement.y,
|
const container = getContainerElement(updatedElement);
|
||||||
);
|
let maxWidth = updatedElement.width;
|
||||||
const { textAlign, angle } = updatedElement;
|
|
||||||
|
|
||||||
editable.value = updatedElement.text;
|
let maxHeight = updatedElement.height;
|
||||||
|
let width = updatedElement.width;
|
||||||
const lines = updatedElement.text.replace(/\r\n?/g, "\n").split("\n");
|
// Set to element height by default since that's
|
||||||
const lineHeight = updatedElement.height / lines.length;
|
// what is going to be used for unbounded text
|
||||||
const maxWidth =
|
let height = updatedElement.height;
|
||||||
(appState.offsetLeft + appState.width - viewportX - 8) /
|
if (container && updatedElement.containerId) {
|
||||||
appState.zoom.value -
|
const propertiesUpdated = textPropertiesUpdated(
|
||||||
// margin-right of parent if any
|
updatedElement,
|
||||||
Number(
|
editable,
|
||||||
getComputedStyle(
|
|
||||||
excalidrawContainer?.parentNode as Element,
|
|
||||||
).marginRight.slice(0, -2),
|
|
||||||
);
|
);
|
||||||
|
// using editor.style.height to get the accurate height of text editor
|
||||||
|
const editorHeight = Number(editable.style.height.slice(0, -2));
|
||||||
|
if (editorHeight > 0) {
|
||||||
|
height = editorHeight;
|
||||||
|
}
|
||||||
|
if (propertiesUpdated) {
|
||||||
|
originalContainerHeight = container.height;
|
||||||
|
|
||||||
|
// update height of the editor after properties updated
|
||||||
|
height = updatedElement.height;
|
||||||
|
}
|
||||||
|
if (!originalContainerHeight) {
|
||||||
|
originalContainerHeight = container.height;
|
||||||
|
}
|
||||||
|
maxWidth = container.width - BOUND_TEXT_PADDING * 2;
|
||||||
|
maxHeight = container.height - BOUND_TEXT_PADDING * 2;
|
||||||
|
width = maxWidth;
|
||||||
|
// The coordinates of text box set a distance of
|
||||||
|
// 5px to preserve padding
|
||||||
|
coordX = container.x + BOUND_TEXT_PADDING;
|
||||||
|
// autogrow container height if text exceeds
|
||||||
|
if (height > maxHeight) {
|
||||||
|
const diff = Math.min(height - maxHeight, approxLineHeight);
|
||||||
|
mutateElement(container, { height: container.height + diff });
|
||||||
|
return;
|
||||||
|
} else if (
|
||||||
|
// autoshrink container height until original container height
|
||||||
|
// is reached when text is removed
|
||||||
|
container.height > originalContainerHeight &&
|
||||||
|
height < maxHeight
|
||||||
|
) {
|
||||||
|
const diff = Math.min(maxHeight - height, approxLineHeight);
|
||||||
|
mutateElement(container, { height: container.height - diff });
|
||||||
|
}
|
||||||
|
// Start pushing text upward until a diff of 30px (padding)
|
||||||
|
// is reached
|
||||||
|
else {
|
||||||
|
// vertically center align the text
|
||||||
|
if (verticalAlign === VERTICAL_ALIGN.MIDDLE) {
|
||||||
|
coordY = container.y + container.height / 2 - height / 2;
|
||||||
|
}
|
||||||
|
if (verticalAlign === VERTICAL_ALIGN.BOTTOM) {
|
||||||
|
coordY =
|
||||||
|
container.y + container.height - height - BOUND_TEXT_PADDING;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const [viewportX, viewportY] = getViewportCoords(coordX, coordY);
|
||||||
|
const initialSelectionStart = editable.selectionStart;
|
||||||
|
const initialSelectionEnd = editable.selectionEnd;
|
||||||
|
const initialLength = editable.value.length;
|
||||||
|
editable.value = updatedElement.originalText;
|
||||||
|
|
||||||
|
// restore cursor position after value updated so it doesn't
|
||||||
|
// go to the end of text when container auto expanded
|
||||||
|
if (
|
||||||
|
initialSelectionStart === initialSelectionEnd &&
|
||||||
|
initialSelectionEnd !== initialLength
|
||||||
|
) {
|
||||||
|
// get diff between length and selection end and shift
|
||||||
|
// the cursor by "diff" times to position correctly
|
||||||
|
const diff = initialLength - initialSelectionEnd;
|
||||||
|
editable.selectionStart = editable.value.length - diff;
|
||||||
|
editable.selectionEnd = editable.value.length - diff;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = updatedElement.originalText.split("\n");
|
||||||
|
const lineHeight = updatedElement.containerId
|
||||||
|
? approxLineHeight
|
||||||
|
: updatedElement.height / lines.length;
|
||||||
|
if (!container) {
|
||||||
|
maxWidth = (appState.width - 8 - viewportX) / appState.zoom.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure text editor height doesn't go beyond viewport
|
||||||
|
const editorMaxHeight =
|
||||||
|
(appState.height - viewportY) / appState.zoom.value;
|
||||||
|
const angle = container ? container.angle : updatedElement.angle;
|
||||||
Object.assign(editable.style, {
|
Object.assign(editable.style, {
|
||||||
font: getFontString(updatedElement),
|
font: getFontString(updatedElement),
|
||||||
// must be defined *after* font ¯\_(ツ)_/¯
|
// must be defined *after* font ¯\_(ツ)_/¯
|
||||||
lineHeight: `${lineHeight}px`,
|
lineHeight: `${lineHeight}px`,
|
||||||
width: `${updatedElement.width}px`,
|
width: `${width}px`,
|
||||||
height: `${updatedElement.height}px`,
|
height: `${height}px`,
|
||||||
left: `${viewportX}px`,
|
left: `${viewportX}px`,
|
||||||
top: `${viewportY}px`,
|
top: `${viewportY}px`,
|
||||||
transform: getTransform(
|
transform: getTransform(
|
||||||
updatedElement.width,
|
width,
|
||||||
updatedElement.height,
|
height,
|
||||||
angle,
|
angle,
|
||||||
appState,
|
appState,
|
||||||
maxWidth,
|
maxWidth,
|
||||||
|
editorMaxHeight,
|
||||||
),
|
),
|
||||||
textAlign,
|
textAlign,
|
||||||
|
verticalAlign,
|
||||||
color: updatedElement.strokeColor,
|
color: updatedElement.strokeColor,
|
||||||
opacity: updatedElement.opacity / 100,
|
opacity: updatedElement.opacity / 100,
|
||||||
filter: "var(--theme-filter)",
|
filter: "var(--theme-filter)",
|
||||||
maxWidth: `${maxWidth}px`,
|
maxWidth: `${maxWidth}px`,
|
||||||
|
maxHeight: `${editorMaxHeight}px`,
|
||||||
});
|
});
|
||||||
|
// For some reason updating font attribute doesn't set font family
|
||||||
|
// hence updating font family explicitly for test environment
|
||||||
|
if (isTestEnv()) {
|
||||||
|
editable.style.fontFamily = getFontFamilyString(updatedElement);
|
||||||
|
}
|
||||||
|
mutateElement(updatedElement, { x: coordX, y: coordY });
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -110,6 +244,13 @@ export const textWysiwyg = ({
|
|||||||
editable.wrap = "off";
|
editable.wrap = "off";
|
||||||
editable.classList.add("excalidraw-wysiwyg");
|
editable.classList.add("excalidraw-wysiwyg");
|
||||||
|
|
||||||
|
let whiteSpace = "pre";
|
||||||
|
let wordBreak = "normal";
|
||||||
|
|
||||||
|
if (isBoundToContainer(element)) {
|
||||||
|
whiteSpace = "pre-wrap";
|
||||||
|
wordBreak = "break-word";
|
||||||
|
}
|
||||||
Object.assign(editable.style, {
|
Object.assign(editable.style, {
|
||||||
position: "absolute",
|
position: "absolute",
|
||||||
display: "inline-block",
|
display: "inline-block",
|
||||||
@@ -122,23 +263,72 @@ export const textWysiwyg = ({
|
|||||||
resize: "none",
|
resize: "none",
|
||||||
background: "transparent",
|
background: "transparent",
|
||||||
overflow: "hidden",
|
overflow: "hidden",
|
||||||
// prevent line wrapping (`whitespace: nowrap` doesn't work on FF)
|
|
||||||
whiteSpace: "pre",
|
|
||||||
// must be specified because in dark mode canvas creates a stacking context
|
// must be specified because in dark mode canvas creates a stacking context
|
||||||
zIndex: "var(--zIndex-wysiwyg)",
|
zIndex: "var(--zIndex-wysiwyg)",
|
||||||
|
wordBreak,
|
||||||
|
// prevent line wrapping (`whitespace: nowrap` doesn't work on FF)
|
||||||
|
whiteSpace,
|
||||||
|
overflowWrap: "break-word",
|
||||||
});
|
});
|
||||||
|
|
||||||
updateWysiwygStyle();
|
updateWysiwygStyle();
|
||||||
|
|
||||||
if (onChange) {
|
if (onChange) {
|
||||||
editable.oninput = () => {
|
editable.oninput = () => {
|
||||||
|
const updatedElement = Scene.getScene(element)?.getElement(
|
||||||
|
id,
|
||||||
|
) as ExcalidrawTextElement;
|
||||||
|
const font = getFontString(updatedElement);
|
||||||
|
// using scrollHeight here since we need to calculate
|
||||||
|
// number of lines so cannot use editable.style.height
|
||||||
|
// as that gets updated below
|
||||||
|
const lines = editable.scrollHeight / getApproxLineHeight(font);
|
||||||
|
// auto increase height only when lines > 1 so its
|
||||||
|
// measured correctly and vertically aligns for
|
||||||
|
// first line as well as setting height to "auto"
|
||||||
|
// doubles the height as soon as user starts typing
|
||||||
|
if (isBoundToContainer(element) && lines > 1) {
|
||||||
|
let height = "auto";
|
||||||
|
|
||||||
|
if (lines === 2) {
|
||||||
|
const container = getContainerElement(element);
|
||||||
|
const actualLineCount = wrapText(
|
||||||
|
editable.value,
|
||||||
|
font,
|
||||||
|
container!.width,
|
||||||
|
).split("\n").length;
|
||||||
|
|
||||||
|
// This is browser behaviour when setting height to "auto"
|
||||||
|
// It sets the height needed for 2 lines even if actual
|
||||||
|
// line count is 1 as mentioned above as well
|
||||||
|
// hence reducing the height by half if actual line count is 1
|
||||||
|
// so single line aligns vertically when deleting
|
||||||
|
if (actualLineCount === 1) {
|
||||||
|
height = `${editable.scrollHeight / 2}px`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
editable.style.height = height;
|
||||||
|
editable.style.height = `${editable.scrollHeight}px`;
|
||||||
|
}
|
||||||
onChange(normalizeText(editable.value));
|
onChange(normalizeText(editable.value));
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
editable.onkeydown = (event) => {
|
editable.onkeydown = (event) => {
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (event.key === KEYS.ESCAPE) {
|
|
||||||
|
if (!event.shiftKey && actionZoomIn.keyTest(event)) {
|
||||||
|
event.preventDefault();
|
||||||
|
app.actionManager.executeAction(actionZoomIn);
|
||||||
|
updateWysiwygStyle();
|
||||||
|
} else if (!event.shiftKey && actionZoomOut.keyTest(event)) {
|
||||||
|
event.preventDefault();
|
||||||
|
app.actionManager.executeAction(actionZoomOut);
|
||||||
|
updateWysiwygStyle();
|
||||||
|
} else if (actionDecreaseFontSize.keyTest(event)) {
|
||||||
|
app.actionManager.executeAction(actionDecreaseFontSize);
|
||||||
|
} else if (actionIncreaseFontSize.keyTest(event)) {
|
||||||
|
app.actionManager.executeAction(actionIncreaseFontSize);
|
||||||
|
} else if (event.key === KEYS.ESCAPE) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
submittedViaKeyboard = true;
|
submittedViaKeyboard = true;
|
||||||
handleSubmit();
|
handleSubmit();
|
||||||
@@ -174,7 +364,7 @@ export const textWysiwyg = ({
|
|||||||
const linesStartIndices = getSelectedLinesStartIndices();
|
const linesStartIndices = getSelectedLinesStartIndices();
|
||||||
|
|
||||||
let value = editable.value;
|
let value = editable.value;
|
||||||
linesStartIndices.forEach((startIndex) => {
|
linesStartIndices.forEach((startIndex: number) => {
|
||||||
const startValue = value.slice(0, startIndex);
|
const startValue = value.slice(0, startIndex);
|
||||||
const endValue = value.slice(startIndex);
|
const endValue = value.slice(startIndex);
|
||||||
|
|
||||||
@@ -232,7 +422,7 @@ export const textWysiwyg = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @returns indeces of start positions of selected lines, in reverse order
|
* @returns indices of start positions of selected lines, in reverse order
|
||||||
*/
|
*/
|
||||||
const getSelectedLinesStartIndices = () => {
|
const getSelectedLinesStartIndices = () => {
|
||||||
let { selectionStart, selectionEnd, value } = editable;
|
let { selectionStart, selectionEnd, value } = editable;
|
||||||
@@ -274,9 +464,43 @@ export const textWysiwyg = ({
|
|||||||
// it'd get stuck in an infinite loop of blur→onSubmit after we re-focus the
|
// it'd get stuck in an infinite loop of blur→onSubmit after we re-focus the
|
||||||
// wysiwyg on update
|
// wysiwyg on update
|
||||||
cleanup();
|
cleanup();
|
||||||
|
const updateElement = Scene.getScene(element)?.getElement(
|
||||||
|
element.id,
|
||||||
|
) as ExcalidrawTextElement;
|
||||||
|
if (!updateElement) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let text = editable.value;
|
||||||
|
const container = getContainerElement(updateElement);
|
||||||
|
|
||||||
|
if (container) {
|
||||||
|
text = updateElement.text;
|
||||||
|
if (editable.value) {
|
||||||
|
const boundTextElementId = getBoundTextElementId(container);
|
||||||
|
if (!boundTextElementId || boundTextElementId !== element.id) {
|
||||||
|
mutateElement(container, {
|
||||||
|
boundElements: (container.boundElements || []).concat({
|
||||||
|
type: "text",
|
||||||
|
id: element.id,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
mutateElement(container, {
|
||||||
|
boundElements: container.boundElements?.filter(
|
||||||
|
(ele) =>
|
||||||
|
!isTextElement(
|
||||||
|
ele as ExcalidrawTextElement | ExcalidrawLinearElement,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
onSubmit({
|
onSubmit({
|
||||||
text: normalizeText(editable.value),
|
text,
|
||||||
viaKeyboard: submittedViaKeyboard,
|
viaKeyboard: submittedViaKeyboard,
|
||||||
|
originalText: editable.value,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -305,27 +529,75 @@ export const textWysiwyg = ({
|
|||||||
editable.remove();
|
editable.remove();
|
||||||
};
|
};
|
||||||
|
|
||||||
const bindBlurEvent = () => {
|
const bindBlurEvent = (event?: MouseEvent) => {
|
||||||
window.removeEventListener("pointerup", bindBlurEvent);
|
window.removeEventListener("pointerup", bindBlurEvent);
|
||||||
// Deferred so that the pointerdown that initiates the wysiwyg doesn't
|
// Deferred so that the pointerdown that initiates the wysiwyg doesn't
|
||||||
// trigger the blur on ensuing pointerup.
|
// trigger the blur on ensuing pointerup.
|
||||||
// Also to handle cases such as picking a color which would trigger a blur
|
// Also to handle cases such as picking a color which would trigger a blur
|
||||||
// in that same tick.
|
// in that same tick.
|
||||||
|
const target = event?.target;
|
||||||
|
|
||||||
|
const isTargetColorPicker =
|
||||||
|
target instanceof HTMLInputElement &&
|
||||||
|
target.closest(".color-picker-input") &&
|
||||||
|
isWritableElement(target);
|
||||||
|
|
||||||
|
const isShapeActionsPanel =
|
||||||
|
(target instanceof HTMLElement || target instanceof SVGElement) &&
|
||||||
|
(target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) ||
|
||||||
|
target.closest(`.${CLASSES.SHAPE_ACTIONS_MOBILE_MENU}`) ||
|
||||||
|
target.closest(`.${CLASSES.MOBILE_TOOLBAR}`));
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
editable.onblur = handleSubmit;
|
editable.onblur = () => {
|
||||||
|
app.setState({
|
||||||
|
toastMessage:
|
||||||
|
target instanceof HTMLElement
|
||||||
|
? target.tagName ?? "no tagName"
|
||||||
|
: "not an HTMLElement",
|
||||||
|
});
|
||||||
|
if (isShapeActionsPanel) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
app.setState({
|
||||||
|
toastMessage: "debug: onblur",
|
||||||
|
});
|
||||||
|
handleSubmit();
|
||||||
|
};
|
||||||
|
if (target && (isTargetColorPicker || isShapeActionsPanel)) {
|
||||||
|
target.onblur = () => {
|
||||||
|
editable.focus();
|
||||||
|
};
|
||||||
|
}
|
||||||
// case: clicking on the same property → no change → no update → no focus
|
// case: clicking on the same property → no change → no update → no focus
|
||||||
editable.focus();
|
if (!isTargetColorPicker) {
|
||||||
|
editable.focus();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// prevent blur when changing properties from the menu
|
// prevent blur when changing properties from the menu
|
||||||
const onPointerDown = (event: MouseEvent) => {
|
const onPointerDown = (event: MouseEvent) => {
|
||||||
if (
|
const isTargetColorPicker =
|
||||||
|
event.target instanceof HTMLInputElement &&
|
||||||
|
event.target.closest(".color-picker-input") &&
|
||||||
|
isWritableElement(event.target);
|
||||||
|
const isShapeActionsPanel =
|
||||||
(event.target instanceof HTMLElement ||
|
(event.target instanceof HTMLElement ||
|
||||||
event.target instanceof SVGElement) &&
|
event.target instanceof SVGElement) &&
|
||||||
event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) &&
|
(event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MENU}`) ||
|
||||||
!isWritableElement(event.target)
|
event.target.closest(`.${CLASSES.SHAPE_ACTIONS_MOBILE_MENU}`) ||
|
||||||
|
event.target.closest(`.${CLASSES.MOBILE_TOOLBAR}`));
|
||||||
|
if (
|
||||||
|
((event.target instanceof HTMLElement ||
|
||||||
|
event.target instanceof SVGElement) &&
|
||||||
|
isShapeActionsPanel &&
|
||||||
|
!isWritableElement(event.target)) ||
|
||||||
|
isTargetColorPicker
|
||||||
) {
|
) {
|
||||||
|
app.setState({
|
||||||
|
toastMessage: "debug: onPointerDown",
|
||||||
|
});
|
||||||
editable.onblur = null;
|
editable.onblur = null;
|
||||||
window.addEventListener("pointerup", bindBlurEvent);
|
window.addEventListener("pointerup", bindBlurEvent);
|
||||||
// handle edge-case where pointerup doesn't fire e.g. due to user
|
// handle edge-case where pointerup doesn't fire e.g. due to user
|
||||||
@@ -337,7 +609,12 @@ export const textWysiwyg = ({
|
|||||||
// handle updates of textElement properties of editing element
|
// handle updates of textElement properties of editing element
|
||||||
const unbindUpdate = Scene.getScene(element)!.addCallback(() => {
|
const unbindUpdate = Scene.getScene(element)!.addCallback(() => {
|
||||||
updateWysiwygStyle();
|
updateWysiwygStyle();
|
||||||
editable.focus();
|
const isColorPickerActive = !!document.activeElement?.closest(
|
||||||
|
".color-picker-input",
|
||||||
|
);
|
||||||
|
if (!isColorPickerActive) {
|
||||||
|
editable.focus();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ExcalidrawElement, PointerType } from "./types";
|
|||||||
import { getElementAbsoluteCoords, Bounds } from "./bounds";
|
import { getElementAbsoluteCoords, Bounds } from "./bounds";
|
||||||
import { rotate } from "../math";
|
import { rotate } from "../math";
|
||||||
import { Zoom } from "../types";
|
import { Zoom } from "../types";
|
||||||
|
import { isTextElement } from ".";
|
||||||
|
|
||||||
export type TransformHandleDirection =
|
export type TransformHandleDirection =
|
||||||
| "n"
|
| "n"
|
||||||
@@ -242,7 +243,7 @@ export const getTransformHandles = (
|
|||||||
omitSides = OMIT_SIDES_FOR_LINE_BACKSLASH;
|
omitSides = OMIT_SIDES_FOR_LINE_BACKSLASH;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (element.type === "text") {
|
} else if (isTextElement(element)) {
|
||||||
omitSides = OMIT_SIDES_FOR_TEXT_ELEMENT;
|
omitSides = OMIT_SIDES_FOR_TEXT_ELEMENT;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import {
|
|||||||
ExcalidrawFreeDrawElement,
|
ExcalidrawFreeDrawElement,
|
||||||
InitializedExcalidrawImageElement,
|
InitializedExcalidrawImageElement,
|
||||||
ExcalidrawImageElement,
|
ExcalidrawImageElement,
|
||||||
|
ExcalidrawTextElementWithContainer,
|
||||||
|
ExcalidrawTextContainer,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const isGenericElement = (
|
export const isGenericElement = (
|
||||||
@@ -85,7 +87,20 @@ export const isBindableElement = (
|
|||||||
(element.type === "rectangle" ||
|
(element.type === "rectangle" ||
|
||||||
element.type === "diamond" ||
|
element.type === "diamond" ||
|
||||||
element.type === "ellipse" ||
|
element.type === "ellipse" ||
|
||||||
element.type === "text")
|
element.type === "image" ||
|
||||||
|
(element.type === "text" && !element.containerId))
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isTextBindableContainer = (
|
||||||
|
element: ExcalidrawElement | null,
|
||||||
|
): element is ExcalidrawTextContainer => {
|
||||||
|
return (
|
||||||
|
element != null &&
|
||||||
|
(element.type === "rectangle" ||
|
||||||
|
element.type === "diamond" ||
|
||||||
|
element.type === "ellipse" ||
|
||||||
|
element.type === "image")
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -100,3 +115,20 @@ export const isExcalidrawElement = (element: any): boolean => {
|
|||||||
element?.type === "line"
|
element?.type === "line"
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const hasBoundTextElement = (
|
||||||
|
element: ExcalidrawElement | null,
|
||||||
|
): element is ExcalidrawBindableElement => {
|
||||||
|
return (
|
||||||
|
isBindableElement(element) &&
|
||||||
|
!!element.boundElements?.some(({ type }) => type === "text")
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const isBoundToContainer = (
|
||||||
|
element: ExcalidrawElement | null,
|
||||||
|
): element is ExcalidrawTextElementWithContainer => {
|
||||||
|
return (
|
||||||
|
element !== null && isTextElement(element) && element.containerId !== null
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|||||||
+26
-4
@@ -1,5 +1,5 @@
|
|||||||
import { Point } from "../types";
|
import { Point } from "../types";
|
||||||
import { FONT_FAMILY, THEME } from "../constants";
|
import { FONT_FAMILY, THEME, VERTICAL_ALIGN } from "../constants";
|
||||||
|
|
||||||
export type ChartType = "bar" | "line";
|
export type ChartType = "bar" | "line";
|
||||||
export type FillStyle = "hachure" | "cross-hatch" | "solid";
|
export type FillStyle = "hachure" | "cross-hatch" | "solid";
|
||||||
@@ -12,7 +12,9 @@ export type PointerType = "mouse" | "pen" | "touch";
|
|||||||
export type StrokeSharpness = "round" | "sharp";
|
export type StrokeSharpness = "round" | "sharp";
|
||||||
export type StrokeStyle = "solid" | "dashed" | "dotted";
|
export type StrokeStyle = "solid" | "dashed" | "dotted";
|
||||||
export type TextAlign = "left" | "center" | "right";
|
export type TextAlign = "left" | "center" | "right";
|
||||||
export type VerticalAlign = "top" | "middle";
|
|
||||||
|
type VerticalAlignKeys = keyof typeof VERTICAL_ALIGN;
|
||||||
|
export type VerticalAlign = typeof VERTICAL_ALIGN[VerticalAlignKeys];
|
||||||
|
|
||||||
type _ExcalidrawElementBase = Readonly<{
|
type _ExcalidrawElementBase = Readonly<{
|
||||||
id: string;
|
id: string;
|
||||||
@@ -43,8 +45,16 @@ type _ExcalidrawElementBase = Readonly<{
|
|||||||
/** List of groups the element belongs to.
|
/** List of groups the element belongs to.
|
||||||
Ordered from deepest to shallowest. */
|
Ordered from deepest to shallowest. */
|
||||||
groupIds: readonly GroupId[];
|
groupIds: readonly GroupId[];
|
||||||
/** Ids of (linear) elements that are bound to this element. */
|
/** other elements that are bound to this element */
|
||||||
boundElementIds: readonly ExcalidrawLinearElement["id"][] | null;
|
boundElements:
|
||||||
|
| readonly Readonly<{
|
||||||
|
id: ExcalidrawLinearElement["id"];
|
||||||
|
type: "arrow" | "text";
|
||||||
|
}>[]
|
||||||
|
| null;
|
||||||
|
/** epoch (ms) timestamp of last element update */
|
||||||
|
updated: number;
|
||||||
|
link: string | null;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
|
export type ExcalidrawSelectionElement = _ExcalidrawElementBase & {
|
||||||
@@ -114,6 +124,8 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
|
|||||||
baseline: number;
|
baseline: number;
|
||||||
textAlign: TextAlign;
|
textAlign: TextAlign;
|
||||||
verticalAlign: VerticalAlign;
|
verticalAlign: VerticalAlign;
|
||||||
|
containerId: ExcalidrawGenericElement["id"] | null;
|
||||||
|
originalText: string;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
export type ExcalidrawBindableElement =
|
export type ExcalidrawBindableElement =
|
||||||
@@ -123,6 +135,16 @@ export type ExcalidrawBindableElement =
|
|||||||
| ExcalidrawTextElement
|
| ExcalidrawTextElement
|
||||||
| ExcalidrawImageElement;
|
| ExcalidrawImageElement;
|
||||||
|
|
||||||
|
export type ExcalidrawTextContainer =
|
||||||
|
| ExcalidrawRectangleElement
|
||||||
|
| ExcalidrawDiamondElement
|
||||||
|
| ExcalidrawEllipseElement
|
||||||
|
| ExcalidrawImageElement;
|
||||||
|
|
||||||
|
export type ExcalidrawTextElementWithContainer = {
|
||||||
|
containerId: ExcalidrawTextContainer["id"];
|
||||||
|
} & ExcalidrawTextElement;
|
||||||
|
|
||||||
export type PointBinding = {
|
export type PointBinding = {
|
||||||
elementId: ExcalidrawBindableElement["id"];
|
elementId: ExcalidrawBindableElement["id"];
|
||||||
focus: number;
|
focus: number;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ export const INITIAL_SCENE_UPDATE_TIMEOUT = 5000;
|
|||||||
export const FILE_UPLOAD_TIMEOUT = 300;
|
export const FILE_UPLOAD_TIMEOUT = 300;
|
||||||
export const LOAD_IMAGES_TIMEOUT = 500;
|
export const LOAD_IMAGES_TIMEOUT = 500;
|
||||||
export const SYNC_FULL_SCENE_INTERVAL_MS = 20000;
|
export const SYNC_FULL_SCENE_INTERVAL_MS = 20000;
|
||||||
|
export const SYNC_BROWSER_TABS_TIMEOUT = 50;
|
||||||
|
export const CURSOR_SYNC_TIMEOUT = 33; // ~30fps
|
||||||
|
|
||||||
export const FILE_UPLOAD_MAX_BYTES = 3 * 1024 * 1024; // 3 MiB
|
export const FILE_UPLOAD_MAX_BYTES = 3 * 1024 * 1024; // 3 MiB
|
||||||
// 1 year (https://stackoverflow.com/a/25201898/927631)
|
// 1 year (https://stackoverflow.com/a/25201898/927631)
|
||||||
@@ -25,3 +27,13 @@ export const FIREBASE_STORAGE_PREFIXES = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const ROOM_ID_BYTES = 10;
|
export const ROOM_ID_BYTES = 10;
|
||||||
|
|
||||||
|
export const STORAGE_KEYS = {
|
||||||
|
LOCAL_STORAGE_ELEMENTS: "excalidraw",
|
||||||
|
LOCAL_STORAGE_APP_STATE: "excalidraw-state",
|
||||||
|
LOCAL_STORAGE_COLLAB: "excalidraw-collab",
|
||||||
|
LOCAL_STORAGE_KEY_COLLAB_FORCE_FLAG: "collabLinkForceLoadFlag",
|
||||||
|
LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
||||||
|
VERSION_DATA_STATE: "version-dataState",
|
||||||
|
VERSION_FILES: "version-files",
|
||||||
|
} as const;
|
||||||
|
|||||||
@@ -16,18 +16,20 @@ import {
|
|||||||
withBatchedUpdates,
|
withBatchedUpdates,
|
||||||
} from "../../utils";
|
} from "../../utils";
|
||||||
import {
|
import {
|
||||||
|
CURSOR_SYNC_TIMEOUT,
|
||||||
FILE_UPLOAD_MAX_BYTES,
|
FILE_UPLOAD_MAX_BYTES,
|
||||||
FIREBASE_STORAGE_PREFIXES,
|
FIREBASE_STORAGE_PREFIXES,
|
||||||
INITIAL_SCENE_UPDATE_TIMEOUT,
|
INITIAL_SCENE_UPDATE_TIMEOUT,
|
||||||
LOAD_IMAGES_TIMEOUT,
|
LOAD_IMAGES_TIMEOUT,
|
||||||
SCENE,
|
SCENE,
|
||||||
|
STORAGE_KEYS,
|
||||||
SYNC_FULL_SCENE_INTERVAL_MS,
|
SYNC_FULL_SCENE_INTERVAL_MS,
|
||||||
} from "../app_constants";
|
} from "../app_constants";
|
||||||
import {
|
import {
|
||||||
generateCollaborationLinkData,
|
generateCollaborationLinkData,
|
||||||
getCollaborationLink,
|
getCollaborationLink,
|
||||||
|
getCollabServer,
|
||||||
SocketUpdateDataSource,
|
SocketUpdateDataSource,
|
||||||
SOCKET_SERVER,
|
|
||||||
} from "../data";
|
} from "../data";
|
||||||
import {
|
import {
|
||||||
isSavedToFirebase,
|
isSavedToFirebase,
|
||||||
@@ -39,7 +41,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
importUsernameFromLocalStorage,
|
importUsernameFromLocalStorage,
|
||||||
saveUsernameToLocalStorage,
|
saveUsernameToLocalStorage,
|
||||||
STORAGE_KEYS,
|
|
||||||
} from "../data/localStorage";
|
} from "../data/localStorage";
|
||||||
import Portal from "./Portal";
|
import Portal from "./Portal";
|
||||||
import RoomDialog from "./RoomDialog";
|
import RoomDialog from "./RoomDialog";
|
||||||
@@ -65,6 +66,7 @@ import {
|
|||||||
reconcileElements as _reconcileElements,
|
reconcileElements as _reconcileElements,
|
||||||
} from "./reconciliation";
|
} from "./reconciliation";
|
||||||
import { decryptData } from "../../data/encryption";
|
import { decryptData } from "../../data/encryption";
|
||||||
|
import { resetBrowserStateVersions } from "../data/tabSync";
|
||||||
|
|
||||||
interface CollabState {
|
interface CollabState {
|
||||||
modalIsShown: boolean;
|
modalIsShown: boolean;
|
||||||
@@ -86,6 +88,7 @@ export interface CollabAPI {
|
|||||||
onCollabButtonClick: CollabInstance["onCollabButtonClick"];
|
onCollabButtonClick: CollabInstance["onCollabButtonClick"];
|
||||||
broadcastElements: CollabInstance["broadcastElements"];
|
broadcastElements: CollabInstance["broadcastElements"];
|
||||||
fetchImageFilesFromFirebase: CollabInstance["fetchImageFilesFromFirebase"];
|
fetchImageFilesFromFirebase: CollabInstance["fetchImageFilesFromFirebase"];
|
||||||
|
setUsername: (username: string) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -246,6 +249,10 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
|
|
||||||
this.saveCollabRoomToFirebase();
|
this.saveCollabRoomToFirebase();
|
||||||
if (window.confirm(t("alerts.collabStopOverridePrompt"))) {
|
if (window.confirm(t("alerts.collabStopOverridePrompt"))) {
|
||||||
|
// hack to ensure that we prefer we disregard any new browser state
|
||||||
|
// that could have been saved in other tabs while we were collaborating
|
||||||
|
resetBrowserStateVersions();
|
||||||
|
|
||||||
window.history.pushState({}, APP_NAME, window.location.origin);
|
window.history.pushState({}, APP_NAME, window.location.origin);
|
||||||
this.destroySocketClient();
|
this.destroySocketClient();
|
||||||
trackEvent("share", "room closed");
|
trackEvent("share", "room closed");
|
||||||
@@ -347,32 +354,29 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
|
|
||||||
this.isCollaborating = true;
|
this.isCollaborating = true;
|
||||||
|
|
||||||
const { default: socketIOClient }: any = await import(
|
const { default: socketIOClient } = await import(
|
||||||
/* webpackChunkName: "socketIoClient" */ "socket.io-client"
|
/* webpackChunkName: "socketIoClient" */ "socket.io-client"
|
||||||
);
|
);
|
||||||
|
|
||||||
this.portal.open(socketIOClient(SOCKET_SERVER), roomId, roomKey);
|
try {
|
||||||
|
const socketServerData = await getCollabServer();
|
||||||
|
|
||||||
if (existingRoomLinkData) {
|
this.portal.socket = this.portal.open(
|
||||||
this.excalidrawAPI.resetScene();
|
socketIOClient(socketServerData.url, {
|
||||||
|
transports: socketServerData.polling
|
||||||
|
? ["websocket", "polling"]
|
||||||
|
: ["websocket"],
|
||||||
|
}),
|
||||||
|
roomId,
|
||||||
|
roomKey,
|
||||||
|
);
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error(error);
|
||||||
|
this.setState({ errorMessage: error.message });
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
if (!existingRoomLinkData) {
|
||||||
const elements = await loadFromFirebase(
|
|
||||||
roomId,
|
|
||||||
roomKey,
|
|
||||||
this.portal.socket,
|
|
||||||
);
|
|
||||||
if (elements) {
|
|
||||||
scenePromise.resolve({
|
|
||||||
elements,
|
|
||||||
scrollToContent: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
|
||||||
// log the error and move on. other peers will sync us the scene.
|
|
||||||
console.error(error);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const elements = this.excalidrawAPI.getSceneElements().map((element) => {
|
const elements = this.excalidrawAPI.getSceneElements().map((element) => {
|
||||||
if (isImageElement(element) && element.status === "saved") {
|
if (isImageElement(element) && element.status === "saved") {
|
||||||
return newElementWith(element, { status: "pending" });
|
return newElementWith(element, { status: "pending" });
|
||||||
@@ -396,14 +400,17 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// fallback in case you're not alone in the room but still don't receive
|
// fallback in case you're not alone in the room but still don't receive
|
||||||
// initial SCENE_UPDATE message
|
// initial SCENE_INIT message
|
||||||
this.socketInitializationTimer = window.setTimeout(() => {
|
this.socketInitializationTimer = window.setTimeout(() => {
|
||||||
this.initializeSocket();
|
this.initializeRoom({
|
||||||
|
roomLinkData: existingRoomLinkData,
|
||||||
|
fetchScene: true,
|
||||||
|
});
|
||||||
scenePromise.resolve(null);
|
scenePromise.resolve(null);
|
||||||
}, INITIAL_SCENE_UPDATE_TIMEOUT);
|
}, INITIAL_SCENE_UPDATE_TIMEOUT);
|
||||||
|
|
||||||
// All socket listeners are moving to Portal
|
// All socket listeners are moving to Portal
|
||||||
this.portal.socket!.on(
|
this.portal.socket.on(
|
||||||
"client-broadcast",
|
"client-broadcast",
|
||||||
async (encryptedData: ArrayBuffer, iv: Uint8Array) => {
|
async (encryptedData: ArrayBuffer, iv: Uint8Array) => {
|
||||||
if (!this.portal.roomKey) {
|
if (!this.portal.roomKey) {
|
||||||
@@ -421,7 +428,7 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
return;
|
return;
|
||||||
case SCENE.INIT: {
|
case SCENE.INIT: {
|
||||||
if (!this.portal.socketInitialized) {
|
if (!this.portal.socketInitialized) {
|
||||||
this.initializeSocket();
|
this.initializeRoom({ fetchScene: false });
|
||||||
const remoteElements = decryptedData.payload.elements;
|
const remoteElements = decryptedData.payload.elements;
|
||||||
const reconciledElements = this.reconcileElements(remoteElements);
|
const reconciledElements = this.reconcileElements(remoteElements);
|
||||||
this.handleRemoteSceneUpdate(reconciledElements, {
|
this.handleRemoteSceneUpdate(reconciledElements, {
|
||||||
@@ -475,12 +482,15 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
this.portal.socket!.on("first-in-room", () => {
|
this.portal.socket.on("first-in-room", async () => {
|
||||||
if (this.portal.socket) {
|
if (this.portal.socket) {
|
||||||
this.portal.socket.off("first-in-room");
|
this.portal.socket.off("first-in-room");
|
||||||
}
|
}
|
||||||
this.initializeSocket();
|
const sceneData = await this.initializeRoom({
|
||||||
scenePromise.resolve(null);
|
fetchScene: true,
|
||||||
|
roomLinkData: existingRoomLinkData,
|
||||||
|
});
|
||||||
|
scenePromise.resolve(sceneData);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.initializeIdleDetector();
|
this.initializeIdleDetector();
|
||||||
@@ -492,9 +502,45 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
return scenePromise;
|
return scenePromise;
|
||||||
};
|
};
|
||||||
|
|
||||||
private initializeSocket = () => {
|
private initializeRoom = async ({
|
||||||
this.portal.socketInitialized = true;
|
fetchScene,
|
||||||
|
roomLinkData,
|
||||||
|
}:
|
||||||
|
| {
|
||||||
|
fetchScene: true;
|
||||||
|
roomLinkData: { roomId: string; roomKey: string } | null;
|
||||||
|
}
|
||||||
|
| { fetchScene: false; roomLinkData?: null }) => {
|
||||||
clearTimeout(this.socketInitializationTimer!);
|
clearTimeout(this.socketInitializationTimer!);
|
||||||
|
if (fetchScene && roomLinkData && this.portal.socket) {
|
||||||
|
this.excalidrawAPI.resetScene();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const elements = await loadFromFirebase(
|
||||||
|
roomLinkData.roomId,
|
||||||
|
roomLinkData.roomKey,
|
||||||
|
this.portal.socket,
|
||||||
|
);
|
||||||
|
if (elements) {
|
||||||
|
this.setLastBroadcastedOrReceivedSceneVersion(
|
||||||
|
getSceneVersion(elements),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
elements,
|
||||||
|
scrollToContent: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
// log the error and move on. other peers will sync us the scene.
|
||||||
|
console.error(error);
|
||||||
|
} finally {
|
||||||
|
this.portal.socketInitialized = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.portal.socketInitialized = true;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
private reconcileElements = (
|
private reconcileElements = (
|
||||||
@@ -558,7 +604,9 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
window.clearTimeout(this.idleTimeoutId);
|
window.clearTimeout(this.idleTimeoutId);
|
||||||
this.idleTimeoutId = null;
|
this.idleTimeoutId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.idleTimeoutId = window.setTimeout(this.reportIdle, IDLE_THRESHOLD);
|
this.idleTimeoutId = window.setTimeout(this.reportIdle, IDLE_THRESHOLD);
|
||||||
|
|
||||||
if (!this.activeIntervalId) {
|
if (!this.activeIntervalId) {
|
||||||
this.activeIntervalId = window.setInterval(
|
this.activeIntervalId = window.setInterval(
|
||||||
this.reportActive,
|
this.reportActive,
|
||||||
@@ -633,15 +681,18 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
return this.excalidrawAPI.getSceneElementsIncludingDeleted();
|
return this.excalidrawAPI.getSceneElementsIncludingDeleted();
|
||||||
};
|
};
|
||||||
|
|
||||||
onPointerUpdate = (payload: {
|
onPointerUpdate = throttle(
|
||||||
pointer: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["pointer"];
|
(payload: {
|
||||||
button: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["button"];
|
pointer: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["pointer"];
|
||||||
pointersMap: Gesture["pointers"];
|
button: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["button"];
|
||||||
}) => {
|
pointersMap: Gesture["pointers"];
|
||||||
payload.pointersMap.size < 2 &&
|
}) => {
|
||||||
this.portal.socket &&
|
payload.pointersMap.size < 2 &&
|
||||||
this.portal.broadcastMouseLocation(payload);
|
this.portal.socket &&
|
||||||
};
|
this.portal.broadcastMouseLocation(payload);
|
||||||
|
},
|
||||||
|
CURSOR_SYNC_TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
onIdleStateChange = (userState: UserIdleState) => {
|
onIdleStateChange = (userState: UserIdleState) => {
|
||||||
this.setState({ userState });
|
this.setState({ userState });
|
||||||
@@ -677,8 +728,12 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
this.setState({ modalIsShown: false });
|
this.setState({ modalIsShown: false });
|
||||||
};
|
};
|
||||||
|
|
||||||
onUsernameChange = (username: string) => {
|
setUsername = (username: string) => {
|
||||||
this.setState({ username });
|
this.setState({ username });
|
||||||
|
};
|
||||||
|
|
||||||
|
onUsernameChange = (username: string) => {
|
||||||
|
this.setUsername(username);
|
||||||
saveUsernameToLocalStorage(username);
|
saveUsernameToLocalStorage(username);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -712,6 +767,7 @@ class CollabWrapper extends PureComponent<Props, CollabState> {
|
|||||||
this.contextValue.broadcastElements = this.broadcastElements;
|
this.contextValue.broadcastElements = this.broadcastElements;
|
||||||
this.contextValue.fetchImageFilesFromFirebase =
|
this.contextValue.fetchImageFilesFromFirebase =
|
||||||
this.fetchImageFilesFromFirebase;
|
this.fetchImageFilesFromFirebase;
|
||||||
|
this.contextValue.setUsername = this.setUsername;
|
||||||
return this.contextValue;
|
return this.contextValue;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user