Compare commits

..

116 Commits

Author SHA1 Message Date
dependabot[bot]
ff5405bacc chore(deps): bump socket.io-client from 2.3.1 to 4.5.1
Bumps [socket.io-client](https://github.com/socketio/socket.io-client) from 2.3.1 to 4.5.1.
- [Release notes](https://github.com/socketio/socket.io-client/releases)
- [Changelog](https://github.com/socketio/socket.io-client/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io-client/compare/2.3.1...4.5.1)

---
updated-dependencies:
- dependency-name: socket.io-client
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-01-31 12:55:12 +00:00
David Luzar
e6de1fe4a4 feat: rewrite public UI component rendering using tunnels (#6117)
* feat: rewrite public UI component rendering using tunnels

* factor out into components

* comments

* fix variable naming

* fix not hiding welcomeScreen

* factor out AppFooter and memoize components

* remove `UIOptions.welcomeScreen` and render only from host app

* factor out tunnels into own file

* update changelog. Keep `UIOptions.welcomeScreen` as deprecated

* update changelog

* lint

---------

Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2023-01-31 13:53:20 +01:00
Aakansha Doshi
3a141ca77a fix: add 1px width to the container to calculate more accurately (#6174)
* fix: add 1px width to the container to calculate accurately

* fix tests
2023-01-30 18:52:56 +05:30
JUNYI OU
5ae39c9292 fix: quick typo fix (#6167) 2023-01-29 14:22:25 +01:00
Aakansha Doshi
e41ea9562b fix: set the width correctly using measureText in editor (#6162) 2023-01-28 12:09:53 +01:00
Ignacio Cuadra
b52c8943e4 fix: 🐛 broken emojis when wrap text (#6153)
* fix: 🐛 broken emojis when wrap text

* refactor: Delete unnecessary "else" (reduce indentation)

* fix: remove code block that causes the emojis to disappear

* Apply suggestions from code review

Co-authored-by: David Luzar <luzar.david@gmail.com>

* fix: 🚑 possibly undefined value

* Add spec

Co-authored-by: David Luzar <luzar.david@gmail.com>
Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2023-01-26 11:49:21 +05:30
Aakansha Doshi
cf38c0f933 fix: declare css variable for font in excalidraw so its available in host (#6160)
declar css variable for font in excalidraw so its available in host
2023-01-25 15:44:20 +05:30
David Luzar
1db078a3dc feat: close MainMenu and Library dropdown on item select (#6152) 2023-01-23 16:54:35 +01:00
David Luzar
d4afd66268 feat: add hand/panning tool (#6141)
* feat: add hand/panning tool

* move hand tool right of tool lock separator

* tweak i18n

* rename `panning` -> `hand`

* toggle between last tool and hand on `H` shortcut

* hide properties sidebar when `hand` active

* revert to rendering HandButton manually due to mobile toolbar
2023-01-23 16:12:28 +01:00
David Luzar
849e6a0c86 fix: button background and svg sizes (#6155)
* fix: button background color fallback

* fix svg width/height
2023-01-23 16:10:04 +01:00
Nishant-l
f03f5c948d style: change in ExportButton style (#6147) (#6148)
Co-authored-by: David Luzar <luzar.david@gmail.com>
2023-01-22 12:37:18 +00:00
David Luzar
d2b698093c feat: show copy-as-png export button on firefox and show steps how to enable it (#6125)
* feat: hide copy-as-png shortcut from help dialog if not supported

* fix: support firefox if clipboard.write supported

* show shrotcut in firefox and instead show error message how to enable the flag support

* widen to TypeError because minification

* show copy-as-png on firefox even if it will throw
2023-01-22 12:33:15 +01:00
Excalidraw Bot
0f1720be61 chore: Update translations from Crowdin (#6077) 2023-01-22 12:19:21 +01:00
David Luzar
d0b33d35db build: temporarily disable pre-commit (#6132) 2023-01-19 13:50:42 +01:00
Aakansha Doshi
d6a5ef1936 docs: release @excalidraw/excalidraw@0.14.1 🎉 (#6112) 2023-01-16 16:08:03 +05:30
Aakansha Doshi
c7a11f5cd2 docs: release @excalidraw/excalidraw@0.14.0 🎉 (#6109) 2023-01-13 16:08:29 +05:30
Aakansha Doshi
893c487add fix: remove overflow hidden from button (#6110)
remove overflow hidden from button
2023-01-13 15:44:33 +05:30
Aakansha Doshi
99fdffdab7 fix: mobile tools positioning (#6107)
* fix: mobile tools positioning

* add var for padding

* use css var

* new line

* stupid mistake

* lint
2023-01-13 00:57:25 +05:30
Aakansha Doshi
faad8a65f1 feat: new Live Collaboration Component API (#6104)
* feat: new Live Collaboration Component API

* namespace export icons into `icons` dictionary and lowercase

* update readme and changelog

* review fixes

* fix

* fix

* update docs

* remove

* allow button rest props

* update docs

* docs

* add `WelcomeScreen.Center.MenuItemLiveCollaborationTrigger`

* fix lint

* update changelog

Co-authored-by: dwelle <luzar.david@gmail.com>
2023-01-12 23:28:57 +05:30
Aakansha Doshi
9d04479f98 fix: renamed folder MainMenu->main-menu and support rest props (#6103)
* renamed folder MainMenu -> main-menu

* rename ariaLabel -> aria-label and dataTestId -> data-testid

* allow rest props

* fix

* lint

* add ts check

* ts for div

* fix

* fix

* fix
2023-01-12 20:40:09 +05:30
David Luzar
599a8f3c6f feat: support WelcomeScreen customization API (#6048) 2023-01-12 15:49:28 +01:00
David Luzar
0982da38fe feat: render unknown supplied children to UI (#6096) 2023-01-12 15:20:16 +01:00
Barnabás Molnár
699897f71b feat: generic button export (#6092)
Co-authored-by: dwelle <luzar.david@gmail.com>
2023-01-12 13:06:00 +01:00
Aakansha Doshi
328ff6c32d fix: use position absolute for mobile misc tools (#6099) 2023-01-11 19:47:40 +05:30
David Luzar
618442299f fix: React.memo resolvers not accounting for all props (#6042) 2023-01-09 10:24:17 +01:00
Antonio Della Fortuna
06b45e0cfc fix: image horizontal flip fix + improved tests (#5799)
Co-authored-by: Antonio Della Fortuna <a.dellafortuna00@gmail.com>
Co-authored-by: dwelle <luzar.david@gmail.com>
fixes https://github.com/excalidraw/excalidraw/issues/5784
2023-01-08 16:19:13 +00:00
David Luzar
809d5ba17f fix: png-exporting does not preserve angles correctly for flipped images (#6085)
* fix: png-exporting does not preserve angles correctly for flipped images

* refactor related code

* simplify further and comment
2023-01-08 16:22:04 +01:00
David Luzar
40d53d9231 fix: stale appState of MainMenu defaultItems rendered from Actions (#6074) 2023-01-06 14:32:55 +01:00
dependabot[bot]
9803a85381 build(deps): bump loader-utils from 2.0.3 to 2.0.4 in /src/packages/excalidraw (#5892)
build(deps): bump loader-utils in /src/packages/excalidraw

Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.3 to 2.0.4.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.4/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.3...v2.0.4)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:31:06 +05:30
dependabot[bot]
72784f9d29 build(deps): bump loader-utils from 2.0.3 to 2.0.4 (#5905)
Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.3 to 2.0.4.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.4/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.3...v2.0.4)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:30:43 +05:30
dependabot[bot]
e3249f930c build(deps): bump json5 from 1.0.1 to 1.0.2 (#6076)
Bumps [json5](https://github.com/json5/json5) from 1.0.1 to 1.0.2.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v1.0.1...v1.0.2)

---
updated-dependencies:
- dependency-name: json5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 06:59:44 +00:00
dependabot[bot]
cbe0d34f1a build(deps): bump decode-uri-component from 0.2.0 to 0.2.2 (#5963)
Bumps [decode-uri-component](https://github.com/SamVerschueren/decode-uri-component) from 0.2.0 to 0.2.2.
- [Release notes](https://github.com/SamVerschueren/decode-uri-component/releases)
- [Commits](https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.2)

---
updated-dependencies:
- dependency-name: decode-uri-component
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:26:23 +05:30
dependabot[bot]
bed8093e47 build(deps): bump json5 from 2.2.1 to 2.2.3 in /dev-docs (#6060)
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.3.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.3)

---
updated-dependencies:
- dependency-name: json5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:25:48 +05:30
dependabot[bot]
1255ca2e84 build(deps): bump json5 from 2.2.1 to 2.2.3 in /src/packages/utils (#6061)
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.3.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.3)

---
updated-dependencies:
- dependency-name: json5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:25:35 +05:30
dependabot[bot]
14d02dcaea build(deps): bump json5 from 2.2.1 to 2.2.3 in /src/packages/excalidraw (#6062)
Bumps [json5](https://github.com/json5/json5) from 2.2.1 to 2.2.3.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v2.2.1...v2.2.3)

---
updated-dependencies:
- dependency-name: json5
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-01-06 12:25:20 +05:30
Excalidraw Bot
9747223705 chore: Update translations from Crowdin (#6052)
* New translations en.json (German)

* Auto commit: Calculate translation coverage

* New translations en.json (Hindi)

* New translations en.json (Marathi)

* New translations en.json (Hindi)

* Auto commit: Calculate translation coverage

* New translations en.json (Galician)

* Auto commit: Calculate translation coverage

* New translations en.json (Romanian)

* New translations en.json (French)

* New translations en.json (Spanish)

* New translations en.json (Arabic)

* New translations en.json (Bulgarian)

* New translations en.json (Catalan)

* New translations en.json (Czech)

* New translations en.json (Danish)

* New translations en.json (German)

* New translations en.json (Greek)

* New translations en.json (Basque)

* New translations en.json (Finnish)

* New translations en.json (Hebrew)

* New translations en.json (Hungarian)

* New translations en.json (Italian)

* New translations en.json (Japanese)

* New translations en.json (Korean)

* New translations en.json (Kurdish)

* New translations en.json (Lithuanian)

* New translations en.json (Dutch)

* New translations en.json (Punjabi)

* New translations en.json (Polish)

* New translations en.json (Portuguese)

* New translations en.json (Russian)

* New translations en.json (Slovak)

* New translations en.json (Slovenian)

* New translations en.json (Swedish)

* New translations en.json (Turkish)

* New translations en.json (Ukrainian)

* New translations en.json (Chinese Simplified)

* New translations en.json (Chinese Traditional)

* New translations en.json (Vietnamese)

* New translations en.json (Galician)

* New translations en.json (Portuguese, Brazilian)

* New translations en.json (Indonesian)

* New translations en.json (Persian)

* New translations en.json (Tamil)

* New translations en.json (Bengali)

* New translations en.json (Marathi)

* New translations en.json (Norwegian Nynorsk)

* New translations en.json (Kazakh)

* New translations en.json (Latvian)

* New translations en.json (Hindi)

* New translations en.json (Burmese)

* New translations en.json (Chinese Traditional, Hong Kong)

* New translations en.json (Sinhala)

* New translations en.json (Norwegian Bokmal)

* New translations en.json (Occitan)

* New translations en.json (Kabyle)

* Auto commit: Calculate translation coverage

* New translations en.json (Chinese Simplified)

* Auto commit: Calculate translation coverage

* New translations en.json (Chinese Traditional)

* New translations en.json (Chinese Traditional)

* New translations en.json (Norwegian Bokmal)

* Auto commit: Calculate translation coverage

* New translations en.json (Latvian)

* Auto commit: Calculate translation coverage

* New translations en.json (Romanian)

* Auto commit: Calculate translation coverage

* New translations en.json (Slovenian)

* Auto commit: Calculate translation coverage

* New translations en.json (Spanish)

* New translations en.json (Russian)

* Auto commit: Calculate translation coverage

* New translations en.json (German)

* Auto commit: Calculate translation coverage

* New translations en.json (Vietnamese)

* Auto commit: Calculate translation coverage

* New translations en.json (Hindi)

* Auto commit: Calculate translation coverage

* New translations en.json (Dutch)

* Auto commit: Calculate translation coverage

* New translations en.json (Marathi)

* Auto commit: Calculate translation coverage

* New translations en.json (Latvian)

* New translations en.json (French)

* Auto commit: Calculate translation coverage

* New translations en.json (French)

* Auto commit: Calculate translation coverage

* New translations en.json (Portuguese, Brazilian)

* Auto commit: Calculate translation coverage

* New translations en.json (Japanese)

* Auto commit: Calculate translation coverage
2023-01-06 12:23:14 +05:30
EternalWill43
0f11f7da15 fix: HelpDialog (#6072) 2023-01-05 17:43:19 +01:00
Aakansha Doshi
8420aecb34 feat: new Menu Component API (#6034)
* feat: new Menu Component API

* allow valid children types

* introduce menu group to group items

* Add lang footer

* use display name

* displayName

* define types inside

* fix default menu

* add json export to menu

* fix

* simplify expression

* put open menu into own compo to optimize perf

So that we don't rerun `useOutsideClickHook` (and rebind event listeners
all the time)

* naming tweaks

* rename MenuComponents->MenuDefaultItems and export default items from Menu.Items

* import Menu.scss in Menu.tsx

* move menu scss to excal app

* Don't filter children inside menu group

* move E+ out of socials

* support style prop for MenuItem and MenuGroup

* Support header in menu group and add Excalidraw links header for default items in social section

* rename header to title

* fix padding for lang

* render menu in mobile

* review fixes

* tweaks

* Export collaborators and show in mobile menu

* revert .env

* lint :p

* again lint

* show correct actions in view mode for mobile

* Whitelist Collaborators Comp

* mobile styling

* padding

* don't show nerds when menu open in mobile

* lint :(

* hide shortcuts

* refactor userlist to support mobile and keep a wrapper comp for excal app

* use only UserList

* render only on mobile for default items

* remove unused hooks

* Show collab button in menu when onCollabButtonClick present and hide export when UIOptions.canvasActions.export is false

* fix tests

* lint

* inject userlist inside menu on mobile

* revert userlist

* move menu socials to default menu

* fix collab

* use meny in library

* Make Menu generic and create hamburgemenu for public excal menu and use menu in library as well

* use appState.openMenu for mobile

* fix tests

* styling fixes and support style and class name in menu content

* fix test

* rename MenuDefaultItems->DefaultItems

* move footer css to its own comp

* rename HamburgerMenu -> MainMenu

* rename menu -> dropdownMenu and update classes, onClick->onToggle

* close main menu when dialog closes

* by bye filtering

* update docs

* fix lint

* update example, docs for useDevice and footer in mobile, rename menu ->DropDownMenu everywhere

* spec

* remove isMenuOpenAtom and set openMenu as canvas for main menu, render decreases in specs :)

* [temp] remove cyclic depenedency to fix build

* hack- update appstate to sync lang change

* Add more specs

* wip: rewrite MainMenu footer

* fix margin

* fix snaps

* not needed as lang list no more imported

* simplify custom footer rendering

* Add DropdownMenuItemLink and DropdownMenuItemCustom and update API, docs

* fix `MainMenu.ItemCustom`

* naming

* use onSelect and base class for custom items

* fix lint

* fix snap

* use custom item for lang

* update docs

* fix

* properly use `MainMenu.ItemCustom` for `LanguageList`

* add margin top to custom items

* flex

Co-authored-by: dwelle <luzar.david@gmail.com>
2023-01-05 22:04:23 +05:30
David Luzar
08afb857c3 fix: show error message on collab save failure (#6063)
* fix: show error message on collab save failure

* comment
2023-01-02 23:53:51 +01:00
David Luzar
9230c8f4d2 fix: remove ga from docker build (#6059)
* fix: remove ga from docker build

* lint

* fix debug
2023-01-02 21:21:57 +01:00
Excalidraw Bot
dba8f812f1 chore: Update translations from Crowdin (#5807)
Co-authored-by: David Luzar <luzar.david@gmail.com>
2023-01-01 17:01:46 +00:00
DanielJGeiger
fdd8552637 feat: Scroll using PageUp and PageDown (#6038)
* feat: Scroll using PageUp and PageDown

* support x-axis via `shift` & enable in viewMode

* tweak test

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-31 15:54:37 -06:00
Aakansha Doshi
c8370b394c fix: use displayName since name gets stripped off when uglifying/minifiyng in production (#6036)
fix: use displayName since name gets stripped off when uglifying/minifiy in production
2022-12-27 15:17:13 +05:30
David Luzar
5fcf6a4845 fix: remove background from wysiwyg when editing arrow label (#6033)
Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2022-12-23 19:40:52 +01:00
Aakansha Doshi
af3b93c410 fix: use canvas measureText to calculate width in measureText (#6030)
* fix: use canvas measureText to calculate width in measureText

* calculate multiline width correctly using canvas measure text and rename functions

* set correct width when pasting in bound container

* take existing value + new pasted

* remove debugger :p

* fix snaps
2022-12-23 21:45:49 +05:30
David Luzar
2595e0de82 fix: restoring deleted bindings (#6029)
* fix: restoring deleted bindings

* add tests

* add one more test

* merge restore tests files
2022-12-23 11:48:14 +01:00
Aakansha Doshi
8ec5f7b982 feat: support shrinking text containers to original height when text removed (#6025)
* fix:cache bind text containers height so that it could autoshrink to original height when text deleted

* revert

* rename

* reset cache when resized

* safe check

* restore original containr height when text is unbind

* update cache when redrawing bounding box

* reset cache when unbind

* make type-safe

* add specs

* skip one test

* remoe mock

* fix

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-23 11:57:48 +05:30
David Luzar
9086674b27 chore: bump typescript @ 4.9.4 (#6024) 2022-12-22 19:32:21 +01:00
zsviczian
6273d56524 fix: ColorPicker getColor (#5949)
Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-22 12:53:49 +00:00
David Luzar
7e135c4e22 feat: move contextMenu into the component tree and control via appState (#6021) 2022-12-21 12:47:09 +01:00
Aakansha Doshi
b704705ed8 feat: render footer as a component instead of render prop (#5970)
* feat: render footer as a component instead of render prop

* Export FooterCenter as footer

* remove useDevice export

* revert some changes

* remove

* add spec

* update specs

* parse children into a dictionary

* factor app footer components into a single file

* Add docs

* split app footer components

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-21 14:29:06 +05:30
Aakansha Doshi
d2e371cdf0 fix: don't push whitespace to next line when exceeding max width during wrapping and make sure to use same width of text editor on DOM when measuring dimensions (#5996)
* fix: don't push whitespace to next line when exceeding max width during wrapping

* add a helper function and never push empty line

* use width same as in text area so dimensions are same

* add tests

* make sure dom element has exact same width as text editor
2022-12-21 12:32:43 +05:30
David Luzar
6ab3f0eb74 fix: showing grabbing cursor when holding spacebar (#6015) 2022-12-20 13:22:20 +01:00
David Luzar
539505affd fix: resize sometimes throwing on missing null-checks (#6013) 2022-12-18 23:06:01 +01:00
David Luzar
95d669390f fix: PWA not working after CRA@5 update (#6012)
* fix: PWA not working after CRA@5 update

* fix: fallback to default locale when fetch fails
2022-12-18 22:23:30 +01:00
David Luzar
73a45e1988 fix: not properly restoring element stroke and bg colors (#6002) 2022-12-16 18:19:26 +01:00
David Luzar
88c2812949 fix: Avatar outline on safari & center (#5997) 2022-12-16 18:18:34 +01:00
David Luzar
bdb14723b3 fix: chart pasting not working due to removing tab characters (#5987) 2022-12-16 18:18:27 +01:00
David Luzar
cc9e764585 feat: allow readonly actions to be used in viewMode (#5982) 2022-12-11 22:57:03 +01:00
Ryan Di
8466eb0eef fix: apply the right type of roundness when pasting styles (#5979)
* fix: only paste roundness when target and source elements are of the same type

* apply roundness when pasting across different types

* simplify

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-10 20:12:09 +08:00
Aakansha Doshi
0ebe6292a3 chore: add display name to context providers (#5974)
* chore: add display name to context providers

* fix typo
2022-12-08 16:19:44 +00:00
Ryan Di
5854ac3eed feat: better default radius sizes for rectangles (#5553)
Co-authored-by: Ryan <diweihao@bytedance.com>
Co-authored-by: dwelle <luzar.david@gmail.com>
2022-12-08 16:48:49 +01:00
Aakansha Doshi
65d84a5d5a fix: remove editor onpaste handler (#5971) 2022-12-07 23:05:57 +05:30
fennghuang
808366d112 fix: remove blank space (#5950) 2022-12-06 17:40:53 +05:30
Fer
9311c99d3c fix: Galego and Kurdî missing in languages plus two locale typos (#5954) 2022-12-06 17:34:22 +05:30
DanielJGeiger
d131b31084 fix: ExcalidrawArrowElement rather than ExcalidrawArrowEleement (#5955) 2022-12-06 17:30:03 +05:30
Aakansha Doshi
0111ca2050 fix: renderFooter styling (#5962) 2022-12-06 16:42:54 +05:30
Aakansha Doshi
a1dcd6d984 build: move release scripts to use release branch (#5958) 2022-12-06 16:33:02 +05:30
David Luzar
fffd4957db fix: repair element bindings on restore (#5956)
* fix: repair element bindings on restore

* fix dropping non-text bound elements

* be more conservative
2022-12-06 00:23:47 +01:00
Aakansha Doshi
760fd7b3a6 feat: Support labels for arrow 🔥 (#5723)
* feat: support arrow with text

* render arrow -> clear rect-> render text

* move bound text when linear elements move

* fix centering cursor when linear element rotated

* fix y coord when new line added and container has 3 points

* update text position when 2nd point moved

* support adding label on top of 2nd point when 3 points are present

* change linear element editor shortcut to cmd+enter and fix tests

* scale bound text points when resizing via bounding box

* ohh yeah rotation works :)

* fix coords when updating text properties

* calculate new position after rotation always from original position

* rotate the bound text by same angle as parent

* don't rotate text and make sure dimensions and coords are always calculated from original point

* hardcoding the text width for now

* Move the linear element when bound text hit

* Rotation working yaay

* consider text element angle when editing

* refactor

* update x2 coords if needed when text updated

* simplify

* consider bound text to be part of bounding box when hit

* show bounding box correctly when multiple element selected

* fix typo

* support rotating multiple elements

* support multiple element resizing

* shift bound text to mid point when odd points

* Always render linear element handles inside editor after element rendered so point is visible for bound text

* Delete bound text when point attached to it deleted

* move bound to mid segement mid point when points are even

* shift bound text when points nearby deleted and handle segment deletion

* Resize working :)

* more resize fixes

* don't update cache-its breaking delete points, look for better soln

* update mid point cache for bound elements when updated

* introduce wrapping when resizing

* wrap when resize for 2 pointer linear elements

* support adding text for linear elements with more than 3 points

* export to svg  working :)

* clip from nearest enclosing element with non transparent color if present when exporting and fill with correct color in canvas

* fix snap

* use visible elements

* Make export to svg work with Mask :)

* remove id

* mask canvas linear element area where label is added

* decide the position of bound text during render

* fix coords when editing

* fix multiple resize

* update cache when bound text version changes

* fix masking when rotated

* render text in correct position in preview

* remove unnecessary code

* fix masking when rotating linear element

* fix masking with zoom

* fix mask in preview for export

* fix offsets in export view

* fix coords on svg export

* fix mask when element rotated in svg

* enable double-click to enter text

* fix hint

* Position cursor correctly and text dimensiosn when height of element is negative

* don't allow 2 pointer linear element with bound text width to go beyond min width

* code cleanup

* fix freedraw

* Add padding

* don't show vertical align action for linear element containers

* Add specs for getBoundTextElementPosition

* more specs

* move some utils to linearElementEditor.ts

* remove only :p

* check absoulte coods in test

* Add test to hide vertical align for linear eleemnt with bound text

* improve export preview

* support labels only for arrows

* spec

* fix large texts

* fix tests

* fix zooming

* enter line editor with cmd+double click

* Allow points to move beyond min width/height for 2 pointer arrow with bound text

* fix hint for line editing

* attempt to fix arrow getting deselected

* fix hint and shortcut

* Add padding of 5px when creating bound text and add spec

* Wrap bound text when arrow binding containers moved

* Add spec

* remove

* set boundTextElementVersion to null if not present

* dont use cache when version mismatch

* Add a padding of 5px vertically when creating text

* Add box sizing content box

* Set bound elements when text element created to fix the padding

* fix zooming in editor

* fix zoom in export

* remove globalCompositeOperation and use clearRect instead of fillRect
2022-12-05 21:03:13 +05:30
Aakansha Doshi
1933116261 fix: don't allow whitespaces for bound text (#5939)
* fix: don't allow whitespaces for bound text

* fix

* remove

* remove empty else

* fix

* fix

* fix
2022-12-02 16:47:50 +05:30
David Luzar
8b33ca3a1a fix: bindings do not survive history serialization (#5942) 2022-12-02 10:36:18 +00:00
Aakansha Doshi
a86224c797 fix: Dedupe boundElement ids when container duplicated with alt+drag (#5938)
* Dedupe boundElement ids when container duplicated with alt+drag and add spec

* set to null by default
2022-12-01 20:44:33 +05:30
Aakansha Doshi
66bbfda460 fix: scale font correctly when using shift (#5935)
* fix: scale font correctly when using shift

* fix

* Empty-Commit

* Add spec

* fix
2022-11-30 15:55:01 +05:30
Aakansha Doshi
88b2f4707d refactor: remove unnecessary code (#5933) 2022-11-29 16:41:02 +05:30
Aakansha Doshi
25c6056b03 feat: Don't add midpoint until dragged beyond a threshold (#5927)
* Don't add midpoint until dragged beyond a threshold

* remove unnecessary code

* fix tests

* fix

* add spec

* remove isMidpoint

* cleanup

* fix threshold for zoom

* split into shouldAddMidpoint and addMidpoint

* wrap in flushSync for synchronous updates

* remove threshold for line editor and add spec

* [unrelated] fix stack overflow state update

* fix tests

* don't drag arrow when dragging to add mid point

* add specs

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-11-29 00:01:53 +05:30
Antonio Della Fortuna
baf9651d34 feat: changed text copy/paste behaviour (#5786)
Co-authored-by: dwelle <luzar.david@gmail.com>
Co-authored-by: Antonio Della Fortuna <a.dellafortuna00@gmail.com>
2022-11-26 23:44:26 +01:00
Aakansha Doshi
d2181847be fix: Always bind to container selected by user (#5880)
* fix: Always bind to container selected by user

* Don't bind to container when using text tool

* adjust z-index for bound text

* fix

* Add spec

* Add test

* Allow double click on transparent container and add spec

* fix spec

* adjust z-index only when binding

* update index

* fix

* add index check

* Update src/scene/Scene.ts

Co-authored-by: dwelle <luzar.david@gmail.com>
2022-11-25 15:45:34 +05:30
David Luzar
1f117995d9 fix: fonts not rendered on init if loadingdone not fired (#5923)
* fix: fonts not rendered on init if `loadingdone` not fired

* remove unnecessary check
2022-11-23 21:15:32 +01:00
David Luzar
52c96a6870 chore: bump create-react-app to 5.0.1 (from 4.0.3) (#5904) 2022-11-19 18:28:21 +01:00
David Luzar
81fd2350a9 fix: stop replacing del word with Delete (#5897) 2022-11-19 18:28:08 +01:00
David Luzar
8ed0fc2c87 fix: remove legacy React.render() from the editor (#5893) 2022-11-19 18:27:54 +01:00
Aakansha Doshi
96a5d6548b fix: allow adding text via enter only for text containers (#5891)
* fix: allow adding text via enter only for text containers

* fix

* fix

* fix

* move check isTextElement outside
2022-11-17 15:26:18 +05:30
dependabot[bot]
4709b953e7 build(deps): bump loader-utils from 2.0.3 to 2.0.4 in /dev-docs (#5885)
Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.3 to 2.0.4.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.4/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.3...v2.0.4)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-17 15:14:29 +05:30
David Luzar
bbe0c35f66 fix: stop font loadingdone loop when rendering element SVGs (#5883)
* fix: stop font `loadingdone` loop when rendering element SVGs

* update snaps

* stop updating scene elements array if no change was made

* always re-render if invalidating element shape
2022-11-15 21:02:57 +01:00
David Luzar
d273acb7e4 fix: refresh text dimensions only after font load done (#5878)
* fix: refresh text dimensions only after font load done

* fix snaps
2022-11-15 00:15:02 +01:00
dependabot[bot]
3c0b29d85f build(deps): bump loader-utils from 2.0.0 to 2.0.4 in /src/packages/utils (#5874)
build(deps): bump loader-utils in /src/packages/utils

Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.0 to 2.0.4.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.4/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.0...v2.0.4)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-14 15:49:05 +05:30
DanielJGeiger
bfbaeae67f fix: Correctly paste contents parsed by JSON.parse() as text. (#5868)
* Fix #5867

* Add test.

* Add tests to clipboard.test.ts

Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2022-11-14 14:02:54 +05:30
dependabot[bot]
74b9885955 build(deps): bump minimatch from 3.0.4 to 3.1.2 in /src/packages/excalidraw (#5861)
build(deps): bump minimatch in /src/packages/excalidraw

Bumps [minimatch](https://github.com/isaacs/minimatch) from 3.0.4 to 3.1.2.
- [Release notes](https://github.com/isaacs/minimatch/releases)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.0.4...v3.1.2)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-14 13:51:10 +05:30
dependabot[bot]
2cbe869a13 build(deps): bump socket.io-parser from 3.3.2 to 3.3.3 (#5862)
Bumps [socket.io-parser](https://github.com/socketio/socket.io-parser) from 3.3.2 to 3.3.3.
- [Release notes](https://github.com/socketio/socket.io-parser/releases)
- [Changelog](https://github.com/socketio/socket.io-parser/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io-parser/compare/3.3.2...3.3.3)

---
updated-dependencies:
- dependency-name: socket.io-parser
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-14 13:50:15 +05:30
dependabot[bot]
a48607eb25 build(deps): bump loader-utils from 2.0.2 to 2.0.3 in /src/packages/excalidraw (#5851)
build(deps): bump loader-utils in /src/packages/excalidraw

Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.2 to 2.0.3.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.3/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.2...v2.0.3)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-14 13:49:39 +05:30
zsviczian
7831b6e74b fix: SVG element attributes in icons.tsx (#5871)
Update icons.tsx
2022-11-14 11:42:28 +05:30
dependabot[bot]
640affe7c0 build(deps): bump loader-utils from 2.0.2 to 2.0.3 in /dev-docs (#5853)
Bumps [loader-utils](https://github.com/webpack/loader-utils) from 2.0.2 to 2.0.3.
- [Release notes](https://github.com/webpack/loader-utils/releases)
- [Changelog](https://github.com/webpack/loader-utils/blob/v2.0.3/CHANGELOG.md)
- [Commits](https://github.com/webpack/loader-utils/compare/v2.0.2...v2.0.3)

---
updated-dependencies:
- dependency-name: loader-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-10 15:02:18 +05:30
DanielJGeiger
335aff8838 fix: merge existing text with new when pasted (#5856)
* Fix #5855.

* fix test

* tweak

* Add specs

* Add more snaps

Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2022-11-09 23:39:53 +05:30
Aakansha Doshi
dc97dc30bf fix: disable FAST_REFRESH to fix live reload (#5852) 2022-11-09 17:13:20 +05:30
DanielJGeiger
a0ecfed4cd fix: Paste clipboard contents into unbound text elements (#5849)
* Fix #5848.

* Add test.

* some tweaks

Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2022-11-09 11:30:22 +05:30
Aakansha Doshi
e201e79cd0 fix: compute dimensions of container correctly when text pasted on container (#5845)
* fix: compute dimensions of container correctly when text pasted on container

* add test

* remove only
2022-11-08 19:50:41 +05:30
Pritam Sangani
e1c5c706c6 build: stops ignoring .env files from docker context so env variables get set during react app build. (#5809)
build: stops ignoring .env.development and .env.production files from docker context so env variables get set during react app build.
* this fixes the issue where Browse Libraries button link was broken in
  docker/self-hosted versions of excalidraw
2022-11-07 16:48:38 +05:30
David Luzar
bdc56090d7 feat: reintroduce x shortcut for freedraw (#5840) 2022-11-06 23:07:15 +01:00
David Luzar
58accc9310 feat: tweak toolbar shortcuts & remove library shortcut (#5832) 2022-11-06 20:14:53 +01:00
David Luzar
b91158198e feat: clean unused images only after 24hrs (local-only) (#5839)
* feat: clean unused images only after 24hrs (local-only)

* fix test

* make optional for now
2022-11-06 19:41:14 +01:00
David Luzar
938ce241ff feat: refetch errored/pending images on collab room init load (#5833) 2022-11-05 15:55:14 +01:00
David Luzar
0228646507 fix: line editor points rendering below elements (#5781)
* fix: line editor points rendering below elements

* add test
2022-11-05 11:35:53 +01:00
Aakansha Doshi
25ea97d0f9 test: fix failing tests and API (#5823)
* tests: fix failing tests

* fix selection.test.tsx

* fix excalidraw.test.tsx and don't show image export when SaveAsImage is false in UIOptions.canvasActions

* more fixes

* require fake index db in setUp test to fix the tests

* fix regression
2022-11-04 18:22:21 +05:30
David Luzar
8d5d68e589 feat: stop deleting whole line when no point select in line editor (#5676)
* feat: stop deleting whole line when no point select in line editor

* Comments typo

Co-authored-by: DanielJGeiger <1852529+DanielJGeiger@users.noreply.github.com>
2022-11-02 14:52:32 +01:00
David Luzar
6c15d9948b fix: syncing 1-point lines to remote clients (#5677) 2022-11-02 14:39:12 +01:00
David Luzar
e8fba43cf6 fix: incorrectly selecting linear elements on creation while tool-locked (#5785) 2022-11-02 14:38:58 +01:00
Paul Yi
2e5c798c71 fix: Corrected typo in toggle theme shortcut (#5813) 2022-11-02 14:32:21 +01:00
David Luzar
8c298336fc fix: hide canvas-modifying UI in view mode (#5815)
* fix: hide canvas-modifying UI in view mode

* add class for better targeting

* fix missing `key`

* fix: useOutsideClick not working in view mode
2022-11-01 22:25:12 +01:00
David Luzar
7f91cdc0c9 fix: fix vertical/horizntal centering icons (#5812) 2022-11-01 18:39:31 +01:00
Barnabás Molnár
6334bd832f feat: editor redesign 🔥 (#5780)
* Placed eraser into shape switcher (top toolbar).
Redesigned top toolbar.

* Redesigned zoom and undo-redo buttons.

* Started redesigning left toolbar.

* Redesigned help dialog.

* Colour picker now somewhat in line with new design

* [WIP] Changed a bunch of icons.
TODO: organise new icons.

* [WIP] Organised a bunch of icons. Still some to do

* [WIP] Started working on hamburger menu.

* Fixed some bugs with hamburger menu.

* Menu and left toolbar positioning.

* Added some more items to hamburger menu.

* Changed some icons.

* Modal/dialog styling & bunch of fixes.

* Some more dialog improvements & fixes.

* Mobile menu changes.

* Menu can now be closed with outside click.

* Collab avatars and button changes.

* Icon sizing. Left toolbar positioning.

* Implemented welcome screen rendering logic.

* [WIP] Welcome screen content + design.

* Some more welcome screen content and design.

* Merge fixes.

* Tweaked icon set.

* Welcome screen darkmode fix.

* Content updates.

* Various small fixes & adjustments.
Moved language selection into menu.
Fixed some problematic icons.
Slightly moved encryption icon.

* Sidebar header redesign.

* Libraries content rendering logic + some styling.

* Somem more library sidebar styling.

* Publish library dialog styling.

* scroll-back-to-content btn styling

* ColorPicker positioning.

* Library button styling.

* ColorPicker positioning "fix".

* Misc adjustments.

* PenMode button changes.

* Trying to make mobile somewhat usable.

* Added a couple of icons.

* Added some shortcuts.

* Prevent welcome screen flickering.
Fix issue with welcome screen interactivity.
Don't show sidebar button when docked.

* Icon sizing on smaller screens.

* Sidebar styling changes.

* Alignment button... well... alignments.

* Fix inconsistent padding in left toolbar.

* HintViewer changes.

* Hamburger menu changes.

* Move encryption badge back to its original pos.

* Arrowhead changes.
Active state, colours + stronger shadow.

* Added new custom font.

* Fixed bug with library button not rendering.

* Fixed issue with lang selection colours.

* Add tooltips for undo, redo.

* Address some dark mode contrast issues.

* (Re)introduce counter for selectedItems in sidebar

* [WIP] Tweaked bounding box colour & padding.

* Dashed bounding box for remote clients.

* Some more bounding box tweaks.

* Removed docking animation for now...

* Address some RTL issues.

* Welcome screen responsiveness.

* use lighter selection color in dark mode & align naming

* use rounded corners for transform handles

* use lighter gray for welcomeScreen text in dark mode

* disable selection on dialog buttons

* change selection button icon

* fix library item width being flexible

* library: visually align spinner with first section heading

* lint

* fix scrollbar color in dark mode & make thinner

* adapt properties panel max-height

* add shrotcut label to save-to-current-file

* fix unrelated `useOutsideClick` firing for active modal

* add promo color to e+ menu item

* fix type

* lowered button size

* fix transform handles raidus not accounting for zoom

* attempt fix for excal logo on safari

* final fix for excal logo on safari

* fixing fhd resolution button sized

* remove TODO shortcut

* Collab related styling changes.
Expanding avatar list no longer offsets top toolbar.
Added active state & collaborator count badge for collab button.

* Tweaked collab button active colours.

* Added active style to collab btn in hamburger menu

* Remove unnecessary comment.

* Added back promo link for non (signed in) E+ users

* Go to E+ button added for signed in E+ users.

* Close menu & dropdown on modal close.

* tweak icons & fix rendering on smaller sizes [part one]

* align welcomeScreen icons with other UI

* switch icon resize mq to `device-width`

* disable welcomeScreen items `:hover` when selecting on canvas

* change selection box color and style

* reduce selection padding and fix group selection styling

* improve collab cursor styling

- make name borders round
- hide status when "active"
- remove black/gray colors

* add Twitter to hamburger menu

* align collab button

* add shortcut for image export dialog

* revert yarn.lock

* fix more tabler icons

* slightly better-looking penMode button

* change penMode button & tooltip

* revert hamburger menu icon

* align padding on lang picker & canvas bg

* updated robot txt to allow twitter bot and fb bot

* added new OG and tweaked the OG state

* add tooltip to collab button

* align style for scroll-to-content button

* fix pointer-events around toolbar

* fix decor arrow positioning and RTL

* fix welcomeScreen-item active state in dark mode

* change `load` button copy

* prevent shadow anim when opening a docked sidebar

* update E+ links ga params

* show redirect-to-eplus welcomeScreen subheading for signed-in users

* make more generic

* add ga for eplus redirect button

* change copy and icons for hamburger export buttons

* update snaps

* trim the username to account for trailing spaces

* tweaks around decor breakpoints

* fix linear element editor test

* remove .env change

* remove `it.only`

Co-authored-by: dwelle <luzar.david@gmail.com>
Co-authored-by: Maielo <maielo.mv@gmail.com>
Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
2022-11-01 17:29:58 +01:00
David Luzar
4d26993c8f chore: fix yarn.lock file (#5803)
* chore: fix yarn.lock file

* ts fix
2022-10-31 13:44:08 +01:00
zsviczian
1e69609ce4 fix: consistent use of ZOOM_STEP (#5801)
introduce MIN_ZOOM, consistent use of ZOOM_STEP
2022-10-31 06:23:05 +01:00
Alex Kim
f5379d1563 fix: multiple elements resizing regressions (#5586) 2022-10-29 13:01:38 +02:00
David Luzar
c8f6e3faa8 fix: restore text dimensions (#5432)
* fix: restore text dimensions

* fix tests

* update readme & changelog

* reduce API surface area by always refreshing dimensions for full `restore()`
2022-10-28 23:31:56 +02:00
Aakansha Doshi
36bf17cf59 fix: changelog typo (#5795)
* fix: changelog typo

* fix

* fix

* Empty-Commit
2022-10-27 20:43:03 +05:30
310 changed files with 24412 additions and 15972 deletions

View File

@@ -1,5 +1,6 @@
* *
!.env !.env.development
!.env.production
!.eslintrc.json !.eslintrc.json
!.npmrc !.npmrc
!.prettierrc !.prettierrc

View File

@@ -20,3 +20,5 @@ REACT_APP_DEV_ENABLE_SW=
# whether to disable live reload / HMR. Usuaully what you want to do when # whether to disable live reload / HMR. Usuaully what you want to do when
# debugging Service Workers. # debugging Service Workers.
REACT_APP_DEV_DISABLE_LIVE_RELOAD= REACT_APP_DEV_DISABLE_LIVE_RELOAD=
FAST_REFRESH=false

View File

@@ -2,7 +2,7 @@ name: Auto release excalidraw next
on: on:
push: push:
branches: branches:
- master - release
jobs: jobs:
Auto-release-excalidraw-next: Auto-release-excalidraw-next:

View File

@@ -3,7 +3,7 @@ name: Build Docker image
on: on:
push: push:
branches: branches:
- master - release
jobs: jobs:
build-docker: build-docker:

View File

@@ -3,7 +3,7 @@ name: Cancel previous runs
on: on:
push: push:
branches: branches:
- master - release
pull_request: pull_request:
jobs: jobs:

View File

@@ -3,7 +3,7 @@ name: Publish Docker
on: on:
push: push:
branches: branches:
- master - release
jobs: jobs:
publish-docker: publish-docker:

View File

@@ -3,7 +3,7 @@ name: New Sentry production release
on: on:
push: push:
branches: branches:
- master - release
jobs: jobs:
sentry: sentry:

View File

@@ -1,2 +1,2 @@
#!/bin/sh #!/bin/sh
yarn lint-staged # yarn lint-staged

View File

@@ -4692,9 +4692,9 @@ json-schema-traverse@^1.0.0:
integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==
json5@^2.1.2, json5@^2.2.1: json5@^2.1.2, json5@^2.2.1:
version "2.2.1" version "2.2.3"
resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.1.tgz#655d50ed1e6f95ad1a3caababd2b0efda10b395c" resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283"
integrity sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA== integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==
jsonfile@^6.0.1: jsonfile@^6.0.1:
version "6.1.0" version "6.1.0"
@@ -4755,9 +4755,9 @@ loader-runner@^4.2.0:
integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg== integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==
loader-utils@^2.0.0: loader-utils@^2.0.0:
version "2.0.2" version "2.0.4"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.2.tgz#d6e3b4fb81870721ae4e0868ab11dd638368c129" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c"
integrity sha512-TM57VeHptv569d/GKh6TAYdzKblwDNiumOdkFnejjD0XwTH87K90w3O7AiJRqdQoXygvi1VQTJTLGhJl7WqA7A== integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==
dependencies: dependencies:
big.js "^5.2.2" big.js "^5.2.2"
emojis-list "^3.0.0" emojis-list "^3.0.0"

View File

@@ -31,6 +31,7 @@
"@types/socket.io-client": "1.4.36", "@types/socket.io-client": "1.4.36",
"browser-fs-access": "0.29.1", "browser-fs-access": "0.29.1",
"clsx": "1.1.1", "clsx": "1.1.1",
"cross-env": "7.0.3",
"fake-indexeddb": "3.1.7", "fake-indexeddb": "3.1.7",
"firebase": "8.3.3", "firebase": "8.3.3",
"i18next-browser-languagedetector": "6.1.4", "i18next-browser-languagedetector": "6.1.4",
@@ -50,11 +51,24 @@
"pwacompat": "2.0.17", "pwacompat": "2.0.17",
"react": "18.2.0", "react": "18.2.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-scripts": "4.0.3", "react-scripts": "5.0.1",
"roughjs": "4.5.2", "roughjs": "4.5.2",
"sass": "1.51.0", "sass": "1.51.0",
"socket.io-client": "2.3.1", "socket.io-client": "4.5.4",
"typescript": "4.5.5" "tunnel-rat": "0.1.0",
"typescript": "4.9.4",
"workbox-background-sync": "^6.5.4",
"workbox-broadcast-update": "^6.5.4",
"workbox-cacheable-response": "^6.5.4",
"workbox-core": "^6.5.4",
"workbox-expiration": "^6.5.4",
"workbox-google-analytics": "^6.5.4",
"workbox-navigation-preload": "^6.5.4",
"workbox-precaching": "^6.5.4",
"workbox-range-requests": "^6.5.4",
"workbox-routing": "^6.5.4",
"workbox-strategies": "^6.5.4",
"workbox-streams": "^6.5.4"
}, },
"devDependencies": { "devDependencies": {
"@excalidraw/eslint-config": "1.0.0", "@excalidraw/eslint-config": "1.0.0",
@@ -67,6 +81,7 @@
"dotenv": "16.0.1", "dotenv": "16.0.1",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.5.0",
"eslint-plugin-prettier": "3.3.1", "eslint-plugin-prettier": "3.3.1",
"http-server": "14.1.1",
"husky": "7.0.4", "husky": "7.0.4",
"jest-canvas-mock": "2.4.0", "jest-canvas-mock": "2.4.0",
"lint-staged": "12.3.7", "lint-staged": "12.3.7",
@@ -74,9 +89,6 @@
"prettier": "2.6.2", "prettier": "2.6.2",
"rewire": "6.0.0" "rewire": "6.0.0"
}, },
"resolutions": {
"@typescript-eslint/typescript-estree": "5.10.2"
},
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
}, },
@@ -92,11 +104,10 @@
"private": true, "private": true,
"scripts": { "scripts": {
"build-node": "node ./scripts/build-node.js", "build-node": "node ./scripts/build-node.js",
"build:app:docker": "REACT_APP_DISABLE_SENTRY=true react-scripts build", "build:app:docker": "cross-env REACT_APP_DISABLE_SENTRY=true REACT_APP_DISABLE_TRACKING=true react-scripts build",
"build:app": "REACT_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA react-scripts build", "build:app": "cross-env REACT_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA react-scripts build",
"build:version": "node ./scripts/build-version.js", "build:version": "node ./scripts/build-version.js",
"build:prebuild": "node ./scripts/prebuild.js", "build": "yarn build:app && yarn build:version",
"build": "yarn build:prebuild && yarn build:app && yarn build:version",
"eject": "react-scripts eject", "eject": "react-scripts eject",
"fix:code": "yarn test:code --fix", "fix:code": "yarn test:code --fix",
"fix:other": "yarn prettier --write", "fix:other": "yarn prettier --write",
@@ -106,6 +117,7 @@
"prepare": "husky install", "prepare": "husky install",
"prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore", "prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore",
"start": "react-scripts start", "start": "react-scripts start",
"start:production": "npm run build && npx http-server build -a localhost -p 5001 -o",
"test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watchAll=false", "test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watchAll=false",
"test:app": "react-scripts test --passWithNoTests", "test:app": "react-scripts test --passWithNoTests",
"test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .", "test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .",

BIN
public/Assistant-Bold.woff2 Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -11,3 +11,28 @@
src: url("Cascadia.woff2"); src: url("Cascadia.woff2");
font-display: swap; font-display: swap;
} }
@font-face {
font-family: "Assistant";
src: url("Assistant-Regular.woff2");
font-display: swap;
font-weight: 400;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-Medium.woff2");
font-display: swap;
font-weight: 500;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-SemiBold.woff2");
font-display: swap;
font-weight: 600;
}
@font-face {
font-family: "Assistant";
src: url("Assistant-Bold.woff2");
font-display: swap;
font-weight: 700;
}

View File

@@ -8,49 +8,57 @@
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no"
/> />
<meta name="referrer" content="origin" /> <meta name="referrer" content="origin" />
<meta name="mobile-web-app-capable" content="yes" /> <meta name="mobile-web-app-capable" content="yes" />
<meta name="theme-color" content="#121212" />
<meta name="theme-color" content="#000" /> <!-- Primary Meta Tags -->
<meta
name="title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta
name="description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta name="image" content="https://excalidraw.com/og-general-v1.png" />
<!-- Open Graph / Facebook -->
<meta property="og:site_name" content="Excalidraw" />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://excalidraw.com" />
<meta
property="og:title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta property="og:image:alt" content="Excalidraw logo" />
<meta
property="og:description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta property="og:image" content="https://excalidraw.com/og-fb-v1.png" />
<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:site" content="@excalidraw" />
<meta property="twitter:url" content="https://excalidraw.com" />
<meta
property="twitter:title"
content="Excalidraw — Collaborative whiteboarding made easy"
/>
<meta
property="twitter:description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<meta
property="twitter:image"
content="https://excalidraw.com/og-twitter-v1.png"
/>
<!-- General tags --> <!-- General tags -->
<meta <meta
name="description" name="description"
content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them." content="Excalidraw is a virtual collaborative whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/> />
<meta name="image" content="og-image.png" />
<!-- OpenGraph tags -->
<meta property="og:url" content="https://excalidraw.com" />
<meta property="og:site_name" content="Excalidraw" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Excalidraw" />
<meta
property="og:description"
content="Excalidraw is a whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<!-- OG tags require an absolute url for images -->
<meta
property="og:image"
name="twitter:image"
content="https://excalidraw.com/og-image.png"
/>
<meta
property="og:image:secure_url"
name="twitter:image"
content="https://excalidraw.com/og-image.png"
/>
<meta property="og:image:width" content="1280" />
<meta property="og:image:height" content="669" />
<meta property="og:image:alt" content="Excalidraw logo with byline." />
<!-- Twitter Card tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Excalidraw" />
<meta
name="twitter:description"
content="Excalidraw is a whiteboard tool that lets you easily sketch diagrams that have a hand-drawn feel to them."
/>
<!-------------------------------------------------------------------------> <!------------------------------------------------------------------------->
<!-- to minimize white flash on load when user has dark mode enabled --> <!-- to minimize white flash on load when user has dark mode enabled -->
@@ -138,7 +146,8 @@
// setting this so that libraries installation reuses this window tab. // setting this so that libraries installation reuses this window tab.
window.name = "_excalidraw"; window.name = "_excalidraw";
</script> </script>
<% if (process.env.REACT_APP_GOOGLE_ANALYTICS_ID) { %> <% if (process.env.REACT_APP_DISABLE_TRACKING !== 'true' &&
process.env.REACT_APP_GOOGLE_ANALYTICS_ID) { %>
<script <script
async async
src="https://www.googletagmanager.com/gtag/js?id=%REACT_APP_GOOGLE_ANALYTICS_ID%" src="https://www.googletagmanager.com/gtag/js?id=%REACT_APP_GOOGLE_ANALYTICS_ID%"
@@ -158,9 +167,6 @@
body, body,
html { html {
margin: 0; margin: 0;
--ui-font: system-ui, BlinkMacSystemFont, -apple-system, Segoe UI,
Roboto, Helvetica, Arial, sans-serif;
font-family: var(--ui-font);
-webkit-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
width: 100%; width: 100%;

BIN
public/og-fb-v1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
public/og-general-v1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
public/og-twitter-v1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -1,3 +1,9 @@
User-agent: Twitterbot
Disallow:
User-agent: facebookexternalhit
Disallow:
user-agent: * user-agent: *
Allow: /$ Allow: /$
Disallow: / Disallow: /

View File

@@ -1,81 +0,0 @@
// eslint-disable-next-line no-restricted-globals
// eslint-disable-next-line no-unused-expressions
/* eslint-disable no-restricted-globals */
/* global importScripts, workbox */
/**
* Welcome to your Workbox-powered service worker!
*
* You'll need to register this file in your web app and you should
* disable HTTP caching for this file too.
* See https://goo.gl/nhQhGp
*
* The rest of the code is auto-generated. Please don't update this file
* directly; instead, make changes to your Workbox build configuration
* and re-run your build process.
* See https://goo.gl/2aRDsh
*/
// in dev, `process` is undefined because this file is not compiled until build
const IS_DEVELOPMENT =
typeof process === "undefined" || process.env.NODE_ENV !== "production";
if (IS_DEVELOPMENT) {
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js",
);
workbox.setConfig({
debug: true,
});
} else {
importScripts("/workbox/workbox-sw.js");
workbox.setConfig({
modulePathPrefix: "/workbox/",
});
}
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
workbox.core.clientsClaim();
if (!IS_DEVELOPMENT) {
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);
workbox.routing.registerNavigationRoute(
workbox.precaching.getCacheKeyForURL("./index.html"),
{
blacklist: [/^\/_/, /\/[^/?]+\.[^/]+$/],
},
);
}
// Cache relevant font files
workbox.routing.registerRoute(
new RegExp("/(fonts.css|.+.(ttf|woff2|otf))"),
new workbox.strategies.StaleWhileRevalidate({
cacheName: "fonts",
plugins: [new workbox.expiration.Plugin({ maxEntries: 10 })],
}),
);
self.addEventListener("fetch", (event) => {
if (
event.request.method === "POST" &&
event.request.url.endsWith("/web-share-target")
) {
return event.respondWith(
(async () => {
const formData = await event.request.formData();
const file = formData.get("file");
const webShareTargetCache = await caches.open("web-share-target");
await webShareTargetCache.put("shared-file", new Response(file));
return Response.redirect("/?web-share-target", 303);
})(),
);
}
});

View File

@@ -50,8 +50,8 @@ const crowdinMap = {
"lv-LV": "en-lv", "lv-LV": "en-lv",
"cs-CZ": "en-cs", "cs-CZ": "en-cs",
"kk-KZ": "en-kk", "kk-KZ": "en-kk",
"vi-vn": "en-vi", "vi-VN": "en-vi",
"mr-in": "en-mr", "mr-IN": "en-mr",
}; };
const flags = { const flags = {
@@ -120,6 +120,7 @@ const languages = {
"fa-IR": "فارسی", "fa-IR": "فارسی",
"fi-FI": "Suomi", "fi-FI": "Suomi",
"fr-FR": "Français", "fr-FR": "Français",
"gl-ES": "Galego",
"he-IL": "עברית", "he-IL": "עברית",
"hi-IN": "हिन्दी", "hi-IN": "हिन्दी",
"hu-HU": "Magyar", "hu-HU": "Magyar",
@@ -129,6 +130,7 @@ const languages = {
"kab-KAB": "Taqbaylit", "kab-KAB": "Taqbaylit",
"kk-KZ": "Қазақ тілі", "kk-KZ": "Қазақ тілі",
"ko-KR": "한국어", "ko-KR": "한국어",
"ku-TR": "Kurdî",
"lt-LT": "Lietuvių", "lt-LT": "Lietuvių",
"lv-LV": "Latviešu", "lv-LV": "Latviešu",
"my-MM": "Burmese", "my-MM": "Burmese",

View File

@@ -1,21 +0,0 @@
const fs = require("fs");
const path = require("path");
// for development purposes we want to have the service-worker.js file
// accessible from the public folder. On build though, we need to compile it
// and CRA expects that file to be in src/ folder.
const moveServiceWorkerScript = () => {
const oldPath = path.resolve(__dirname, "../public/service-worker.js");
const newPath = path.resolve(__dirname, "../src/service-worker.js");
fs.rename(oldPath, newPath, (error) => {
if (error) {
throw error;
}
console.info("public/service-worker.js moved to src/");
});
};
// -----------------------------------------------------------------------------
moveServiceWorkerScript();

View File

@@ -60,7 +60,7 @@ export const actionAlignTop = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<AlignTopIcon theme={appState.theme} />} icon={AlignTopIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignTop")}${getShortcutKey( title={`${t("labels.alignTop")}${getShortcutKey(
"CtrlOrCmd+Shift+Up", "CtrlOrCmd+Shift+Up",
@@ -90,7 +90,7 @@ export const actionAlignBottom = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<AlignBottomIcon theme={appState.theme} />} icon={AlignBottomIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignBottom")}${getShortcutKey( title={`${t("labels.alignBottom")}${getShortcutKey(
"CtrlOrCmd+Shift+Down", "CtrlOrCmd+Shift+Down",
@@ -120,7 +120,7 @@ export const actionAlignLeft = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<AlignLeftIcon theme={appState.theme} />} icon={AlignLeftIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignLeft")}${getShortcutKey( title={`${t("labels.alignLeft")}${getShortcutKey(
"CtrlOrCmd+Shift+Left", "CtrlOrCmd+Shift+Left",
@@ -151,7 +151,7 @@ export const actionAlignRight = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<AlignRightIcon theme={appState.theme} />} icon={AlignRightIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.alignRight")}${getShortcutKey( title={`${t("labels.alignRight")}${getShortcutKey(
"CtrlOrCmd+Shift+Right", "CtrlOrCmd+Shift+Right",
@@ -180,7 +180,7 @@ export const actionAlignVerticallyCentered = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<CenterVerticallyIcon theme={appState.theme} />} icon={CenterVerticallyIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={t("labels.centerVertically")} title={t("labels.centerVertically")}
aria-label={t("labels.centerVertically")} aria-label={t("labels.centerVertically")}
@@ -206,7 +206,7 @@ export const actionAlignHorizontallyCentered = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<CenterHorizontallyIcon theme={appState.theme} />} icon={CenterHorizontallyIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={t("labels.centerHorizontally")} title={t("labels.centerHorizontally")}
aria-label={t("labels.centerHorizontally")} aria-label={t("labels.centerHorizontally")}

View File

@@ -6,6 +6,10 @@ import {
measureText, measureText,
redrawTextBoundingBox, redrawTextBoundingBox,
} from "../element/textElement"; } from "../element/textElement";
import {
getOriginalContainerHeightFromCache,
resetOriginalContainerCache,
} from "../element/textWysiwyg";
import { import {
hasBoundTextElement, hasBoundTextElement,
isTextBindableContainer, isTextBindableContainer,
@@ -22,7 +26,7 @@ export const actionUnbindText = register({
name: "unbindText", name: "unbindText",
contextItemLabel: "labels.unbindText", contextItemLabel: "labels.unbindText",
trackEvent: { category: "element" }, trackEvent: { category: "element" },
contextItemPredicate: (elements, appState) => { predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState); const selectedElements = getSelectedElements(elements, appState);
return selectedElements.some((element) => hasBoundTextElement(element)); return selectedElements.some((element) => hasBoundTextElement(element));
}, },
@@ -38,6 +42,11 @@ export const actionUnbindText = register({
boundTextElement.originalText, boundTextElement.originalText,
getFontString(boundTextElement), getFontString(boundTextElement),
); );
const originalContainerHeight = getOriginalContainerHeightFromCache(
element.id,
);
resetOriginalContainerCache(element.id);
mutateElement(boundTextElement as ExcalidrawTextElement, { mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null, containerId: null,
width, width,
@@ -49,6 +58,9 @@ export const actionUnbindText = register({
boundElements: element.boundElements?.filter( boundElements: element.boundElements?.filter(
(ele) => ele.id !== boundTextElement.id, (ele) => ele.id !== boundTextElement.id,
), ),
height: originalContainerHeight
? originalContainerHeight
: element.height,
}); });
} }
}); });
@@ -64,7 +76,7 @@ export const actionBindText = register({
name: "bindText", name: "bindText",
contextItemLabel: "labels.bindText", contextItemLabel: "labels.bindText",
trackEvent: { category: "element" }, trackEvent: { category: "element" },
contextItemPredicate: (elements, appState) => { predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState); const selectedElements = getSelectedElements(elements, appState);
if (selectedElements.length === 2) { if (selectedElements.length === 2) {

View File

@@ -1,8 +1,7 @@
import { ColorPicker } from "../components/ColorPicker"; import { ColorPicker } from "../components/ColorPicker";
import { eraser, zoomIn, zoomOut } from "../components/icons"; import { ZoomInIcon, ZoomOutIcon } from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { DarkModeToggle } from "../components/DarkModeToggle"; import { CURSOR_TYPE, MIN_ZOOM, THEME, ZOOM_STEP } from "../constants";
import { THEME, ZOOM_STEP } from "../constants";
import { getCommonBounds, getNonDeletedElements } from "../element"; import { getCommonBounds, getNonDeletedElements } from "../element";
import { ExcalidrawElement } from "../element/types"; import { ExcalidrawElement } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
@@ -11,17 +10,25 @@ import { getNormalizedZoom, getSelectedElements } from "../scene";
import { centerScrollOn } from "../scene/scroll"; import { centerScrollOn } from "../scene/scroll";
import { getStateForZoom } from "../scene/zoom"; import { getStateForZoom } from "../scene/zoom";
import { AppState, NormalizedZoomValue } from "../types"; import { AppState, NormalizedZoomValue } from "../types";
import { getShortcutKey, updateActiveTool } from "../utils"; import { getShortcutKey, setCursor, updateActiveTool } from "../utils";
import { register } from "./register"; import { register } from "./register";
import { Tooltip } from "../components/Tooltip"; import { Tooltip } from "../components/Tooltip";
import { newElementWith } from "../element/mutateElement"; import { newElementWith } from "../element/mutateElement";
import { getDefaultAppState, isEraserActive } from "../appState"; import {
import ClearCanvas from "../components/ClearCanvas"; getDefaultAppState,
import clsx from "clsx"; isEraserActive,
isHandToolActive,
} from "../appState";
export const actionChangeViewBackgroundColor = register({ export const actionChangeViewBackgroundColor = register({
name: "changeViewBackgroundColor", name: "changeViewBackgroundColor",
trackEvent: false, trackEvent: false,
predicate: (elements, appState, props, app) => {
return (
!!app.props.UIOptions.canvasActions.changeViewBackgroundColor &&
!appState.viewModeEnabled
);
},
perform: (_, appState, value) => { perform: (_, appState, value) => {
return { return {
appState: { ...appState, ...value }, appState: { ...appState, ...value },
@@ -29,6 +36,7 @@ export const actionChangeViewBackgroundColor = register({
}; };
}, },
PanelComponent: ({ elements, appState, updateData }) => { PanelComponent: ({ elements, appState, updateData }) => {
// FIXME move me to src/components/mainMenu/DefaultItems.tsx
return ( return (
<div style={{ position: "relative" }}> <div style={{ position: "relative" }}>
<ColorPicker <ColorPicker
@@ -52,6 +60,12 @@ export const actionChangeViewBackgroundColor = register({
export const actionClearCanvas = register({ export const actionClearCanvas = register({
name: "clearCanvas", name: "clearCanvas",
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
predicate: (elements, appState, props, app) => {
return (
!!app.props.UIOptions.canvasActions.clearCanvas &&
!appState.viewModeEnabled
);
},
perform: (elements, appState, _, app) => { perform: (elements, appState, _, app) => {
app.imageCache.clear(); app.imageCache.clear();
return { return {
@@ -77,12 +91,11 @@ export const actionClearCanvas = register({
commitToHistory: true, commitToHistory: true,
}; };
}, },
PanelComponent: ({ updateData }) => <ClearCanvas onConfirm={updateData} />,
}); });
export const actionZoomIn = register({ export const actionZoomIn = register({
name: "zoomIn", name: "zoomIn",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -103,13 +116,13 @@ export const actionZoomIn = register({
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={zoomIn} className="zoom-in-button zoom-button"
icon={ZoomInIcon}
title={`${t("buttons.zoomIn")}${getShortcutKey("CtrlOrCmd++")}`} title={`${t("buttons.zoomIn")}${getShortcutKey("CtrlOrCmd++")}`}
aria-label={t("buttons.zoomIn")} aria-label={t("buttons.zoomIn")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
/> />
), ),
keyTest: (event) => keyTest: (event) =>
@@ -119,6 +132,7 @@ export const actionZoomIn = register({
export const actionZoomOut = register({ export const actionZoomOut = register({
name: "zoomOut", name: "zoomOut",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -139,13 +153,13 @@ export const actionZoomOut = register({
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={zoomOut} className="zoom-out-button zoom-button"
icon={ZoomOutIcon}
title={`${t("buttons.zoomOut")}${getShortcutKey("CtrlOrCmd+-")}`} title={`${t("buttons.zoomOut")}${getShortcutKey("CtrlOrCmd+-")}`}
aria-label={t("buttons.zoomOut")} aria-label={t("buttons.zoomOut")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
/> />
), ),
keyTest: (event) => keyTest: (event) =>
@@ -155,6 +169,7 @@ export const actionZoomOut = register({
export const actionResetZoom = register({ export const actionResetZoom = register({
name: "resetZoom", name: "resetZoom",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => { perform: (_elements, appState, _, app) => {
return { return {
@@ -176,13 +191,12 @@ export const actionResetZoom = register({
<Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}> <Tooltip label={t("buttons.resetZoom")} style={{ height: "100%" }}>
<ToolButton <ToolButton
type="button" type="button"
className="reset-zoom-button" className="reset-zoom-button zoom-button"
title={t("buttons.resetZoom")} title={t("buttons.resetZoom")}
aria-label={t("buttons.resetZoom")} aria-label={t("buttons.resetZoom")}
onClick={() => { onClick={() => {
updateData(null); updateData(null);
}} }}
size="small"
> >
{(appState.zoom.value * 100).toFixed(0)}% {(appState.zoom.value * 100).toFixed(0)}%
</ToolButton> </ToolButton>
@@ -206,7 +220,7 @@ const zoomValueToFitBoundsOnViewport = (
const zoomAdjustedToSteps = const zoomAdjustedToSteps =
Math.floor(smallestZoomValue / ZOOM_STEP) * ZOOM_STEP; Math.floor(smallestZoomValue / ZOOM_STEP) * ZOOM_STEP;
const clampedZoomValueToFitElements = Math.min( const clampedZoomValueToFitElements = Math.min(
Math.max(zoomAdjustedToSteps, ZOOM_STEP), Math.max(zoomAdjustedToSteps, MIN_ZOOM),
1, 1,
); );
return clampedZoomValueToFitElements as NormalizedZoomValue; return clampedZoomValueToFitElements as NormalizedZoomValue;
@@ -265,6 +279,7 @@ export const actionZoomToSelected = register({
export const actionZoomToFit = register({ export const actionZoomToFit = register({
name: "zoomToFit", name: "zoomToFit",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (elements, appState) => zoomToFitElements(elements, appState, false), perform: (elements, appState) => zoomToFitElements(elements, appState, false),
keyTest: (event) => keyTest: (event) =>
@@ -276,6 +291,7 @@ export const actionZoomToFit = register({
export const actionToggleTheme = register({ export const actionToggleTheme = register({
name: "toggleTheme", name: "toggleTheme",
viewMode: true,
trackEvent: { category: "canvas" }, trackEvent: { category: "canvas" },
perform: (_, appState, value) => { perform: (_, appState, value) => {
return { return {
@@ -287,28 +303,21 @@ export const actionToggleTheme = register({
commitToHistory: false, commitToHistory: false,
}; };
}, },
PanelComponent: ({ appState, updateData }) => (
<div style={{ marginInlineStart: "0.25rem" }}>
<DarkModeToggle
value={appState.theme}
onChange={(theme) => {
updateData(theme);
}}
/>
</div>
),
keyTest: (event) => event.altKey && event.shiftKey && event.code === CODES.D, keyTest: (event) => event.altKey && event.shiftKey && event.code === CODES.D,
predicate: (elements, appState, props, app) => {
return !!app.props.UIOptions.canvasActions.toggleTheme;
},
}); });
export const actionErase = register({ export const actionToggleEraserTool = register({
name: "eraser", name: "toggleEraserTool",
trackEvent: { category: "toolbar" }, trackEvent: { category: "toolbar" },
perform: (elements, appState) => { perform: (elements, appState) => {
let activeTool: AppState["activeTool"]; let activeTool: AppState["activeTool"];
if (isEraserActive(appState)) { if (isEraserActive(appState)) {
activeTool = updateActiveTool(appState, { activeTool = updateActiveTool(appState, {
...(appState.activeTool.lastActiveToolBeforeEraser || { ...(appState.activeTool.lastActiveTool || {
type: "selection", type: "selection",
}), }),
lastActiveToolBeforeEraser: null, lastActiveToolBeforeEraser: null,
@@ -331,17 +340,38 @@ export const actionErase = register({
}; };
}, },
keyTest: (event) => event.key === KEYS.E, keyTest: (event) => event.key === KEYS.E,
PanelComponent: ({ elements, appState, updateData, data }) => ( });
<ToolButton
type="button" export const actionToggleHandTool = register({
icon={eraser} name: "toggleHandTool",
className={clsx("eraser", { active: isEraserActive(appState) })} trackEvent: { category: "toolbar" },
title={`${t("toolBar.eraser")}-${getShortcutKey("E")}`} perform: (elements, appState, _, app) => {
aria-label={t("toolBar.eraser")} let activeTool: AppState["activeTool"];
onClick={() => {
updateData(null); if (isHandToolActive(appState)) {
}} activeTool = updateActiveTool(appState, {
size={data?.size || "medium"} ...(appState.activeTool.lastActiveTool || {
></ToolButton> type: "selection",
), }),
lastActiveToolBeforeEraser: null,
});
} else {
activeTool = updateActiveTool(appState, {
type: "hand",
lastActiveToolBeforeEraser: appState.activeTool,
});
setCursor(app.canvas, CURSOR_TYPE.GRAB);
}
return {
appState: {
...appState,
selectedElementIds: {},
selectedGroupIds: {},
activeTool,
},
commitToHistory: true,
};
},
keyTest: (event) => event.key === KEYS.H,
}); });

View File

@@ -3,6 +3,7 @@ import { register } from "./register";
import { import {
copyTextToSystemClipboard, copyTextToSystemClipboard,
copyToClipboard, copyToClipboard,
probablySupportsClipboardBlob,
probablySupportsClipboardWriteText, probablySupportsClipboardWriteText,
} from "../clipboard"; } from "../clipboard";
import { actionDeleteSelected } from "./actionDeleteSelected"; import { actionDeleteSelected } from "./actionDeleteSelected";
@@ -23,11 +24,31 @@ export const actionCopy = register({
commitToHistory: false, commitToHistory: false,
}; };
}, },
predicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.copy", contextItemLabel: "labels.copy",
// don't supply a shortcut since we handle this conditionally via onCopy event // don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined, keyTest: undefined,
}); });
export const actionPaste = register({
name: "paste",
trackEvent: { category: "element" },
perform: (elements: any, appStates: any, data, app) => {
app.pasteFromClipboard(null);
return {
commitToHistory: false,
};
},
predicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.paste",
// don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined,
});
export const actionCut = register({ export const actionCut = register({
name: "cut", name: "cut",
trackEvent: { category: "element" }, trackEvent: { category: "element" },
@@ -35,6 +56,9 @@ export const actionCut = register({
actionCopy.perform(elements, appState, data, app); actionCopy.perform(elements, appState, data, app);
return actionDeleteSelected.perform(elements, appState); return actionDeleteSelected.perform(elements, appState);
}, },
predicate: (elements, appState, appProps, app) => {
return app.device.isMobile && !!navigator.clipboard;
},
contextItemLabel: "labels.cut", contextItemLabel: "labels.cut",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X,
}); });
@@ -77,6 +101,9 @@ export const actionCopyAsSvg = register({
}; };
} }
}, },
predicate: (elements) => {
return probablySupportsClipboardWriteText && elements.length > 0;
},
contextItemLabel: "labels.copyAsSvg", contextItemLabel: "labels.copyAsSvg",
}); });
@@ -131,6 +158,9 @@ export const actionCopyAsPng = register({
}; };
} }
}, },
predicate: (elements) => {
return probablySupportsClipboardBlob && elements.length > 0;
},
contextItemLabel: "labels.copyAsPng", contextItemLabel: "labels.copyAsPng",
keyTest: (event) => event.code === CODES.C && event.altKey && event.shiftKey, keyTest: (event) => event.code === CODES.C && event.altKey && event.shiftKey,
}); });
@@ -158,7 +188,7 @@ export const copyText = register({
commitToHistory: false, commitToHistory: false,
}; };
}, },
contextItemPredicate: (elements, appState) => { predicate: (elements, appState) => {
return ( return (
probablySupportsClipboardWriteText && probablySupportsClipboardWriteText &&
getSelectedElements(elements, appState, true).some(isTextElement) getSelectedElements(elements, appState, true).some(isTextElement)

View File

@@ -1,7 +1,6 @@
import { isSomeElementSelected } from "../scene"; import { isSomeElementSelected } from "../scene";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { trash } from "../components/icons";
import { t } from "../i18n"; import { t } from "../i18n";
import { register } from "./register"; import { register } from "./register";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
@@ -13,6 +12,7 @@ import { LinearElementEditor } from "../element/linearElementEditor";
import { fixBindingsAfterDeletion } from "../element/binding"; import { fixBindingsAfterDeletion } from "../element/binding";
import { isBoundToContainer } from "../element/typeChecks"; import { isBoundToContainer } from "../element/typeChecks";
import { updateActiveTool } from "../utils"; import { updateActiveTool } from "../utils";
import { TrashIcon } from "../components/icons";
const deleteSelectedElements = ( const deleteSelectedElements = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
@@ -72,13 +72,22 @@ export const actionDeleteSelected = register({
if (!element) { if (!element) {
return false; return false;
} }
if ( // case: no point selected → do nothing, as deleting the whole element
// case: no point selected delete whole element // is most likely a mistake, where you wanted to delete a specific point
selectedPointsIndices == null || // but failed to select it (or you thought it's selected, while it was
// case: deleting last remaining point // only in a hover state)
element.points.length < 2 if (selectedPointsIndices == null) {
) { return false;
const nextElements = elements.filter((el) => el.id !== element.id); }
// case: deleting last remaining point
if (element.points.length < 2) {
const nextElements = elements.map((el) => {
if (el.id === element.id) {
return newElementWith(el, { isDeleted: true });
}
return el;
});
const nextAppState = handleGroupEditingState(appState, nextElements); const nextAppState = handleGroupEditingState(appState, nextElements);
return { return {
@@ -149,7 +158,7 @@ export const actionDeleteSelected = register({
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={trash} icon={TrashIcon}
title={t("labels.delete")} title={t("labels.delete")}
aria-label={t("labels.delete")} aria-label={t("labels.delete")}
onClick={() => updateData(null)} onClick={() => updateData(null)}

View File

@@ -56,7 +56,7 @@ export const distributeHorizontally = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<DistributeHorizontallyIcon theme={appState.theme} />} icon={DistributeHorizontallyIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.distributeHorizontally")}${getShortcutKey( title={`${t("labels.distributeHorizontally")}${getShortcutKey(
"Alt+H", "Alt+H",
@@ -86,7 +86,7 @@ export const distributeVertically = register({
<ToolButton <ToolButton
hidden={!enableActionGroup(elements, appState)} hidden={!enableActionGroup(elements, appState)}
type="button" type="button"
icon={<DistributeVerticallyIcon theme={appState.theme} />} icon={DistributeVerticallyIcon}
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.distributeVertically")}${getShortcutKey("Alt+V")}`} title={`${t("labels.distributeVertically")}${getShortcutKey("Alt+V")}`}
aria-label={t("labels.distributeVertically")} aria-label={t("labels.distributeVertically")}

View File

@@ -4,7 +4,6 @@ import { ExcalidrawElement } from "../element/types";
import { duplicateElement, getNonDeletedElements } from "../element"; import { duplicateElement, getNonDeletedElements } from "../element";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { clone } from "../components/icons";
import { t } from "../i18n"; import { t } from "../i18n";
import { arrayToMap, getShortcutKey } from "../utils"; import { arrayToMap, getShortcutKey } from "../utils";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
@@ -19,6 +18,7 @@ import { ActionResult } from "./types";
import { GRID_SIZE } from "../constants"; import { GRID_SIZE } from "../constants";
import { bindTextToShapeAfterDuplication } from "../element/textElement"; import { bindTextToShapeAfterDuplication } from "../element/textElement";
import { isBoundToContainer } from "../element/typeChecks"; import { isBoundToContainer } from "../element/typeChecks";
import { DuplicateIcon } from "../components/icons";
export const actionDuplicateSelection = register({ export const actionDuplicateSelection = register({
name: "duplicateSelection", name: "duplicateSelection",
@@ -49,7 +49,7 @@ export const actionDuplicateSelection = register({
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={clone} icon={DuplicateIcon}
title={`${t("labels.duplicateSelection")}${getShortcutKey( title={`${t("labels.duplicateSelection")}${getShortcutKey(
"CtrlOrCmd+D", "CtrlOrCmd+D",
)}`} )}`}

View File

@@ -1,7 +1,6 @@
import { load, questionCircle, saveAs } from "../components/icons"; import { questionCircle, saveAs } from "../components/icons";
import { ProjectName } from "../components/ProjectName"; import { ProjectName } from "../components/ProjectName";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import "../components/ToolIcon.scss";
import { Tooltip } from "../components/Tooltip"; import { Tooltip } from "../components/Tooltip";
import { DarkModeToggle } from "../components/DarkModeToggle"; import { DarkModeToggle } from "../components/DarkModeToggle";
import { loadFromJSON, saveAsJSON } from "../data"; import { loadFromJSON, saveAsJSON } from "../data";
@@ -15,11 +14,12 @@ import { getExportSize } from "../scene/export";
import { DEFAULT_EXPORT_PADDING, EXPORT_SCALES, THEME } from "../constants"; import { DEFAULT_EXPORT_PADDING, EXPORT_SCALES, THEME } from "../constants";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { getNonDeletedElements } from "../element"; import { getNonDeletedElements } from "../element";
import { ActiveFile } from "../components/ActiveFile";
import { isImageFileHandle } from "../data/blob"; import { isImageFileHandle } from "../data/blob";
import { nativeFileSystemSupported } from "../data/filesystem"; import { nativeFileSystemSupported } from "../data/filesystem";
import { Theme } from "../element/types"; import { Theme } from "../element/types";
import "../components/ToolIcon.scss";
export const actionChangeProjectName = register({ export const actionChangeProjectName = register({
name: "changeProjectName", name: "changeProjectName",
trackEvent: false, trackEvent: false,
@@ -131,6 +131,13 @@ export const actionChangeExportEmbedScene = register({
export const actionSaveToActiveFile = register({ export const actionSaveToActiveFile = register({
name: "saveToActiveFile", name: "saveToActiveFile",
trackEvent: { category: "export" }, trackEvent: { category: "export" },
predicate: (elements, appState, props, app) => {
return (
!!app.props.UIOptions.canvasActions.saveToActiveFile &&
!!appState.fileHandle &&
!appState.viewModeEnabled
);
},
perform: async (elements, appState, value, app) => { perform: async (elements, appState, value, app) => {
const fileHandleExists = !!appState.fileHandle; const fileHandleExists = !!appState.fileHandle;
@@ -167,16 +174,11 @@ export const actionSaveToActiveFile = register({
}, },
keyTest: (event) => keyTest: (event) =>
event.key === KEYS.S && event[KEYS.CTRL_OR_CMD] && !event.shiftKey, event.key === KEYS.S && event[KEYS.CTRL_OR_CMD] && !event.shiftKey,
PanelComponent: ({ updateData, appState }) => (
<ActiveFile
onSave={() => updateData(null)}
fileName={appState.fileHandle?.name}
/>
),
}); });
export const actionSaveFileToDisk = register({ export const actionSaveFileToDisk = register({
name: "saveFileToDisk", name: "saveFileToDisk",
viewMode: true,
trackEvent: { category: "export" }, trackEvent: { category: "export" },
perform: async (elements, appState, value, app) => { perform: async (elements, appState, value, app) => {
try { try {
@@ -217,6 +219,11 @@ export const actionSaveFileToDisk = register({
export const actionLoadScene = register({ export const actionLoadScene = register({
name: "loadScene", name: "loadScene",
trackEvent: { category: "export" }, trackEvent: { category: "export" },
predicate: (elements, appState, props, app) => {
return (
!!app.props.UIOptions.canvasActions.loadScene && !appState.viewModeEnabled
);
},
perform: async (elements, appState, _, app) => { perform: async (elements, appState, _, app) => {
try { try {
const { const {
@@ -244,17 +251,6 @@ export const actionLoadScene = register({
} }
}, },
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.O, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.O,
PanelComponent: ({ updateData }) => (
<ToolButton
type="button"
icon={load}
title={t("buttons.load")}
aria-label={t("buttons.load")}
showAriaLabel={useDevice().isMobile}
onClick={updateData}
data-testid="load-button"
/>
),
}); });
export const actionExportWithDarkMode = register({ export const actionExportWithDarkMode = register({

View File

@@ -145,7 +145,7 @@ export const actionFinalize = register({
let activeTool: AppState["activeTool"]; let activeTool: AppState["activeTool"];
if (appState.activeTool.type === "eraser") { if (appState.activeTool.type === "eraser") {
activeTool = updateActiveTool(appState, { activeTool = updateActiveTool(appState, {
...(appState.activeTool.lastActiveToolBeforeEraser || { ...(appState.activeTool.lastActiveTool || {
type: "selection", type: "selection",
}), }),
lastActiveToolBeforeEraser: null, lastActiveToolBeforeEraser: null,

View File

@@ -14,6 +14,7 @@ import {
} from "../element/bounds"; } from "../element/bounds";
import { isLinearElement } from "../element/typeChecks"; import { isLinearElement } from "../element/typeChecks";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
import { KEYS } from "../keys";
const enableActionFlipHorizontal = ( const enableActionFlipHorizontal = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
@@ -49,7 +50,7 @@ export const actionFlipHorizontal = register({
}, },
keyTest: (event) => event.shiftKey && event.code === "KeyH", keyTest: (event) => event.shiftKey && event.code === "KeyH",
contextItemLabel: "labels.flipHorizontal", contextItemLabel: "labels.flipHorizontal",
contextItemPredicate: (elements, appState) => predicate: (elements, appState) =>
enableActionFlipHorizontal(elements, appState), enableActionFlipHorizontal(elements, appState),
}); });
@@ -63,9 +64,10 @@ export const actionFlipVertical = register({
commitToHistory: true, commitToHistory: true,
}; };
}, },
keyTest: (event) => event.shiftKey && event.code === "KeyV", keyTest: (event) =>
event.shiftKey && event.code === "KeyV" && !event[KEYS.CTRL_OR_CMD],
contextItemLabel: "labels.flipVertical", contextItemLabel: "labels.flipVertical",
contextItemPredicate: (elements, appState) => predicate: (elements, appState) =>
enableActionFlipVertical(elements, appState), enableActionFlipVertical(elements, appState),
}); });
@@ -151,11 +153,7 @@ const flipElement = (
let initialPointsCoords; let initialPointsCoords;
if (isLinearElement(element)) { if (isLinearElement(element)) {
initialPointsCoords = getElementPointsCoords( initialPointsCoords = getElementPointsCoords(element, element.points);
element,
element.points,
element.strokeSharpness,
);
} }
const initialElementAbsoluteCoords = getElementAbsoluteCoords(element); const initialElementAbsoluteCoords = getElementAbsoluteCoords(element);
@@ -213,11 +211,7 @@ const flipElement = (
// Adjusting origin because when a beizer curve path exceeds min/max points it offsets the origin. // Adjusting origin because when a beizer curve path exceeds min/max points it offsets the origin.
// There's still room for improvement since when the line roughness is > 1 // There's still room for improvement since when the line roughness is > 1
// we still have a small offset of the origin when fliipping the element. // we still have a small offset of the origin when fliipping the element.
const finalPointsCoords = getElementPointsCoords( const finalPointsCoords = getElementPointsCoords(element, element.points);
element,
element.points,
element.strokeSharpness,
);
const topLeftCoordsDiff = initialPointsCoords[0] - finalPointsCoords[0]; const topLeftCoordsDiff = initialPointsCoords[0] - finalPointsCoords[0];
const topRightCoordDiff = initialPointsCoords[2] - finalPointsCoords[2]; const topRightCoordDiff = initialPointsCoords[2] - finalPointsCoords[2];

View File

@@ -129,8 +129,7 @@ export const actionGroup = register({
}; };
}, },
contextItemLabel: "labels.group", contextItemLabel: "labels.group",
contextItemPredicate: (elements, appState) => predicate: (elements, appState) => enableActionGroup(elements, appState),
enableActionGroup(elements, appState),
keyTest: (event) => keyTest: (event) =>
!event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.key === KEYS.G, !event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.key === KEYS.G,
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
@@ -193,8 +192,7 @@ export const actionUngroup = register({
event[KEYS.CTRL_OR_CMD] && event[KEYS.CTRL_OR_CMD] &&
event.key === KEYS.G.toUpperCase(), event.key === KEYS.G.toUpperCase(),
contextItemLabel: "labels.ungroup", contextItemLabel: "labels.ungroup",
contextItemPredicate: (elements, appState) => predicate: (elements, appState) => getSelectedGroupIds(appState).length > 0,
getSelectedGroupIds(appState).length > 0,
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton <ToolButton

View File

@@ -1,14 +1,15 @@
import { Action, ActionResult } from "./types"; import { Action, ActionResult } from "./types";
import { undo, redo } from "../components/icons"; import { UndoIcon, RedoIcon } from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n"; import { t } from "../i18n";
import History, { HistoryEntry } from "../history"; 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 { KEYS } from "../keys";
import { newElementWith } from "../element/mutateElement"; import { newElementWith } from "../element/mutateElement";
import { fixBindingsAfterDeletion } from "../element/binding"; import { fixBindingsAfterDeletion } from "../element/binding";
import { arrayToMap } from "../utils"; import { arrayToMap } from "../utils";
import { isWindows } from "../constants";
const writeData = ( const writeData = (
prevElements: readonly ExcalidrawElement[], prevElements: readonly ExcalidrawElement[],
@@ -72,7 +73,7 @@ export const createUndoAction: ActionCreator = (history) => ({
PanelComponent: ({ updateData, data }) => ( PanelComponent: ({ updateData, data }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={undo} icon={UndoIcon}
aria-label={t("buttons.undo")} aria-label={t("buttons.undo")}
onClick={updateData} onClick={updateData}
size={data?.size || "medium"} size={data?.size || "medium"}
@@ -94,7 +95,7 @@ export const createRedoAction: ActionCreator = (history) => ({
PanelComponent: ({ updateData, data }) => ( PanelComponent: ({ updateData, data }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={redo} icon={RedoIcon}
aria-label={t("buttons.redo")} aria-label={t("buttons.redo")}
onClick={updateData} onClick={updateData}
size={data?.size || "medium"} size={data?.size || "medium"}

View File

@@ -10,7 +10,7 @@ export const actionToggleLinearEditor = register({
trackEvent: { trackEvent: {
category: "element", category: "element",
}, },
contextItemPredicate: (elements, appState) => { predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState); const selectedElements = getSelectedElements(elements, appState);
if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) { if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
return true; return true;

View File

@@ -1,11 +1,10 @@
import { menu, palette } from "../components/icons"; import { HamburgerMenuIcon, palette } from "../components/icons";
import { ToolButton } from "../components/ToolButton"; import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n"; import { t } from "../i18n";
import { showSelectedShapeActions, getNonDeletedElements } from "../element"; import { showSelectedShapeActions, getNonDeletedElements } from "../element";
import { register } from "./register"; import { register } from "./register";
import { allowFullScreen, exitFullScreen, isFullScreen } from "../utils"; import { allowFullScreen, exitFullScreen, isFullScreen } from "../utils";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { HelpIcon } from "../components/HelpIcon";
export const actionToggleCanvasMenu = register({ export const actionToggleCanvasMenu = register({
name: "toggleCanvasMenu", name: "toggleCanvasMenu",
@@ -20,7 +19,7 @@ export const actionToggleCanvasMenu = register({
PanelComponent: ({ appState, updateData }) => ( PanelComponent: ({ appState, updateData }) => (
<ToolButton <ToolButton
type="button" type="button"
icon={menu} icon={HamburgerMenuIcon}
aria-label={t("buttons.menu")} aria-label={t("buttons.menu")}
onClick={updateData} onClick={updateData}
selected={appState.openMenu === "canvas"} selected={appState.openMenu === "canvas"}
@@ -55,6 +54,7 @@ export const actionToggleEditMenu = register({
export const actionFullScreen = register({ export const actionFullScreen = register({
name: "toggleFullScreen", name: "toggleFullScreen",
viewMode: true,
trackEvent: { category: "canvas", predicate: (appState) => !isFullScreen() }, trackEvent: { category: "canvas", predicate: (appState) => !isFullScreen() },
perform: () => { perform: () => {
if (!isFullScreen()) { if (!isFullScreen()) {
@@ -72,21 +72,19 @@ export const actionFullScreen = register({
export const actionShortcuts = register({ export const actionShortcuts = register({
name: "toggleShortcuts", name: "toggleShortcuts",
viewMode: true,
trackEvent: { category: "menu", action: "toggleHelpDialog" }, trackEvent: { category: "menu", action: "toggleHelpDialog" },
perform: (_elements, appState, _, { focusContainer }) => { perform: (_elements, appState, _, { focusContainer }) => {
if (appState.showHelpDialog) { if (appState.openDialog === "help") {
focusContainer(); focusContainer();
} }
return { return {
appState: { appState: {
...appState, ...appState,
showHelpDialog: !appState.showHelpDialog, openDialog: appState.openDialog === "help" ? null : "help",
}, },
commitToHistory: false, commitToHistory: false,
}; };
}, },
PanelComponent: ({ updateData }) => (
<HelpIcon title={t("helpDialog.title")} onClick={updateData} />
),
keyTest: (event) => event.key === KEYS.QUESTION_MARK, keyTest: (event) => event.key === KEYS.QUESTION_MARK,
}); });

View File

@@ -6,6 +6,7 @@ import { register } from "./register";
export const actionGoToCollaborator = register({ export const actionGoToCollaborator = register({
name: "goToCollaborator", name: "goToCollaborator",
viewMode: true,
trackEvent: { category: "collab" }, trackEvent: { category: "collab" },
perform: (_elements, appState, value) => { perform: (_elements, appState, value) => {
const point = value as Collaborator["pointer"]; const point = value as Collaborator["pointer"];

View File

@@ -2,42 +2,47 @@ import { AppState } from "../../src/types";
import { ButtonIconSelect } from "../components/ButtonIconSelect"; import { ButtonIconSelect } from "../components/ButtonIconSelect";
import { ColorPicker } from "../components/ColorPicker"; import { ColorPicker } from "../components/ColorPicker";
import { IconPicker } from "../components/IconPicker"; import { IconPicker } from "../components/IconPicker";
// TODO barnabasmolnar/editor-redesign
// TextAlignTopIcon, TextAlignBottomIcon,TextAlignMiddleIcon,
// ArrowHead icons
import { import {
ArrowheadArrowIcon, ArrowheadArrowIcon,
ArrowheadBarIcon, ArrowheadBarIcon,
ArrowheadDotIcon, ArrowheadDotIcon,
ArrowheadTriangleIcon, ArrowheadTriangleIcon,
ArrowheadNoneIcon, ArrowheadNoneIcon,
EdgeRoundIcon,
EdgeSharpIcon,
FillCrossHatchIcon,
FillHachureIcon,
FillSolidIcon,
FontFamilyCodeIcon,
FontFamilyHandDrawnIcon,
FontFamilyNormalIcon,
FontSizeExtraLargeIcon,
FontSizeLargeIcon,
FontSizeMediumIcon,
FontSizeSmallIcon,
SloppinessArchitectIcon,
SloppinessArtistIcon,
SloppinessCartoonistIcon,
StrokeStyleDashedIcon, StrokeStyleDashedIcon,
StrokeStyleDottedIcon, StrokeStyleDottedIcon,
StrokeStyleSolidIcon,
StrokeWidthIcon,
TextAlignCenterIcon,
TextAlignLeftIcon,
TextAlignRightIcon,
TextAlignTopIcon, TextAlignTopIcon,
TextAlignBottomIcon, TextAlignBottomIcon,
TextAlignMiddleIcon, TextAlignMiddleIcon,
FillHachureIcon,
FillCrossHatchIcon,
FillSolidIcon,
SloppinessArchitectIcon,
SloppinessArtistIcon,
SloppinessCartoonistIcon,
StrokeWidthBaseIcon,
StrokeWidthBoldIcon,
StrokeWidthExtraBoldIcon,
FontSizeSmallIcon,
FontSizeMediumIcon,
FontSizeLargeIcon,
FontSizeExtraLargeIcon,
EdgeSharpIcon,
EdgeRoundIcon,
FreedrawIcon,
FontFamilyNormalIcon,
FontFamilyCodeIcon,
TextAlignLeftIcon,
TextAlignCenterIcon,
TextAlignRightIcon,
} from "../components/icons"; } from "../components/icons";
import { import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
FONT_FAMILY, FONT_FAMILY,
ROUNDNESS,
VERTICAL_ALIGN, VERTICAL_ALIGN,
} from "../constants"; } from "../constants";
import { import {
@@ -53,7 +58,7 @@ import {
import { import {
isBoundToContainer, isBoundToContainer,
isLinearElement, isLinearElement,
isLinearElementType, isUsingAdaptiveRadius,
} from "../element/typeChecks"; } from "../element/typeChecks";
import { import {
Arrowhead, Arrowhead,
@@ -68,7 +73,7 @@ import { getLanguage, t } from "../i18n";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { randomInteger } from "../random"; import { randomInteger } from "../random";
import { import {
canChangeSharpness, canChangeRoundness,
canHaveArrowheads, canHaveArrowheads,
getCommonAttributeOfSelectedElements, getCommonAttributeOfSelectedElements,
getSelectedElements, getSelectedElements,
@@ -307,17 +312,17 @@ export const actionChangeFillStyle = register({
{ {
value: "hachure", value: "hachure",
text: t("labels.hachure"), text: t("labels.hachure"),
icon: <FillHachureIcon theme={appState.theme} />, icon: FillHachureIcon,
}, },
{ {
value: "cross-hatch", value: "cross-hatch",
text: t("labels.crossHatch"), text: t("labels.crossHatch"),
icon: <FillCrossHatchIcon theme={appState.theme} />, icon: FillCrossHatchIcon,
}, },
{ {
value: "solid", value: "solid",
text: t("labels.solid"), text: t("labels.solid"),
icon: <FillSolidIcon theme={appState.theme} />, icon: FillSolidIcon,
}, },
]} ]}
group="fill" group="fill"
@@ -358,17 +363,17 @@ export const actionChangeStrokeWidth = register({
{ {
value: 1, value: 1,
text: t("labels.thin"), text: t("labels.thin"),
icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={2} />, icon: StrokeWidthBaseIcon,
}, },
{ {
value: 2, value: 2,
text: t("labels.bold"), text: t("labels.bold"),
icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={6} />, icon: StrokeWidthBoldIcon,
}, },
{ {
value: 4, value: 4,
text: t("labels.extraBold"), text: t("labels.extraBold"),
icon: <StrokeWidthIcon theme={appState.theme} strokeWidth={10} />, icon: StrokeWidthExtraBoldIcon,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -407,17 +412,17 @@ export const actionChangeSloppiness = register({
{ {
value: 0, value: 0,
text: t("labels.architect"), text: t("labels.architect"),
icon: <SloppinessArchitectIcon theme={appState.theme} />, icon: SloppinessArchitectIcon,
}, },
{ {
value: 1, value: 1,
text: t("labels.artist"), text: t("labels.artist"),
icon: <SloppinessArtistIcon theme={appState.theme} />, icon: SloppinessArtistIcon,
}, },
{ {
value: 2, value: 2,
text: t("labels.cartoonist"), text: t("labels.cartoonist"),
icon: <SloppinessCartoonistIcon theme={appState.theme} />, icon: SloppinessCartoonistIcon,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -455,17 +460,17 @@ export const actionChangeStrokeStyle = register({
{ {
value: "solid", value: "solid",
text: t("labels.strokeStyle_solid"), text: t("labels.strokeStyle_solid"),
icon: <StrokeStyleSolidIcon theme={appState.theme} />, icon: StrokeWidthBaseIcon,
}, },
{ {
value: "dashed", value: "dashed",
text: t("labels.strokeStyle_dashed"), text: t("labels.strokeStyle_dashed"),
icon: <StrokeStyleDashedIcon theme={appState.theme} />, icon: StrokeStyleDashedIcon,
}, },
{ {
value: "dotted", value: "dotted",
text: t("labels.strokeStyle_dotted"), text: t("labels.strokeStyle_dotted"),
icon: <StrokeStyleDottedIcon theme={appState.theme} />, icon: StrokeStyleDottedIcon,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -535,25 +540,25 @@ export const actionChangeFontSize = register({
{ {
value: 16, value: 16,
text: t("labels.small"), text: t("labels.small"),
icon: <FontSizeSmallIcon theme={appState.theme} />, icon: FontSizeSmallIcon,
testId: "fontSize-small", testId: "fontSize-small",
}, },
{ {
value: 20, value: 20,
text: t("labels.medium"), text: t("labels.medium"),
icon: <FontSizeMediumIcon theme={appState.theme} />, icon: FontSizeMediumIcon,
testId: "fontSize-medium", testId: "fontSize-medium",
}, },
{ {
value: 28, value: 28,
text: t("labels.large"), text: t("labels.large"),
icon: <FontSizeLargeIcon theme={appState.theme} />, icon: FontSizeLargeIcon,
testId: "fontSize-large", testId: "fontSize-large",
}, },
{ {
value: 36, value: 36,
text: t("labels.veryLarge"), text: t("labels.veryLarge"),
icon: <FontSizeExtraLargeIcon theme={appState.theme} />, icon: FontSizeExtraLargeIcon,
testId: "fontSize-veryLarge", testId: "fontSize-veryLarge",
}, },
]} ]}
@@ -658,17 +663,17 @@ export const actionChangeFontFamily = register({
{ {
value: FONT_FAMILY.Virgil, value: FONT_FAMILY.Virgil,
text: t("labels.handDrawn"), text: t("labels.handDrawn"),
icon: <FontFamilyHandDrawnIcon theme={appState.theme} />, icon: FreedrawIcon,
}, },
{ {
value: FONT_FAMILY.Helvetica, value: FONT_FAMILY.Helvetica,
text: t("labels.normal"), text: t("labels.normal"),
icon: <FontFamilyNormalIcon theme={appState.theme} />, icon: FontFamilyNormalIcon,
}, },
{ {
value: FONT_FAMILY.Cascadia, value: FONT_FAMILY.Cascadia,
text: t("labels.code"), text: t("labels.code"),
icon: <FontFamilyCodeIcon theme={appState.theme} />, icon: FontFamilyCodeIcon,
}, },
]; ];
@@ -739,17 +744,17 @@ export const actionChangeTextAlign = register({
{ {
value: "left", value: "left",
text: t("labels.left"), text: t("labels.left"),
icon: <TextAlignLeftIcon theme={appState.theme} />, icon: TextAlignLeftIcon,
}, },
{ {
value: "center", value: "center",
text: t("labels.center"), text: t("labels.center"),
icon: <TextAlignCenterIcon theme={appState.theme} />, icon: TextAlignCenterIcon,
}, },
{ {
value: "right", value: "right",
text: t("labels.right"), text: t("labels.right"),
icon: <TextAlignRightIcon theme={appState.theme} />, icon: TextAlignRightIcon,
}, },
]} ]}
value={getFormValue( value={getFormValue(
@@ -812,16 +817,19 @@ export const actionChangeVerticalAlign = register({
value: VERTICAL_ALIGN.TOP, value: VERTICAL_ALIGN.TOP,
text: t("labels.alignTop"), text: t("labels.alignTop"),
icon: <TextAlignTopIcon theme={appState.theme} />, icon: <TextAlignTopIcon theme={appState.theme} />,
testId: "align-top",
}, },
{ {
value: VERTICAL_ALIGN.MIDDLE, value: VERTICAL_ALIGN.MIDDLE,
text: t("labels.centerVertically"), text: t("labels.centerVertically"),
icon: <TextAlignMiddleIcon theme={appState.theme} />, icon: <TextAlignMiddleIcon theme={appState.theme} />,
testId: "align-middle",
}, },
{ {
value: VERTICAL_ALIGN.BOTTOM, value: VERTICAL_ALIGN.BOTTOM,
text: t("labels.alignBottom"), text: t("labels.alignBottom"),
icon: <TextAlignBottomIcon theme={appState.theme} />, icon: <TextAlignBottomIcon theme={appState.theme} />,
testId: "align-bottom",
}, },
]} ]}
value={getFormValue(elements, appState, (element) => { value={getFormValue(elements, appState, (element) => {
@@ -841,69 +849,71 @@ export const actionChangeVerticalAlign = register({
}, },
}); });
export const actionChangeSharpness = register({ export const actionChangeRoundness = register({
name: "changeSharpness", name: "changeRoundness",
trackEvent: false, trackEvent: false,
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
const targetElements = getTargetElements(
getNonDeletedElements(elements),
appState,
);
const shouldUpdateForNonLinearElements = targetElements.length
? targetElements.every((el) => !isLinearElement(el))
: !isLinearElementType(appState.activeTool.type);
const shouldUpdateForLinearElements = targetElements.length
? targetElements.every(isLinearElement)
: isLinearElementType(appState.activeTool.type);
return { return {
elements: changeProperty(elements, appState, (el) => elements: changeProperty(elements, appState, (el) =>
newElementWith(el, { newElementWith(el, {
strokeSharpness: value, roundness:
value === "round"
? {
type: isUsingAdaptiveRadius(el.type)
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
}), }),
), ),
appState: { appState: {
...appState, ...appState,
currentItemStrokeSharpness: shouldUpdateForNonLinearElements currentItemRoundness: value,
? value
: appState.currentItemStrokeSharpness,
currentItemLinearStrokeSharpness: shouldUpdateForLinearElements
? value
: appState.currentItemLinearStrokeSharpness,
}, },
commitToHistory: true, commitToHistory: true,
}; };
}, },
PanelComponent: ({ elements, appState, updateData }) => ( PanelComponent: ({ elements, appState, updateData }) => {
<fieldset> const targetElements = getTargetElements(
<legend>{t("labels.edges")}</legend> getNonDeletedElements(elements),
<ButtonIconSelect appState,
group="edges" );
options={[
{ const hasLegacyRoundness = targetElements.some(
value: "sharp", (el) => el.roundness?.type === ROUNDNESS.LEGACY,
text: t("labels.sharp"), );
icon: <EdgeSharpIcon theme={appState.theme} />,
}, return (
{ <fieldset>
value: "round", <legend>{t("labels.edges")}</legend>
text: t("labels.round"), <ButtonIconSelect
icon: <EdgeRoundIcon theme={appState.theme} />, group="edges"
}, options={[
]} {
value={getFormValue( value: "sharp",
elements, text: t("labels.sharp"),
appState, icon: EdgeSharpIcon,
(element) => element.strokeSharpness, },
(canChangeSharpness(appState.activeTool.type) && {
(isLinearElementType(appState.activeTool.type) value: "round",
? appState.currentItemLinearStrokeSharpness text: t("labels.round"),
: appState.currentItemStrokeSharpness)) || icon: EdgeRoundIcon,
null, },
)} ]}
onChange={(value) => updateData(value)} value={getFormValue(
/> elements,
</fieldset> appState,
), (element) =>
hasLegacyRoundness ? null : element.roundness ? "round" : "sharp",
(canChangeRoundness(appState.activeTool.type) &&
appState.currentItemRoundness) ||
null,
)}
onChange={(value) => updateData(value)}
/>
</fieldset>
);
},
}); });
export const actionChangeArrowhead = register({ export const actionChangeArrowhead = register({
@@ -949,42 +959,38 @@ export const actionChangeArrowhead = register({
return ( return (
<fieldset> <fieldset>
<legend>{t("labels.arrowheads")}</legend> <legend>{t("labels.arrowheads")}</legend>
<div className="iconSelectList"> <div className="iconSelectList buttonList">
<IconPicker <IconPicker
label="arrowhead_start" label="arrowhead_start"
options={[ options={[
{ {
value: null, value: null,
text: t("labels.arrowhead_none"), text: t("labels.arrowhead_none"),
icon: <ArrowheadNoneIcon theme={appState.theme} />, icon: ArrowheadNoneIcon,
keyBinding: "q", keyBinding: "q",
}, },
{ {
value: "arrow", value: "arrow",
text: t("labels.arrowhead_arrow"), text: t("labels.arrowhead_arrow"),
icon: ( icon: <ArrowheadArrowIcon flip={!isRTL} />,
<ArrowheadArrowIcon theme={appState.theme} flip={!isRTL} />
),
keyBinding: "w", keyBinding: "w",
}, },
{ {
value: "bar", value: "bar",
text: t("labels.arrowhead_bar"), text: t("labels.arrowhead_bar"),
icon: <ArrowheadBarIcon theme={appState.theme} flip={!isRTL} />, icon: <ArrowheadBarIcon flip={!isRTL} />,
keyBinding: "e", keyBinding: "e",
}, },
{ {
value: "dot", value: "dot",
text: t("labels.arrowhead_dot"), text: t("labels.arrowhead_dot"),
icon: <ArrowheadDotIcon theme={appState.theme} flip={!isRTL} />, icon: <ArrowheadDotIcon flip={!isRTL} />,
keyBinding: "r", keyBinding: "r",
}, },
{ {
value: "triangle", value: "triangle",
text: t("labels.arrowhead_triangle"), text: t("labels.arrowhead_triangle"),
icon: ( icon: <ArrowheadTriangleIcon flip={!isRTL} />,
<ArrowheadTriangleIcon theme={appState.theme} flip={!isRTL} />
),
keyBinding: "t", keyBinding: "t",
}, },
]} ]}
@@ -1007,34 +1013,30 @@ export const actionChangeArrowhead = register({
value: null, value: null,
text: t("labels.arrowhead_none"), text: t("labels.arrowhead_none"),
keyBinding: "q", keyBinding: "q",
icon: <ArrowheadNoneIcon theme={appState.theme} />, icon: ArrowheadNoneIcon,
}, },
{ {
value: "arrow", value: "arrow",
text: t("labels.arrowhead_arrow"), text: t("labels.arrowhead_arrow"),
keyBinding: "w", keyBinding: "w",
icon: ( icon: <ArrowheadArrowIcon flip={isRTL} />,
<ArrowheadArrowIcon theme={appState.theme} flip={isRTL} />
),
}, },
{ {
value: "bar", value: "bar",
text: t("labels.arrowhead_bar"), text: t("labels.arrowhead_bar"),
keyBinding: "e", keyBinding: "e",
icon: <ArrowheadBarIcon theme={appState.theme} flip={isRTL} />, icon: <ArrowheadBarIcon flip={isRTL} />,
}, },
{ {
value: "dot", value: "dot",
text: t("labels.arrowhead_dot"), text: t("labels.arrowhead_dot"),
keyBinding: "r", keyBinding: "r",
icon: <ArrowheadDotIcon theme={appState.theme} flip={isRTL} />, icon: <ArrowheadDotIcon flip={isRTL} />,
}, },
{ {
value: "triangle", value: "triangle",
text: t("labels.arrowhead_triangle"), text: t("labels.arrowhead_triangle"),
icon: ( icon: <ArrowheadTriangleIcon flip={isRTL} />,
<ArrowheadTriangleIcon theme={appState.theme} flip={isRTL} />
),
keyBinding: "t", keyBinding: "t",
}, },
]} ]}

View File

@@ -13,7 +13,11 @@ import {
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
} from "../constants"; } from "../constants";
import { getBoundTextElement } from "../element/textElement"; import { getBoundTextElement } from "../element/textElement";
import { hasBoundTextElement } from "../element/typeChecks"; import {
hasBoundTextElement,
canApplyRoundnessTypeToElement,
getDefaultRoundnessTypeForElement,
} from "../element/typeChecks";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
// `copiedStyles` is exported only for tests. // `copiedStyles` is exported only for tests.
@@ -77,6 +81,14 @@ export const actionPasteStyles = register({
fillStyle: elementStylesToCopyFrom?.fillStyle, fillStyle: elementStylesToCopyFrom?.fillStyle,
opacity: elementStylesToCopyFrom?.opacity, opacity: elementStylesToCopyFrom?.opacity,
roughness: elementStylesToCopyFrom?.roughness, roughness: elementStylesToCopyFrom?.roughness,
roundness: elementStylesToCopyFrom.roundness
? canApplyRoundnessTypeToElement(
elementStylesToCopyFrom.roundness.type,
element,
)
? elementStylesToCopyFrom.roundness
: getDefaultRoundnessTypeForElement(element)
: null,
}); });
if (isTextElement(newElement)) { if (isTextElement(newElement)) {

View File

@@ -5,6 +5,7 @@ import { AppState } from "../types";
export const actionToggleGridMode = register({ export const actionToggleGridMode = register({
name: "gridMode", name: "gridMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.gridSize, predicate: (appState) => !appState.gridSize,
@@ -19,6 +20,9 @@ export const actionToggleGridMode = register({
}; };
}, },
checked: (appState: AppState) => appState.gridSize !== null, checked: (appState: AppState) => appState.gridSize !== null,
predicate: (element, appState, props) => {
return typeof props.gridModeEnabled === "undefined";
},
contextItemLabel: "labels.showGrid", contextItemLabel: "labels.showGrid",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.QUOTE, keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.QUOTE,
}); });

View File

@@ -41,15 +41,9 @@ export const actionToggleLock = register({
: "labels.elementLock.lock"; : "labels.elementLock.lock";
} }
if (selected.length > 1) { return getOperation(selected) === "lock"
return getOperation(selected) === "lock" ? "labels.elementLock.lockAll"
? "labels.elementLock.lockAll" : "labels.elementLock.unlockAll";
: "labels.elementLock.unlockAll";
}
throw new Error(
"Unexpected zero elements to lock/unlock. This should never happen.",
);
}, },
keyTest: (event, appState, elements) => { keyTest: (event, appState, elements) => {
return ( return (

View File

@@ -3,6 +3,7 @@ import { CODES, KEYS } from "../keys";
export const actionToggleStats = register({ export const actionToggleStats = register({
name: "stats", name: "stats",
viewMode: true,
trackEvent: { category: "menu" }, trackEvent: { category: "menu" },
perform(elements, appState) { perform(elements, appState) {
return { return {

View File

@@ -3,6 +3,7 @@ import { register } from "./register";
export const actionToggleViewMode = register({ export const actionToggleViewMode = register({
name: "viewMode", name: "viewMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.viewModeEnabled, predicate: (appState) => !appState.viewModeEnabled,
@@ -17,6 +18,9 @@ export const actionToggleViewMode = register({
}; };
}, },
checked: (appState) => appState.viewModeEnabled, checked: (appState) => appState.viewModeEnabled,
predicate: (elements, appState, appProps) => {
return typeof appProps.viewModeEnabled === "undefined";
},
contextItemLabel: "labels.viewMode", contextItemLabel: "labels.viewMode",
keyTest: (event) => keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R, !event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R,

View File

@@ -3,6 +3,7 @@ import { register } from "./register";
export const actionToggleZenMode = register({ export const actionToggleZenMode = register({
name: "zenMode", name: "zenMode",
viewMode: true,
trackEvent: { trackEvent: {
category: "canvas", category: "canvas",
predicate: (appState) => !appState.zenModeEnabled, predicate: (appState) => !appState.zenModeEnabled,
@@ -17,6 +18,9 @@ export const actionToggleZenMode = register({
}; };
}, },
checked: (appState) => appState.zenModeEnabled, checked: (appState) => appState.zenModeEnabled,
predicate: (elements, appState, appProps) => {
return typeof appProps.zenModeEnabled === "undefined";
},
contextItemLabel: "buttons.zenMode", contextItemLabel: "buttons.zenMode",
keyTest: (event) => keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.Z, !event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.Z,

View File

@@ -5,16 +5,17 @@ import {
moveAllLeft, moveAllLeft,
moveAllRight, moveAllRight,
} from "../zindex"; } from "../zindex";
import { KEYS, isDarwin, CODES } from "../keys"; import { KEYS, CODES } from "../keys";
import { t } from "../i18n"; import { t } from "../i18n";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import { register } from "./register"; import { register } from "./register";
import { import {
SendBackwardIcon,
BringToFrontIcon,
SendToBackIcon,
BringForwardIcon, BringForwardIcon,
BringToFrontIcon,
SendBackwardIcon,
SendToBackIcon,
} from "../components/icons"; } from "../components/icons";
import { isDarwin } from "../constants";
export const actionSendBackward = register({ export const actionSendBackward = register({
name: "sendBackward", name: "sendBackward",
@@ -39,7 +40,7 @@ export const actionSendBackward = register({
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.sendBackward")}${getShortcutKey("CtrlOrCmd+[")}`} title={`${t("labels.sendBackward")}${getShortcutKey("CtrlOrCmd+[")}`}
> >
<SendBackwardIcon theme={appState.theme} /> {SendBackwardIcon}
</button> </button>
), ),
}); });
@@ -67,7 +68,7 @@ export const actionBringForward = register({
onClick={() => updateData(null)} onClick={() => updateData(null)}
title={`${t("labels.bringForward")}${getShortcutKey("CtrlOrCmd+]")}`} title={`${t("labels.bringForward")}${getShortcutKey("CtrlOrCmd+]")}`}
> >
<BringForwardIcon theme={appState.theme} /> {BringForwardIcon}
</button> </button>
), ),
}); });
@@ -102,7 +103,7 @@ export const actionSendToBack = register({
: getShortcutKey("CtrlOrCmd+Shift+[") : getShortcutKey("CtrlOrCmd+Shift+[")
}`} }`}
> >
<SendToBackIcon theme={appState.theme} /> {SendToBackIcon}
</button> </button>
), ),
}); });
@@ -138,7 +139,7 @@ export const actionBringToFront = register({
: getShortcutKey("CtrlOrCmd+Shift+]") : getShortcutKey("CtrlOrCmd+Shift+]")
}`} }`}
> >
<BringToFrontIcon theme={appState.theme} /> {BringToFrontIcon}
</button> </button>
), ),
}); });

View File

@@ -9,7 +9,6 @@ import {
} from "./types"; } from "./types";
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 { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
const trackAction = ( const trackAction = (
@@ -103,11 +102,8 @@ export class ActionManager {
const action = data[0]; const action = data[0];
const { viewModeEnabled } = this.getAppState(); if (this.getAppState().viewModeEnabled && action.viewMode !== true) {
if (viewModeEnabled) { return false;
if (!Object.values(MODES).includes(data[0].name)) {
return false;
}
} }
const elements = this.getElementsIncludingDeleted(); const elements = this.getElementsIncludingDeleted();
@@ -137,6 +133,7 @@ export class ActionManager {
*/ */
renderAction = (name: ActionName, data?: PanelComponentProps["data"]) => { renderAction = (name: ActionName, data?: PanelComponentProps["data"]) => {
const canvasActions = this.app.props.UIOptions.canvasActions; const canvasActions = this.app.props.UIOptions.canvasActions;
if ( if (
this.actions[name] && this.actions[name] &&
"PanelComponent" in this.actions[name] && "PanelComponent" in this.actions[name] &&
@@ -175,4 +172,14 @@ export class ActionManager {
return null; return null;
}; };
isActionEnabled = (action: Action) => {
const elements = this.getElementsIncludingDeleted();
const appState = this.getAppState();
return (
!action.predicate ||
action.predicate(elements, appState, this.app.props, this.app)
);
};
} }

View File

@@ -1,45 +1,54 @@
import { isDarwin } from "../constants";
import { t } from "../i18n"; import { t } from "../i18n";
import { isDarwin } from "../keys";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import { ActionName } from "./types"; import { ActionName } from "./types";
export type ShortcutName = SubtypeOf< export type ShortcutName =
ActionName, | SubtypeOf<
| "cut" ActionName,
| "copy" | "toggleTheme"
| "paste" | "loadScene"
| "copyStyles" | "cut"
| "pasteStyles" | "copy"
| "selectAll" | "paste"
| "deleteSelectedElements" | "copyStyles"
| "duplicateSelection" | "pasteStyles"
| "sendBackward" | "selectAll"
| "bringForward" | "deleteSelectedElements"
| "sendToBack" | "duplicateSelection"
| "bringToFront" | "sendBackward"
| "copyAsPng" | "bringForward"
| "copyAsSvg" | "sendToBack"
| "group" | "bringToFront"
| "ungroup" | "copyAsPng"
| "gridMode" | "copyAsSvg"
| "zenMode" | "group"
| "stats" | "ungroup"
| "addToLibrary" | "gridMode"
| "viewMode" | "zenMode"
| "flipHorizontal" | "stats"
| "flipVertical" | "addToLibrary"
| "hyperlink" | "viewMode"
| "toggleLock" | "flipHorizontal"
>; | "flipVertical"
| "hyperlink"
| "toggleLock"
>
| "saveScene"
| "imageExport";
const shortcutMap: Record<ShortcutName, string[]> = { const shortcutMap: Record<ShortcutName, string[]> = {
toggleTheme: [getShortcutKey("Shift+Alt+D")],
saveScene: [getShortcutKey("CtrlOrCmd+S")],
loadScene: [getShortcutKey("CtrlOrCmd+O")],
imageExport: [getShortcutKey("CtrlOrCmd+Shift+E")],
cut: [getShortcutKey("CtrlOrCmd+X")], cut: [getShortcutKey("CtrlOrCmd+X")],
copy: [getShortcutKey("CtrlOrCmd+C")], copy: [getShortcutKey("CtrlOrCmd+C")],
paste: [getShortcutKey("CtrlOrCmd+V")], paste: [getShortcutKey("CtrlOrCmd+V")],
copyStyles: [getShortcutKey("CtrlOrCmd+Alt+C")], copyStyles: [getShortcutKey("CtrlOrCmd+Alt+C")],
pasteStyles: [getShortcutKey("CtrlOrCmd+Alt+V")], pasteStyles: [getShortcutKey("CtrlOrCmd+Alt+V")],
selectAll: [getShortcutKey("CtrlOrCmd+A")], selectAll: [getShortcutKey("CtrlOrCmd+A")],
deleteSelectedElements: [getShortcutKey("Del")], deleteSelectedElements: [getShortcutKey("Delete")],
duplicateSelection: [ duplicateSelection: [
getShortcutKey("CtrlOrCmd+D"), getShortcutKey("CtrlOrCmd+D"),
getShortcutKey(`Alt+${t("helpDialog.drag")}`), getShortcutKey(`Alt+${t("helpDialog.drag")}`),

View File

@@ -91,7 +91,7 @@ export type ActionName =
| "ungroup" | "ungroup"
| "goToCollaborator" | "goToCollaborator"
| "addToLibrary" | "addToLibrary"
| "changeSharpness" | "changeRoundness"
| "alignTop" | "alignTop"
| "alignBottom" | "alignBottom"
| "alignLeft" | "alignLeft"
@@ -109,10 +109,11 @@ export type ActionName =
| "decreaseFontSize" | "decreaseFontSize"
| "unbindText" | "unbindText"
| "hyperlink" | "hyperlink"
| "eraser"
| "bindText" | "bindText"
| "toggleLock" | "toggleLock"
| "toggleLinearEditor"; | "toggleLinearEditor"
| "toggleEraserTool"
| "toggleHandTool";
export type PanelComponentProps = { export type PanelComponentProps = {
elements: readonly ExcalidrawElement[]; elements: readonly ExcalidrawElement[];
@@ -138,9 +139,11 @@ export interface Action {
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>, appState: Readonly<AppState>,
) => string); ) => string);
contextItemPredicate?: ( predicate?: (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
appState: AppState, appState: AppState,
appProps: ExcalidrawProps,
app: AppClassProperties,
) => boolean; ) => boolean;
checked?: (appState: Readonly<AppState>) => boolean; checked?: (appState: Readonly<AppState>) => boolean;
trackEvent: trackEvent:
@@ -162,4 +165,7 @@ export interface Action {
value: any, value: any,
) => boolean; ) => boolean;
}; };
/** if set to `true`, allow action to be performed in viewMode.
* Defaults to `false` */
viewMode?: boolean;
} }

View File

@@ -19,6 +19,7 @@ export const getDefaultAppState = (): Omit<
"offsetTop" | "offsetLeft" | "width" | "height" "offsetTop" | "offsetLeft" | "width" | "height"
> => { > => {
return { return {
showWelcomeScreen: false,
theme: THEME.LIGHT, theme: THEME.LIGHT,
collaborators: new Map(), collaborators: new Map(),
currentChartType: "bar", currentChartType: "bar",
@@ -27,12 +28,11 @@ export const getDefaultAppState = (): Omit<
currentItemFillStyle: "hachure", currentItemFillStyle: "hachure",
currentItemFontFamily: DEFAULT_FONT_FAMILY, currentItemFontFamily: DEFAULT_FONT_FAMILY,
currentItemFontSize: DEFAULT_FONT_SIZE, currentItemFontSize: DEFAULT_FONT_SIZE,
currentItemLinearStrokeSharpness: "round",
currentItemOpacity: 100, currentItemOpacity: 100,
currentItemRoughness: 1, currentItemRoughness: 1,
currentItemStartArrowhead: null, currentItemStartArrowhead: null,
currentItemStrokeColor: oc.black, currentItemStrokeColor: oc.black,
currentItemStrokeSharpness: "sharp", currentItemRoundness: "round",
currentItemStrokeStyle: "solid", currentItemStrokeStyle: "solid",
currentItemStrokeWidth: 1, currentItemStrokeWidth: 1,
currentItemTextAlign: DEFAULT_TEXT_ALIGN, currentItemTextAlign: DEFAULT_TEXT_ALIGN,
@@ -45,7 +45,7 @@ export const getDefaultAppState = (): Omit<
type: "selection", type: "selection",
customType: null, customType: null,
locked: false, locked: false,
lastActiveToolBeforeEraser: null, lastActiveTool: null,
}, },
penMode: false, penMode: false,
penDetected: false, penDetected: false,
@@ -64,9 +64,11 @@ export const getDefaultAppState = (): Omit<
lastPointerDownWith: "mouse", lastPointerDownWith: "mouse",
multiElement: null, multiElement: null,
name: `${t("labels.untitled")}-${getDateTime()}`, name: `${t("labels.untitled")}-${getDateTime()}`,
contextMenu: null,
openMenu: null, openMenu: null,
openPopup: null, openPopup: null,
openSidebar: null, openSidebar: null,
openDialog: null,
pasteDialog: { shown: false, data: null }, pasteDialog: { shown: false, data: null },
previousSelectedElementIds: {}, previousSelectedElementIds: {},
resizingElement: null, resizingElement: null,
@@ -77,7 +79,6 @@ export const getDefaultAppState = (): Omit<
selectedGroupIds: {}, selectedGroupIds: {},
selectionElement: null, selectionElement: null,
shouldCacheIgnoreZoom: false, shouldCacheIgnoreZoom: false,
showHelpDialog: false,
showStats: false, showStats: false,
startBoundElement: null, startBoundElement: null,
suggestedBindings: [], suggestedBindings: [],
@@ -110,6 +111,7 @@ const APP_STATE_STORAGE_CONF = (<
T extends Record<keyof AppState, Values>, T extends Record<keyof AppState, Values>,
>(config: { [K in keyof T]: K extends keyof AppState ? T[K] : never }) => >(config: { [K in keyof T]: K extends keyof AppState ? T[K] : never }) =>
config)({ config)({
showWelcomeScreen: { browser: true, export: false, server: false },
theme: { browser: true, export: false, server: false }, theme: { browser: true, export: false, server: false },
collaborators: { browser: false, export: false, server: false }, collaborators: { browser: false, export: false, server: false },
currentChartType: { browser: true, export: false, server: false }, currentChartType: { browser: true, export: false, server: false },
@@ -118,7 +120,7 @@ const APP_STATE_STORAGE_CONF = (<
currentItemFillStyle: { browser: true, export: false, server: false }, currentItemFillStyle: { browser: true, export: false, server: false },
currentItemFontFamily: { browser: true, export: false, server: false }, currentItemFontFamily: { browser: true, export: false, server: false },
currentItemFontSize: { browser: true, export: false, server: false }, currentItemFontSize: { browser: true, export: false, server: false },
currentItemLinearStrokeSharpness: { currentItemRoundness: {
browser: true, browser: true,
export: false, export: false,
server: false, server: false,
@@ -127,7 +129,6 @@ const APP_STATE_STORAGE_CONF = (<
currentItemRoughness: { browser: true, export: false, server: false }, currentItemRoughness: { browser: true, export: false, server: false },
currentItemStartArrowhead: { browser: true, export: false, server: false }, currentItemStartArrowhead: { browser: true, export: false, server: false },
currentItemStrokeColor: { browser: true, export: false, server: false }, currentItemStrokeColor: { browser: true, export: false, server: false },
currentItemStrokeSharpness: { browser: true, export: false, server: false },
currentItemStrokeStyle: { browser: true, export: false, server: false }, currentItemStrokeStyle: { browser: true, export: false, server: false },
currentItemStrokeWidth: { browser: true, export: false, server: false }, currentItemStrokeWidth: { browser: true, export: false, server: false },
currentItemTextAlign: { browser: true, export: false, server: false }, currentItemTextAlign: { browser: true, export: false, server: false },
@@ -157,9 +158,11 @@ const APP_STATE_STORAGE_CONF = (<
name: { browser: true, export: false, server: false }, name: { browser: true, export: false, server: false },
offsetLeft: { browser: false, export: false, server: false }, offsetLeft: { browser: false, export: false, server: false },
offsetTop: { browser: false, export: false, server: false }, offsetTop: { browser: false, export: false, server: false },
contextMenu: { browser: false, export: false, server: false },
openMenu: { browser: true, export: false, server: false }, openMenu: { browser: true, export: false, server: false },
openPopup: { browser: false, export: false, server: false }, openPopup: { browser: false, export: false, server: false },
openSidebar: { browser: true, export: false, server: false }, openSidebar: { browser: true, export: false, server: false },
openDialog: { browser: false, export: false, server: false },
pasteDialog: { browser: false, export: false, server: false }, pasteDialog: { browser: false, export: false, server: false },
previousSelectedElementIds: { browser: true, export: false, server: false }, previousSelectedElementIds: { browser: true, export: false, server: false },
resizingElement: { browser: false, export: false, server: false }, resizingElement: { browser: false, export: false, server: false },
@@ -170,7 +173,6 @@ const APP_STATE_STORAGE_CONF = (<
selectedGroupIds: { browser: true, export: false, server: false }, selectedGroupIds: { browser: true, export: false, server: false },
selectionElement: { browser: false, export: false, server: false }, selectionElement: { browser: false, export: false, server: false },
shouldCacheIgnoreZoom: { browser: true, export: false, server: false }, shouldCacheIgnoreZoom: { browser: true, export: false, server: false },
showHelpDialog: { browser: false, export: false, server: false },
showStats: { browser: true, export: false, server: false }, showStats: { browser: true, export: false, server: false },
startBoundElement: { browser: false, export: false, server: false }, startBoundElement: { browser: false, export: false, server: false },
suggestedBindings: { browser: false, export: false, server: false }, suggestedBindings: { browser: false, export: false, server: false },
@@ -226,3 +228,11 @@ export const isEraserActive = ({
}: { }: {
activeTool: AppState["activeTool"]; activeTool: AppState["activeTool"];
}) => activeTool.type === "eraser"; }) => activeTool.type === "eraser";
export const isHandToolActive = ({
activeTool,
}: {
activeTool: AppState["activeTool"];
}) => {
return activeTool.type === "hand";
};

View File

@@ -172,7 +172,7 @@ const commonProps = {
opacity: 100, opacity: 100,
roughness: 1, roughness: 1,
strokeColor: colors.elementStroke[0], strokeColor: colors.elementStroke[0],
strokeSharpness: "sharp", roundness: null,
strokeStyle: "solid", strokeStyle: "solid",
strokeWidth: 1, strokeWidth: 1,
verticalAlign: VERTICAL_ALIGN.MIDDLE, verticalAlign: VERTICAL_ALIGN.MIDDLE,
@@ -322,7 +322,7 @@ const chartBaseElements = (
text: spreadsheet.title, text: spreadsheet.title,
x: x + chartWidth / 2, x: x + chartWidth / 2,
y: y - BAR_HEIGHT - BAR_GAP * 2 - DEFAULT_FONT_SIZE, y: y - BAR_HEIGHT - BAR_GAP * 2 - DEFAULT_FONT_SIZE,
strokeSharpness: "sharp", roundness: null,
strokeStyle: "solid", strokeStyle: "solid",
textAlign: "center", textAlign: "center",
}) })

View File

@@ -11,27 +11,18 @@ export const getClientColors = (clientId: string, appState: AppState) => {
// Naive way of getting an integer out of the clientId // Naive way of getting an integer out of the clientId
const sum = clientId.split("").reduce((a, str) => a + str.charCodeAt(0), 0); const sum = clientId.split("").reduce((a, str) => a + str.charCodeAt(0), 0);
// Skip transparent background. // Skip transparent & gray colors
const backgrounds = colors.elementBackground.slice(1); const backgrounds = colors.elementBackground.slice(3);
const strokes = colors.elementStroke.slice(1); const strokes = colors.elementStroke.slice(3);
return { return {
background: backgrounds[sum % backgrounds.length], background: backgrounds[sum % backgrounds.length],
stroke: strokes[sum % strokes.length], stroke: strokes[sum % strokes.length],
}; };
}; };
export const getClientInitials = (username?: string | null) => { export const getClientInitials = (userName?: string | null) => {
if (!username) { if (!userName) {
return "?"; return "?";
} }
const names = username.trim().split(" "); return userName.trim()[0].toUpperCase();
if (names.length < 2) {
return names[0].substring(0, 2).toUpperCase();
}
const firstName = names[0];
const lastName = names[names.length - 1];
return (firstName[0] + lastName[0]).toUpperCase();
}; };

27
src/clipboard.test.ts Normal file
View File

@@ -0,0 +1,27 @@
import { parseClipboard } from "./clipboard";
describe("Test parseClipboard", () => {
it("should parse valid json correctly", async () => {
let text = "123";
let clipboardData = await parseClipboard({
//@ts-ignore
clipboardData: {
getData: () => text,
},
});
expect(clipboardData.text).toBe(text);
text = "[123]";
clipboardData = await parseClipboard({
//@ts-ignore
clipboardData: {
getData: () => text,
},
});
expect(clipboardData.text).toBe(text);
});
});

View File

@@ -109,16 +109,16 @@ const parsePotentialSpreadsheet = (
* Retrieves content from system clipboard (either from ClipboardEvent or * Retrieves content from system clipboard (either from ClipboardEvent or
* via async clipboard API if supported) * via async clipboard API if supported)
*/ */
const getSystemClipboard = async ( export const getSystemClipboard = async (
event: ClipboardEvent | null, event: ClipboardEvent | null,
): Promise<string> => { ): Promise<string> => {
try { try {
const text = event const text = event
? event.clipboardData?.getData("text/plain").trim() ? event.clipboardData?.getData("text/plain")
: probablySupportsClipboardReadText && : probablySupportsClipboardReadText &&
(await navigator.clipboard.readText()); (await navigator.clipboard.readText());
return text || ""; return (text || "").trim();
} catch { } catch {
return ""; return "";
} }
@@ -129,19 +129,25 @@ const getSystemClipboard = async (
*/ */
export const parseClipboard = async ( export const parseClipboard = async (
event: ClipboardEvent | null, event: ClipboardEvent | null,
isPlainPaste = false,
): Promise<ClipboardData> => { ): Promise<ClipboardData> => {
const systemClipboard = await getSystemClipboard(event); const systemClipboard = await getSystemClipboard(event);
// if system clipboard empty, couldn't be resolved, or contains previously // if system clipboard empty, couldn't be resolved, or contains previously
// copied excalidraw scene as SVG, fall back to previously copied excalidraw // copied excalidraw scene as SVG, fall back to previously copied excalidraw
// elements // elements
if (!systemClipboard || systemClipboard.includes(SVG_EXPORT_TAG)) { if (
!systemClipboard ||
(!isPlainPaste && systemClipboard.includes(SVG_EXPORT_TAG))
) {
return getAppClipboard(); return getAppClipboard();
} }
// if system clipboard contains spreadsheet, use it even though it's // if system clipboard contains spreadsheet, use it even though it's
// technically possible it's staler than in-app clipboard // technically possible it's staler than in-app clipboard
const spreadsheetResult = parsePotentialSpreadsheet(systemClipboard); const spreadsheetResult =
!isPlainPaste && parsePotentialSpreadsheet(systemClipboard);
if (spreadsheetResult) { if (spreadsheetResult) {
return spreadsheetResult; return spreadsheetResult;
} }
@@ -154,30 +160,36 @@ export const parseClipboard = async (
return { return {
elements: systemClipboardData.elements, elements: systemClipboardData.elements,
files: systemClipboardData.files, files: systemClipboardData.files,
text: isPlainPaste
? JSON.stringify(systemClipboardData.elements, null, 2)
: undefined,
}; };
} }
return appClipboardData; } catch (e) {}
} catch { // system clipboard doesn't contain excalidraw elements → return plaintext
// system clipboard doesn't contain excalidraw elements → return plaintext // unless we set a flag to prefer in-app clipboard because browser didn't
// unless we set a flag to prefer in-app clipboard because browser didn't // support storing to system clipboard on copy
// support storing to system clipboard on copy return PREFER_APP_CLIPBOARD && appClipboardData.elements
return PREFER_APP_CLIPBOARD && appClipboardData.elements ? {
? appClipboardData ...appClipboardData,
: { text: systemClipboard }; text: isPlainPaste
} ? JSON.stringify(appClipboardData.elements, null, 2)
: undefined,
}
: { text: systemClipboard };
}; };
export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => { export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => {
let promise;
try { try {
// in Safari so far we need to construct the ClipboardItem synchronously // in Safari so far we need to construct the ClipboardItem synchronously
// (i.e. in the same tick) otherwise browser will complain for lack of // (i.e. in the same tick) otherwise browser will complain for lack of
// user intent. Using a Promise ClipboardItem constructor solves this. // user intent. Using a Promise ClipboardItem constructor solves this.
// https://bugs.webkit.org/show_bug.cgi?id=222262 // https://bugs.webkit.org/show_bug.cgi?id=222262
// //
// not await so that we can detect whether the thrown error likely relates // Note that Firefox (and potentially others) seems to support Promise
// to a lack of support for the Promise ClipboardItem constructor // ClipboardItem constructor, but throws on an unrelated MIME type error.
promise = navigator.clipboard.write([ // So we need to await this and fallback to awaiting the blob if applicable.
await navigator.clipboard.write([
new window.ClipboardItem({ new window.ClipboardItem({
[MIME_TYPES.png]: blob, [MIME_TYPES.png]: blob,
}), }),
@@ -195,7 +207,6 @@ export const copyBlobToClipboardAsPng = async (blob: Blob | Promise<Blob>) => {
throw error; throw error;
} }
} }
await promise;
}; };
export const copyTextToSystemClipboard = async (text: string | null) => { export const copyTextToSystemClipboard = async (text: string | null) => {

View File

@@ -0,0 +1,92 @@
.zoom-actions,
.undo-redo-buttons {
background-color: var(--island-bg-color);
border-radius: var(--border-radius-lg);
}
.zoom-button,
.undo-redo-buttons button {
border: 1px solid var(--default-border-color) !important;
border-radius: 0 !important;
background-color: transparent !important;
font-size: 0.875rem !important;
width: var(--lg-button-size);
height: var(--lg-button-size);
svg {
width: var(--lg-icon-size) !important;
height: var(--lg-icon-size) !important;
}
.ToolIcon__icon {
width: 100%;
height: 100%;
}
}
.reset-zoom-button {
border-left: 0 !important;
border-right: 0 !important;
padding: 0 0.625rem !important;
width: 3.75rem !important;
justify-content: center;
color: var(--text-primary-color);
}
.zoom-out-button {
border-top-left-radius: var(--border-radius-lg) !important;
border-bottom-left-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
}
.zoom-in-button {
border-top-right-radius: var(--border-radius-lg) !important;
border-bottom-right-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
}
.undo-redo-buttons {
.undo-button-container button {
border-top-left-radius: var(--border-radius-lg) !important;
border-bottom-left-radius: var(--border-radius-lg) !important;
border-right: 0 !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
}
.redo-button-container button {
border-top-right-radius: var(--border-radius-lg) !important;
border-bottom-right-radius: var(--border-radius-lg) !important;
:root[dir="rtl"] & {
transform: scaleX(-1);
}
.ToolIcon__icon {
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
}
}
}

View File

@@ -5,7 +5,7 @@ import { ExcalidrawElement, PointerType } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "../components/App"; import { useDevice } from "../components/App";
import { import {
canChangeSharpness, canChangeRoundness,
canHaveArrowheads, canHaveArrowheads,
getTargetElements, getTargetElements,
hasBackground, hasBackground,
@@ -25,9 +25,12 @@ import Stack from "./Stack";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import { hasStrokeColor } from "../scene/comparisons"; import { hasStrokeColor } from "../scene/comparisons";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { hasBoundTextElement, isBoundToContainer } from "../element/typeChecks"; import { hasBoundTextElement } from "../element/typeChecks";
import clsx from "clsx"; import clsx from "clsx";
import { actionToggleZenMode } from "../actions"; import { actionToggleZenMode } from "../actions";
import "./Actions.scss";
import { Tooltip } from "./Tooltip";
import { shouldAllowVerticalAlign } from "../element/textElement";
export const SelectedShapeActions = ({ export const SelectedShapeActions = ({
appState, appState,
@@ -79,12 +82,16 @@ export const SelectedShapeActions = ({
return ( return (
<div className="panelColumn"> <div className="panelColumn">
{((hasStrokeColor(appState.activeTool.type) && <div>
appState.activeTool.type !== "image" && {((hasStrokeColor(appState.activeTool.type) &&
commonSelectedType !== "image") || appState.activeTool.type !== "image" &&
targetElements.some((element) => hasStrokeColor(element.type))) && commonSelectedType !== "image") ||
renderAction("changeStrokeColor")} targetElements.some((element) => hasStrokeColor(element.type))) &&
{showChangeBackgroundIcons && renderAction("changeBackgroundColor")} renderAction("changeStrokeColor")}
</div>
{showChangeBackgroundIcons && (
<div>{renderAction("changeBackgroundColor")}</div>
)}
{showFillIcons && renderAction("changeFillStyle")} {showFillIcons && renderAction("changeFillStyle")}
{(hasStrokeWidth(appState.activeTool.type) || {(hasStrokeWidth(appState.activeTool.type) ||
@@ -103,9 +110,9 @@ export const SelectedShapeActions = ({
</> </>
)} )}
{(canChangeSharpness(appState.activeTool.type) || {(canChangeRoundness(appState.activeTool.type) ||
targetElements.some((element) => canChangeSharpness(element.type))) && ( targetElements.some((element) => canChangeRoundness(element.type))) && (
<>{renderAction("changeSharpness")}</> <>{renderAction("changeRoundness")}</>
)} )}
{(hasText(appState.activeTool.type) || {(hasText(appState.activeTool.type) ||
@@ -119,10 +126,8 @@ export const SelectedShapeActions = ({
</> </>
)} )}
{targetElements.some( {shouldAllowVerticalAlign(targetElements) &&
(element) => renderAction("changeVerticalAlign")}
hasBoundTextElement(element) || isBoundToContainer(element),
) && renderAction("changeVerticalAlign")}
{(canHaveArrowheads(appState.activeTool.type) || {(canHaveArrowheads(appState.activeTool.type) ||
targetElements.some((element) => canHaveArrowheads(element.type))) && ( targetElements.some((element) => canHaveArrowheads(element.type))) && (
<>{renderAction("changeArrowhead")}</> <>{renderAction("changeArrowhead")}</>
@@ -163,7 +168,16 @@ export const SelectedShapeActions = ({
)} )}
{targetElements.length > 2 && {targetElements.length > 2 &&
renderAction("distributeHorizontally")} renderAction("distributeHorizontally")}
<div className="iconRow"> {/* breaks the row ˇˇ */}
<div style={{ flexBasis: "100%", height: 0 }} />
<div
style={{
display: "flex",
flexWrap: "wrap",
gap: ".5rem",
marginTop: "-0.5rem",
}}
>
{renderAction("alignTop")} {renderAction("alignTop")}
{renderAction("alignVerticallyCentered")} {renderAction("alignVerticallyCentered")}
{renderAction("alignBottom")} {renderAction("alignBottom")}
@@ -203,25 +217,26 @@ export const ShapesSwitcher = ({
appState: AppState; appState: AppState;
}) => ( }) => (
<> <>
{SHAPES.map(({ value, icon, key }, index) => { {SHAPES.map(({ value, icon, key, numericKey, fillable }, index) => {
const label = t(`toolBar.${value}`); const label = t(`toolBar.${value}`);
const letter = key && (typeof key === "string" ? key : key[0]); const letter =
key && capitalizeString(typeof key === "string" ? key : key[0]);
const shortcut = letter const shortcut = letter
? `${capitalizeString(letter)} ${t("helpDialog.or")} ${index + 1}` ? `${letter} ${t("helpDialog.or")} ${numericKey}`
: `${index + 1}`; : `${numericKey}`;
return ( return (
<ToolButton <ToolButton
className="Shape" className={clsx("Shape", { fillable })}
key={value} key={value}
type="radio" type="radio"
icon={icon} icon={icon}
checked={activeTool.type === value} checked={activeTool.type === value}
name="editor-current-shape" name="editor-current-shape"
title={`${capitalizeString(label)}${shortcut}`} title={`${capitalizeString(label)}${shortcut}`}
keyBindingLabel={`${index + 1}`} keyBindingLabel={numericKey || letter}
aria-label={capitalizeString(label)} aria-label={capitalizeString(label)}
aria-keyshortcuts={shortcut} aria-keyshortcuts={shortcut}
data-testid={value} data-testid={`toolbar-${value}`}
onPointerDown={({ pointerType }) => { onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") { if (!appState.penDetected && pointerType === "pen") {
setAppState({ setAppState({
@@ -263,11 +278,11 @@ export const ZoomActions = ({
renderAction: ActionManager["renderAction"]; renderAction: ActionManager["renderAction"];
zoom: Zoom; zoom: Zoom;
}) => ( }) => (
<Stack.Col gap={1}> <Stack.Col gap={1} className="zoom-actions">
<Stack.Row gap={1} align="center"> <Stack.Row align="center">
{renderAction("zoomOut")} {renderAction("zoomOut")}
{renderAction("zoomIn")}
{renderAction("resetZoom")} {renderAction("resetZoom")}
{renderAction("zoomIn")}
</Stack.Row> </Stack.Row>
</Stack.Col> </Stack.Col>
); );
@@ -280,8 +295,12 @@ export const UndoRedoActions = ({
className?: string; className?: string;
}) => ( }) => (
<div className={`undo-redo-buttons ${className}`}> <div className={`undo-redo-buttons ${className}`}>
{renderAction("undo", { size: "small" })} <div className="undo-button-container">
{renderAction("redo", { size: "small" })} <Tooltip label={t("buttons.undo")}>{renderAction("undo")}</Tooltip>
</div>
<div className="redo-button-container">
<Tooltip label={t("buttons.redo")}> {renderAction("redo")}</Tooltip>
</div>
</div> </div>
); );

View File

@@ -0,0 +1,35 @@
import { atom, useAtom } from "jotai";
import { actionClearCanvas } from "../actions";
import { t } from "../i18n";
import { useExcalidrawActionManager } from "./App";
import ConfirmDialog from "./ConfirmDialog";
export const activeConfirmDialogAtom = atom<"clearCanvas" | null>(null);
export const ActiveConfirmDialog = () => {
const [activeConfirmDialog, setActiveConfirmDialog] = useAtom(
activeConfirmDialogAtom,
);
const actionManager = useExcalidrawActionManager();
if (!activeConfirmDialog) {
return null;
}
if (activeConfirmDialog === "clearCanvas") {
return (
<ConfirmDialog
onConfirm={() => {
actionManager.executeAction(actionClearCanvas);
setActiveConfirmDialog(null);
}}
onCancel={() => setActiveConfirmDialog(null)}
title={t("clearCanvasDialog.title")}
>
<p className="clear-canvas__content"> {t("alerts.clearReset")}</p>
</ConfirmDialog>
);
}
return null;
};

View File

@@ -1,28 +0,0 @@
import Stack from "../components/Stack";
import { ToolButton } from "../components/ToolButton";
import { save, file } from "../components/icons";
import { t } from "../i18n";
import "./ActiveFile.scss";
type ActiveFileProps = {
fileName?: string;
onSave: () => void;
};
export const ActiveFile = ({ fileName, onSave }: ActiveFileProps) => (
<Stack.Row className="ActiveFile" gap={1} align="center">
<span className="ActiveFile__fileName">
{file}
<span>{fileName}</span>
</span>
<ToolButton
type="icon"
icon={save}
title={t("buttons.save")}
aria-label={t("buttons.save")}
onClick={onSave}
data-testid="save-button"
/>
</Stack.Row>
);

File diff suppressed because it is too large Load Diff

View File

@@ -2,21 +2,35 @@
.excalidraw { .excalidraw {
.Avatar { .Avatar {
width: 2.5rem; width: 1.25rem;
height: 2.5rem; height: 1.25rem;
border-radius: 1.25rem; position: relative;
border-radius: 100%;
outline-offset: 2px;
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
color: $oc-white; color: $oc-white;
cursor: pointer; cursor: pointer;
font-size: 0.8rem; font-size: 0.625rem;
font-weight: 500; font-weight: 500;
line-height: 1;
&-img { &-img {
width: 100%; width: 100%;
height: 100%; height: 100%;
border-radius: 100%; border-radius: 100%;
} }
&::before {
content: "";
position: absolute;
top: -3px;
right: -3px;
bottom: -3px;
left: -3px;
border: 1px solid var(--avatar-border-color);
border-radius: 100%;
}
} }
} }

View File

@@ -11,13 +11,11 @@ type AvatarProps = {
src?: string; src?: string;
}; };
export const Avatar = ({ color, border, onClick, name, src }: AvatarProps) => { export const Avatar = ({ color, onClick, name, src }: AvatarProps) => {
const shortName = getClientInitials(name); const shortName = getClientInitials(name);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const loadImg = !error && src; const loadImg = !error && src;
const style = loadImg const style = loadImg ? undefined : { background: color };
? undefined
: { background: color, border: `1px solid ${border}` };
return ( return (
<div className="Avatar" style={style} onClick={onClick}> <div className="Avatar" style={style} onClick={onClick}>
{loadImg ? ( {loadImg ? (

View File

@@ -1,12 +0,0 @@
import { ActionManager } from "../actions/manager";
export const BackgroundPickerAndDarkModeToggle = ({
actionManager,
}: {
actionManager: ActionManager;
}) => (
<div style={{ display: "flex" }}>
{actionManager.renderAction("changeViewBackgroundColor")}
{actionManager.renderAction("toggleTheme")}
</div>
);

View File

@@ -0,0 +1,7 @@
@import "../css/theme";
.excalidraw {
.excalidraw-button {
@include outlineButtonStyles;
}
}

35
src/components/Button.tsx Normal file
View File

@@ -0,0 +1,35 @@
import "./Button.scss";
interface ButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
type?: "button" | "submit" | "reset";
onSelect: () => any;
children: React.ReactNode;
className?: string;
}
/**
* A generic button component that follows Excalidraw's design system.
* Style can be customised using `className` or `style` prop.
* Accepts all props that a regular `button` element accepts.
*/
export const Button = ({
type = "button",
onSelect,
children,
className = "",
...rest
}: ButtonProps) => {
return (
<button
onClick={(event) => {
onSelect();
rest.onClick?.(event);
}}
type={type}
className={`excalidraw-button ${className}`}
{...rest}
>
{children}
</button>
);
};

View File

@@ -64,6 +64,8 @@
color: #{$oc-blue-7}; color: #{$oc-blue-7};
border: 0;
&:focus { &:focus {
box-shadow: 0 0 0 3px #{$oc-blue-7}; box-shadow: 0 0 0 3px #{$oc-blue-7};
} }

View File

@@ -1,43 +0,0 @@
import { useState } from "react";
import { t } from "../i18n";
import { useDevice } from "./App";
import { trash } from "./icons";
import { ToolButton } from "./ToolButton";
import ConfirmDialog from "./ConfirmDialog";
const ClearCanvas = ({ onConfirm }: { onConfirm: () => void }) => {
const [showDialog, setShowDialog] = useState(false);
const toggleDialog = () => {
setShowDialog(!showDialog);
};
return (
<>
<ToolButton
type="button"
icon={trash}
title={t("buttons.clearReset")}
aria-label={t("buttons.clearReset")}
showAriaLabel={useDevice().isMobile}
onClick={toggleDialog}
data-testid="clear-canvas-button"
/>
{showDialog && (
<ConfirmDialog
onConfirm={() => {
onConfirm();
toggleDialog();
}}
onCancel={toggleDialog}
title={t("clearCanvasDialog.title")}
>
<p className="clear-canvas__content"> {t("alerts.clearReset")}</p>
</ConfirmDialog>
)}
</>
);
};
export default ClearCanvas;

View File

@@ -1,32 +0,0 @@
@import "../css/variables.module";
.excalidraw {
.CollabButton.is-collaborating {
background-color: var(--button-special-active-bg-color);
.ToolIcon__icon svg,
.ToolIcon__label {
color: var(--icon-green-fill-color);
}
}
.CollabButton-collaborators {
:root[dir="ltr"] & {
right: -5px;
}
:root[dir="rtl"] & {
left: -5px;
}
min-width: 1em;
min-height: 1em;
line-height: 1;
position: absolute;
bottom: -5px;
padding: 3px;
border-radius: 50%;
background-color: $oc-green-6;
color: $oc-white;
font-size: 0.6em;
font-family: "Cascadia";
}
}

View File

@@ -1,39 +0,0 @@
import clsx from "clsx";
import { ToolButton } from "./ToolButton";
import { t } from "../i18n";
import { useDevice } from "../components/App";
import { users } from "./icons";
import "./CollabButton.scss";
const CollabButton = ({
isCollaborating,
collaboratorCount,
onClick,
}: {
isCollaborating: boolean;
collaboratorCount: number;
onClick: () => void;
}) => {
return (
<>
<ToolButton
className={clsx("CollabButton", {
"is-collaborating": isCollaborating,
})}
onClick={onClick}
icon={users}
type="button"
title={t("labels.liveCollaboration")}
aria-label={t("labels.liveCollaboration")}
showAriaLabel={useDevice().isMobile}
>
{isCollaborating && (
<div className="CollabButton-collaborators">{collaboratorCount}</div>
)}
</ToolButton>
</>
);
};
export default CollabButton;

View File

@@ -21,6 +21,23 @@
display: grid; display: grid;
grid-template-columns: auto 1fr; grid-template-columns: auto 1fr;
align-items: center; align-items: center;
column-gap: 0.5rem;
}
.color-picker-control-container + .popover {
position: static;
}
.color-picker-popover-container {
margin-top: -0.25rem;
:root[dir="ltr"] & {
margin-left: 0.5rem;
}
:root[dir="rtl"] & {
margin-left: -3rem;
}
} }
.color-picker-triangle { .color-picker-triangle {
@@ -30,20 +47,29 @@
border-width: 0 9px 10px; border-width: 0 9px 10px;
border-color: transparent transparent var(--popup-bg-color); border-color: transparent transparent var(--popup-bg-color);
position: absolute; position: absolute;
top: -10px; top: 10px;
:root[dir="ltr"] & { :root[dir="ltr"] & {
left: 12px; transform: rotate(270deg);
left: -14px;
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
right: 12px; transform: rotate(90deg);
right: -14px;
} }
} }
.color-picker-triangle-shadow { .color-picker-triangle-shadow {
border-color: transparent transparent transparentize($oc-black, 0.9); border-color: transparent transparent transparentize($oc-black, 0.9);
top: -11px;
:root[dir="ltr"] & {
left: -14px;
}
:root[dir="rtl"] & {
right: -16px;
}
} }
.color-picker-content--default { .color-picker-content--default {
@@ -119,16 +145,21 @@
} }
.color-picker-hash { .color-picker-hash {
background: var(--input-border-color); height: var(--default-button-size);
height: 1.875rem; flex-shrink: 0;
width: 1.875rem; padding: 0.5rem 0.5rem 0.5rem 0.75rem;
border: 1px solid var(--default-border-color);
border-right: 0;
box-sizing: border-box;
:root[dir="ltr"] & { :root[dir="ltr"] & {
border-radius: 4px 0 0 4px; border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg);
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
border-radius: 0 4px 4px 0; border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0;
border-right: 1px solid var(--default-border-color);
border-left: 0;
} }
color: var(--input-label-color); color: var(--input-label-color);
@@ -138,81 +169,64 @@
position: relative; position: relative;
} }
.color-input-container:focus-within .color-picker-hash {
box-shadow: 0 0 0 2px var(--focus-highlight-color);
}
.color-input-container:focus-within .color-picker-hash::before,
.color-input-container:focus-within .color-picker-hash::after {
content: "";
width: 1px;
height: 100%;
position: absolute;
top: 0;
}
.color-input-container:focus-within .color-picker-hash::before {
background: var(--input-border-color);
:root[dir="ltr"] & {
right: -1px;
}
:root[dir="rtl"] & {
left: -1px;
}
}
.color-input-container:focus-within .color-picker-hash::after {
background: var(--input-bg-color);
:root[dir="ltr"] & {
right: -2px;
}
:root[dir="rtl"] & {
left: -2px;
}
}
.color-input-container { .color-input-container {
display: flex; display: flex;
&:focus-within {
box-shadow: 0 0 0 1px var(--color-primary-darkest);
border-radius: var(--border-radius-lg);
}
} }
.color-picker-input { .color-picker-input {
width: 11ch; /* length of `transparent` */ box-sizing: border-box;
width: 100%;
margin: 0; margin: 0;
font-size: 1rem; font-size: 0.875rem;
background-color: var(--input-bg-color); background-color: transparent;
color: var(--text-primary-color); color: var(--text-primary-color);
border: 0; border: 0;
outline: none; outline: none;
height: 1.75em; height: var(--default-button-size);
box-shadow: var(--input-border-color) 0 0 0 1px inset; border: 1px solid var(--default-border-color);
border-left: 0;
letter-spacing: 0.4px;
:root[dir="ltr"] & { :root[dir="ltr"] & {
border-radius: 0 4px 4px 0; border-radius: 0 var(--border-radius-lg) var(--border-radius-lg) 0;
} }
:root[dir="rtl"] & { :root[dir="rtl"] & {
border-radius: 4px 0 0 4px; border-radius: var(--border-radius-lg) 0 0 var(--border-radius-lg);
border-left: 1px solid var(--default-border-color);
border-right: 0;
} }
float: left; padding: 0.5rem;
padding: 1px; padding-left: 0.25rem;
padding-inline-start: 0.5em;
appearance: none; appearance: none;
&:focus-visible {
box-shadow: none;
}
}
.color-picker-label-swatch-container {
border: 1px solid var(--default-border-color);
border-radius: var(--border-radius-lg);
width: var(--default-button-size);
height: var(--default-button-size);
box-sizing: border-box;
overflow: hidden;
} }
.color-picker-label-swatch { .color-picker-label-swatch {
height: 1.875rem; @include outlineButtonStyles;
width: 1.875rem; background-color: var(--swatch-color) !important;
margin-inline-end: 0.25rem;
border: 1px solid $oc-gray-3;
position: relative;
overflow: hidden; overflow: hidden;
background-color: transparent !important; position: relative;
filter: var(--theme-filter); filter: var(--theme-filter);
border: 0 !important;
&:after { &:after {
content: ""; content: "";

View File

@@ -66,10 +66,13 @@ const getColor = (color: string): string | null => {
return color; return color;
} }
return isValidColor(color) // testing for `#` first fixes a bug on Electron (more specfically, an
? color // Obsidian popout window), where a hex color without `#` is (incorrectly)
: isValidColor(`#${color}`) // considered valid
return isValidColor(`#${color}`)
? `#${color}` ? `#${color}`
: isValidColor(color)
? color
: null; : null;
}; };
@@ -365,17 +368,20 @@ export const ColorPicker = ({
appState: AppState; appState: AppState;
}) => { }) => {
const pickerButton = React.useRef<HTMLButtonElement>(null); const pickerButton = React.useRef<HTMLButtonElement>(null);
const coords = pickerButton.current?.getBoundingClientRect();
return ( return (
<div> <div>
<div className="color-picker-control-container"> <div className="color-picker-control-container">
<button <div className="color-picker-label-swatch-container">
className="color-picker-label-swatch" <button
aria-label={label} className="color-picker-label-swatch"
style={color ? { "--swatch-color": color } : undefined} aria-label={label}
onClick={() => setActive(!isActive)} style={color ? { "--swatch-color": color } : undefined}
ref={pickerButton} onClick={() => setActive(!isActive)}
/> ref={pickerButton}
/>
</div>
<ColorInput <ColorInput
color={color} color={color}
label={label} label={label}
@@ -386,27 +392,37 @@ export const ColorPicker = ({
</div> </div>
<React.Suspense fallback=""> <React.Suspense fallback="">
{isActive ? ( {isActive ? (
<Popover <div
onCloseRequest={(event) => className="color-picker-popover-container"
event.target !== pickerButton.current && setActive(false) style={{
} position: "fixed",
top: coords?.top,
left: coords?.right,
zIndex: 1,
}}
> >
<Picker <Popover
colors={colors[type]} onCloseRequest={(event) =>
color={color || null} event.target !== pickerButton.current && setActive(false)
onChange={(changedColor) => { }
onChange(changedColor); >
}} <Picker
onClose={() => { colors={colors[type]}
setActive(false); color={color || null}
pickerButton.current?.focus(); onChange={(changedColor) => {
}} onChange(changedColor);
label={label} }}
showInput={false} onClose={() => {
type={type} setActive(false);
elements={elements} pickerButton.current?.focus();
/> }}
</Popover> label={label}
showInput={false}
type={type}
elements={elements}
/>
</Popover>
</div>
) : null} ) : null}
</React.Suspense> </React.Suspense>
</div> </div>

View File

@@ -4,34 +4,8 @@
.confirm-dialog { .confirm-dialog {
&-buttons { &-buttons {
display: flex; display: flex;
padding: 0.2rem 0; column-gap: 0.5rem;
justify-content: flex-end; justify-content: flex-end;
} }
.ToolIcon__icon {
min-width: 2.5rem;
width: auto;
font-size: 1rem;
}
.ToolIcon_type_button {
margin-left: 0.8rem;
padding: 0 0.5rem;
}
&__content {
font-size: 1rem;
}
&--confirm.ToolIcon_type_button {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-8;
}
.ToolIcon__icon {
color: $oc-white;
}
}
} }
} }

View File

@@ -1,8 +1,11 @@
import { t } from "../i18n"; import { t } from "../i18n";
import { Dialog, DialogProps } from "./Dialog"; import { Dialog, DialogProps } from "./Dialog";
import { ToolButton } from "./ToolButton";
import "./ConfirmDialog.scss"; import "./ConfirmDialog.scss";
import DialogActionButton from "./DialogActionButton";
import { useSetAtom } from "jotai";
import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent";
import { useExcalidrawSetAppState } from "./App";
interface Props extends Omit<DialogProps, "onCloseRequest"> { interface Props extends Omit<DialogProps, "onCloseRequest"> {
onConfirm: () => void; onConfirm: () => void;
@@ -20,6 +23,9 @@ const ConfirmDialog = (props: Props) => {
className = "", className = "",
...rest ...rest
} = props; } = props;
const setAppState = useExcalidrawSetAppState();
const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
return ( return (
<Dialog <Dialog
onCloseRequest={onCancel} onCloseRequest={onCancel}
@@ -29,21 +35,22 @@ const ConfirmDialog = (props: Props) => {
> >
{children} {children}
<div className="confirm-dialog-buttons"> <div className="confirm-dialog-buttons">
<ToolButton <DialogActionButton
type="button"
title={cancelText}
aria-label={cancelText}
label={cancelText} label={cancelText}
onClick={onCancel} onClick={() => {
className="confirm-dialog--cancel" setAppState({ openMenu: null });
setIsLibraryMenuOpen(false);
onCancel();
}}
/> />
<ToolButton <DialogActionButton
type="button"
title={confirmText}
aria-label={confirmText}
label={confirmText} label={confirmText}
onClick={onConfirm} onClick={() => {
className="confirm-dialog--confirm" setAppState({ openMenu: null });
setIsLibraryMenuOpen(false);
onConfirm();
}}
actionType="danger"
/> />
</div> </div>
</Dialog> </Dialog>

View File

@@ -19,7 +19,7 @@
color: var(--popup-text-color); color: var(--popup-text-color);
} }
.context-menu-option { .context-menu-item {
position: relative; position: relative;
width: 100%; width: 100%;
min-width: 9.5rem; min-width: 9.5rem;
@@ -43,16 +43,16 @@
} }
&.dangerous { &.dangerous {
.context-menu-option__label { .context-menu-item__label {
color: $oc-red-7; color: $oc-red-7;
} }
} }
.context-menu-option__label { .context-menu-item__label {
justify-self: start; justify-self: start;
margin-inline-end: 20px; margin-inline-end: 20px;
} }
.context-menu-option__shortcut { .context-menu-item__shortcut {
justify-self: end; justify-self: end;
opacity: 0.6; opacity: 0.6;
font-family: inherit; font-family: inherit;
@@ -60,37 +60,37 @@
} }
} }
.context-menu-option:hover { .context-menu-item:hover {
color: var(--popup-bg-color); color: var(--popup-bg-color);
background-color: var(--select-highlight-color); background-color: var(--select-highlight-color);
&.dangerous { &.dangerous {
.context-menu-option__label { .context-menu-item__label {
color: var(--popup-bg-color); color: var(--popup-bg-color);
} }
background-color: $oc-red-6; background-color: $oc-red-6;
} }
} }
.context-menu-option:focus { .context-menu-item:focus {
z-index: 1; z-index: 1;
} }
@include isMobile { @include isMobile {
.context-menu-option { .context-menu-item {
display: block; display: block;
.context-menu-option__label { .context-menu-item__label {
margin-inline-end: 0; margin-inline-end: 0;
} }
.context-menu-option__shortcut { .context-menu-item__shortcut {
display: none; display: none;
} }
} }
} }
.context-menu-option-separator { .context-menu-item-separator {
border: none; border: none;
border-top: 1px solid $oc-gray-5; border-top: 1px solid $oc-gray-5;
} }

View File

@@ -1,4 +1,3 @@
import { render, unmountComponentAtNode } from "react-dom";
import clsx from "clsx"; import clsx from "clsx";
import { Popover } from "./Popover"; import { Popover } from "./Popover";
import { t } from "../i18n"; import { t } from "../i18n";
@@ -10,140 +9,116 @@ import {
} from "../actions/shortcuts"; } from "../actions/shortcuts";
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 {
import { NonDeletedExcalidrawElement } from "../element/types"; useExcalidrawAppState,
useExcalidrawElements,
useExcalidrawSetAppState,
} from "./App";
import React from "react";
export type ContextMenuOption = "separator" | Action; export type ContextMenuItem = typeof CONTEXT_MENU_SEPARATOR | Action;
export type ContextMenuItems = (ContextMenuItem | false | null | undefined)[];
type ContextMenuProps = { type ContextMenuProps = {
options: ContextMenuOption[]; actionManager: ActionManager;
onCloseRequest?(): void; items: ContextMenuItems;
top: number; top: number;
left: number; left: number;
actionManager: ActionManager;
appState: Readonly<AppState>;
elements: readonly NonDeletedExcalidrawElement[];
}; };
const ContextMenu = ({ export const CONTEXT_MENU_SEPARATOR = "separator";
options,
onCloseRequest,
top,
left,
actionManager,
appState,
elements,
}: ContextMenuProps) => {
return (
<Popover
onCloseRequest={onCloseRequest}
top={top}
left={left}
fitInViewport={true}
offsetLeft={appState.offsetLeft}
offsetTop={appState.offsetTop}
viewportWidth={appState.width}
viewportHeight={appState.height}
>
<ul
className="context-menu"
onContextMenu={(event) => event.preventDefault()}
>
{options.map((option, idx) => {
if (option === "separator") {
return <hr key={idx} className="context-menu-option-separator" />;
}
const actionName = option.name; export const ContextMenu = React.memo(
let label = ""; ({ actionManager, items, top, left }: ContextMenuProps) => {
if (option.contextItemLabel) { const appState = useExcalidrawAppState();
if (typeof option.contextItemLabel === "function") { const setAppState = useExcalidrawSetAppState();
label = t(option.contextItemLabel(elements, appState)); const elements = useExcalidrawElements();
} else {
label = t(option.contextItemLabel);
}
}
return (
<li key={idx} data-testid={actionName} onClick={onCloseRequest}>
<button
className={clsx("context-menu-option", {
dangerous: actionName === "deleteSelectedElements",
checkmark: option.checked?.(appState),
})}
onClick={() =>
actionManager.executeAction(option, "contextMenu")
}
>
<div className="context-menu-option__label">{label}</div>
<kbd className="context-menu-option__shortcut">
{actionName
? getShortcutFromShortcutName(actionName as ShortcutName)
: ""}
</kbd>
</button>
</li>
);
})}
</ul>
</Popover>
);
};
const contextMenuNodeByContainer = new WeakMap<HTMLElement, HTMLDivElement>(); const filteredItems = items.reduce((acc: ContextMenuItem[], item) => {
if (
const getContextMenuNode = (container: HTMLElement): HTMLDivElement => { item &&
let contextMenuNode = contextMenuNodeByContainer.get(container); (item === CONTEXT_MENU_SEPARATOR ||
if (contextMenuNode) { !item.predicate ||
return contextMenuNode; item.predicate(
} elements,
contextMenuNode = document.createElement("div"); appState,
container actionManager.app.props,
.querySelector(".excalidraw-contextMenuContainer")! actionManager.app,
.appendChild(contextMenuNode); ))
contextMenuNodeByContainer.set(container, contextMenuNode); ) {
return contextMenuNode; acc.push(item);
};
type ContextMenuParams = {
options: (ContextMenuOption | false | null | undefined)[];
top: ContextMenuProps["top"];
left: ContextMenuProps["left"];
actionManager: ContextMenuProps["actionManager"];
appState: Readonly<AppState>;
container: HTMLElement;
elements: readonly NonDeletedExcalidrawElement[];
};
const handleClose = (container: HTMLElement) => {
const contextMenuNode = contextMenuNodeByContainer.get(container);
if (contextMenuNode) {
unmountComponentAtNode(contextMenuNode);
contextMenuNode.remove();
contextMenuNodeByContainer.delete(container);
}
};
export default {
push(params: ContextMenuParams) {
const options = Array.of<ContextMenuOption>();
params.options.forEach((option) => {
if (option) {
options.push(option);
} }
}); return acc;
if (options.length) { }, []);
render(
<ContextMenu return (
top={params.top} <Popover
left={params.left} onCloseRequest={() => setAppState({ contextMenu: null })}
options={options} top={top}
onCloseRequest={() => handleClose(params.container)} left={left}
actionManager={params.actionManager} fitInViewport={true}
appState={params.appState} offsetLeft={appState.offsetLeft}
elements={params.elements} offsetTop={appState.offsetTop}
/>, viewportWidth={appState.width}
getContextMenuNode(params.container), viewportHeight={appState.height}
); >
} <ul
className="context-menu"
onContextMenu={(event) => event.preventDefault()}
>
{filteredItems.map((item, idx) => {
if (item === CONTEXT_MENU_SEPARATOR) {
if (
!filteredItems[idx - 1] ||
filteredItems[idx - 1] === CONTEXT_MENU_SEPARATOR
) {
return null;
}
return <hr key={idx} className="context-menu-item-separator" />;
}
const actionName = item.name;
let label = "";
if (item.contextItemLabel) {
if (typeof item.contextItemLabel === "function") {
label = t(item.contextItemLabel(elements, appState));
} else {
label = t(item.contextItemLabel);
}
}
return (
<li
key={idx}
data-testid={actionName}
onClick={() => {
// we need update state before executing the action in case
// the action uses the appState it's being passed (that still
// contains a defined contextMenu) to return the next state.
setAppState({ contextMenu: null }, () => {
actionManager.executeAction(item, "contextMenu");
});
}}
>
<button
className={clsx("context-menu-item", {
dangerous: actionName === "deleteSelectedElements",
checkmark: item.checked?.(appState),
})}
>
<div className="context-menu-item__label">{label}</div>
<kbd className="context-menu-item__shortcut">
{actionName
? getShortcutFromShortcutName(actionName as ShortcutName)
: ""}
</kbd>
</button>
</li>
);
})}
</ul>
</Popover>
);
}, },
}; );

View File

@@ -7,68 +7,11 @@
} }
.Dialog__title { .Dialog__title {
display: grid;
align-items: center;
margin-top: 0;
grid-template-columns: 1fr calc(var(--space-factor) * 7);
grid-gap: var(--metric);
padding: calc(var(--space-factor) * 2);
text-align: center;
font-variant: small-caps;
font-size: 1.2em;
}
.Dialog__titleContent {
flex: 1;
}
.Dialog .Modal__close {
color: var(--icon-fill-color);
margin: 0; margin: 0;
} text-align: left;
font-size: 1.25rem;
.Dialog__content { border-bottom: 1px solid var(--dialog-border-color);
padding: 0 16px 16px; padding: 0 0 0.75rem;
} margin-bottom: 1.5rem;
@include isMobile {
.Dialog {
--metric: calc(var(--space-factor) * 4);
--inset-left: #{"max(var(--metric), var(--sal))"};
--inset-right: #{"max(var(--metric), var(--sar))"};
}
.Dialog__title {
grid-template-columns: calc(var(--space-factor) * 7) 1fr calc(
var(--space-factor) * 7
);
position: sticky;
top: 0;
padding: calc(var(--space-factor) * 2);
background: var(--island-bg-color);
font-size: 1.25em;
box-sizing: border-box;
border-bottom: 1px solid var(--button-gray-2);
z-index: 1;
}
.Dialog__titleContent {
text-align: center;
}
.Dialog .Island {
width: 100vw;
height: 100%;
box-sizing: border-box;
overflow-y: auto;
padding-left: #{"max(calc(var(--padding) * var(--space-factor)), var(--sal))"};
padding-right: #{"max(calc(var(--padding) * var(--space-factor)), var(--sar))"};
padding-bottom: #{"max(calc(var(--padding) * var(--space-factor)), var(--sab))"};
}
.Dialog .Modal__close {
order: -1;
}
} }
} }

View File

@@ -2,14 +2,20 @@ import clsx from "clsx";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useCallbackRefState } from "../hooks/useCallbackRefState"; import { useCallbackRefState } from "../hooks/useCallbackRefState";
import { t } from "../i18n"; import { t } from "../i18n";
import { useExcalidrawContainer, useDevice } from "../components/App"; import {
useExcalidrawContainer,
useDevice,
useExcalidrawSetAppState,
} from "../components/App";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import "./Dialog.scss"; import "./Dialog.scss";
import { back, close } from "./icons"; import { back, CloseIcon } from "./icons";
import { Island } from "./Island"; import { Island } from "./Island";
import { Modal } from "./Modal"; import { Modal } from "./Modal";
import { AppState } from "../types"; import { AppState } from "../types";
import { queryFocusableElements } from "../utils"; import { queryFocusableElements } from "../utils";
import { useSetAtom } from "jotai";
import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent";
export interface DialogProps { export interface DialogProps {
children: React.ReactNode; children: React.ReactNode;
@@ -65,7 +71,12 @@ export const Dialog = (props: DialogProps) => {
return () => islandNode.removeEventListener("keydown", handleKeyDown); return () => islandNode.removeEventListener("keydown", handleKeyDown);
}, [islandNode, props.autofocus]); }, [islandNode, props.autofocus]);
const setAppState = useExcalidrawSetAppState();
const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
const onClose = () => { const onClose = () => {
setAppState({ openMenu: null });
setIsLibraryMenuOpen(false);
(lastActiveElement as HTMLElement).focus(); (lastActiveElement as HTMLElement).focus();
props.onCloseRequest(); props.onCloseRequest();
}; };
@@ -88,7 +99,7 @@ export const Dialog = (props: DialogProps) => {
title={t("buttons.close")} title={t("buttons.close")}
aria-label={t("buttons.close")} aria-label={t("buttons.close")}
> >
{useDevice().isMobile ? back : close} {useDevice().isMobile ? back : CloseIcon}
</button> </button>
</h2> </h2>
<div className="Dialog__content">{props.children}</div> <div className="Dialog__content">{props.children}</div>

View File

@@ -0,0 +1,47 @@
.excalidraw {
.Dialog__action-button {
position: relative;
display: flex;
column-gap: 0.5rem;
align-items: center;
padding: 0.5rem 1.5rem;
border: 1px solid var(--default-border-color);
background-color: transparent;
height: 3rem;
border-radius: var(--border-radius-lg);
letter-spacing: 0.4px;
color: inherit;
font-family: inherit;
font-size: 0.875rem;
font-weight: 600;
user-select: none;
svg {
display: block;
width: 1rem;
height: 1rem;
}
&--danger {
background-color: var(--color-danger);
border-color: var(--color-danger);
color: #fff;
}
&--primary {
background-color: var(--color-primary);
border-color: var(--color-primary);
color: #fff;
}
}
&.theme--dark {
.Dialog__action-button--danger {
color: var(--color-gray-100);
}
.Dialog__action-button--primary {
color: var(--color-gray-100);
}
}
}

View File

@@ -0,0 +1,46 @@
import clsx from "clsx";
import { ReactNode } from "react";
import "./DialogActionButton.scss";
import Spinner from "./Spinner";
interface DialogActionButtonProps {
label: string;
children?: ReactNode;
actionType?: "primary" | "danger";
isLoading?: boolean;
}
const DialogActionButton = ({
label,
onClick,
className,
children,
actionType,
type = "button",
isLoading,
...rest
}: DialogActionButtonProps & React.ButtonHTMLAttributes<HTMLButtonElement>) => {
const cs = actionType ? `Dialog__action-button--${actionType}` : "";
return (
<button
className={clsx("Dialog__action-button", cs, className)}
type={type}
aria-label={label}
onClick={onClick}
{...rest}
>
{children && (
<div style={isLoading ? { visibility: "hidden" } : {}}>{children}</div>
)}
<div style={isLoading ? { visibility: "hidden" } : {}}>{label}</div>
{isLoading && (
<div style={{ position: "absolute", inset: 0 }}>
<Spinner />
</div>
)}
</button>
);
};
export default DialogActionButton;

View File

@@ -91,9 +91,15 @@
} }
button.ExportDialog-imageExportButton { button.ExportDialog-imageExportButton {
border: 0;
width: 5rem; width: 5rem;
height: 5rem; height: 5rem;
margin: 0 0.2em; margin: 0 0.2em;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
border-radius: 1rem; border-radius: 1rem;
background-color: var(--button-color); background-color: var(--button-color);

View File

@@ -1,3 +1,5 @@
@import "../css/variables.module";
.excalidraw { .excalidraw {
.FixedSideContainer { .FixedSideContainer {
position: absolute; position: absolute;
@@ -9,9 +11,10 @@
} }
.FixedSideContainer_side_top { .FixedSideContainer_side_top {
left: var(--space-factor); left: var(--editor-container-padding);
top: var(--space-factor); top: var(--editor-container-padding);
right: var(--space-factor); right: var(--editor-container-padding);
bottom: var(--editor-container-padding);
z-index: 2; z-index: 2;
} }

View File

@@ -0,0 +1,32 @@
import "./ToolIcon.scss";
import clsx from "clsx";
import { ToolButton } from "./ToolButton";
import { handIcon } from "./icons";
import { KEYS } from "../keys";
type LockIconProps = {
title?: string;
name?: string;
checked: boolean;
onChange?(): void;
isMobile?: boolean;
};
export const HandButton = (props: LockIconProps) => {
return (
<ToolButton
className={clsx("Shape", { fillable: false })}
type="radio"
icon={handIcon}
name="editor-current-shape"
checked={props.checked}
title={`${props.title} — H`}
keyBindingLabel={!props.isMobile ? KEYS.H.toLocaleUpperCase() : undefined}
aria-label={`${props.title} — H`}
aria-keyshortcuts={KEYS.H}
data-testid={`toolbar-hand`}
onChange={() => props.onChange?.()}
/>
);
};

View File

@@ -1,13 +1,13 @@
import { questionCircle } from "../components/icons"; import { HelpIcon } from "./icons";
type HelpIconProps = { type HelpButtonProps = {
title?: string; title?: string;
name?: string; name?: string;
id?: string; id?: string;
onClick?(): void; onClick?(): void;
}; };
export const HelpIcon = (props: HelpIconProps) => ( export const HelpButton = (props: HelpButtonProps) => (
<button <button
className="help-icon" className="help-icon"
onClick={props.onClick} onClick={props.onClick}
@@ -15,6 +15,6 @@ export const HelpIcon = (props: HelpIconProps) => (
title={`${props.title} — ?`} title={`${props.title} — ?`}
aria-label={props.title} aria-label={props.title}
> >
{questionCircle} {HelpIcon}
</button> </button>
); );

View File

@@ -1,56 +1,115 @@
@import "../css/variables.module"; @import "../css/variables.module";
.excalidraw { .excalidraw {
.HelpDialog h3 { .HelpDialog {
border-bottom: 1px solid var(--button-gray-2); .Modal__content {
padding-bottom: 4px; max-width: 960px;
} }
.HelpDialog--island { h3 {
border: 1px solid var(--button-gray-2); margin: 1.5rem 0;
margin-bottom: 16px; font-weight: bold;
} font-size: 1.125rem;
}
.HelpDialog--island-title { &__header {
margin: 0; display: flex;
padding: 4px; flex-wrap: wrap;
background-color: var(--button-gray-1); gap: 0.75rem;
text-align: center; }
}
.HelpDialog--shortcut { &__btn {
border-top: 1px solid var(--button-gray-2); display: flex;
} column-gap: 0.5rem;
align-items: center;
border: 1px solid var(--default-border-color);
padding: 0.625rem 1rem;
border-radius: var(--border-radius-lg);
color: var(--text-primary-color);
font-weight: 600;
font-size: 0.75rem;
letter-spacing: 0.4px;
.HelpDialog--key { &:hover {
word-break: keep-all; text-decoration: none;
border: 1px solid var(--button-gray-2); }
padding: 2px 8px; }
margin: auto 4px;
background-color: var(--button-gray-1);
border-radius: 2px;
font-size: 0.8em;
min-height: 26px;
box-sizing: border-box;
display: flex;
align-items: center;
font-family: inherit;
}
.HelpDialog--header { &__link-icon {
display: flex; line-height: 0;
flex-direction: row; svg {
justify-content: space-evenly; width: 1rem;
margin-bottom: 32px; height: 1rem;
padding-bottom: 16px; }
} }
.HelpDialog--btn { &__islands-container {
border: 1px solid var(--link-color); display: grid;
padding: 8px 32px; @media screen and (min-width: 1024px) {
border-radius: 4px; grid-template-columns: 1fr 1fr;
} }
.HelpDialog--btn:hover { grid-column-gap: 1.5rem;
text-decoration: none; grid-row-gap: 2rem;
}
@media screen and (min-width: 1024px) {
&__island--tools {
grid-area: 1 / 1 / 2 / 2;
}
&__island--view {
grid-area: 2 / 1 / 3 / 2;
}
&__island--editor {
grid-area: 1 / 2 / 3 / 3;
}
}
&__island {
h4 {
font-size: 1rem;
font-weight: bold;
margin: 0;
margin-bottom: 0.625rem;
}
&-content {
border: 1px solid var(--dialog-border-color);
border-radius: var(--border-radius-lg);
}
}
&__shortcut {
border-bottom: 1px solid var(--dialog-border-color);
padding: 0.375rem 0.75rem;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.875rem;
column-gap: 0.5rem;
&:last-child {
border-bottom: none;
}
}
&__key-container {
display: flex;
align-items: center;
column-gap: 0.25rem;
flex-shrink: 0;
}
&__key {
display: flex;
box-sizing: border-box;
font-size: 0.625rem;
background-color: var(--color-primary-light);
border-radius: var(--border-radius-md);
padding: 0.5rem;
word-break: keep-all;
align-items: center;
font-family: inherit;
line-height: 1;
}
} }
} }

View File

@@ -1,35 +1,41 @@
import React from "react"; import React from "react";
import { t } from "../i18n"; import { t } from "../i18n";
import { isDarwin, isWindows } from "../keys"; import { KEYS } from "../keys";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import "./HelpDialog.scss"; import "./HelpDialog.scss";
import { ExternalLinkIcon } from "./icons";
import { probablySupportsClipboardBlob } from "../clipboard";
import { isDarwin, isFirefox, isWindows } from "../constants";
const Header = () => ( const Header = () => (
<div className="HelpDialog--header"> <div className="HelpDialog__header">
<a <a
className="HelpDialog--btn" className="HelpDialog__btn"
href="https://github.com/excalidraw/excalidraw#documentation" href="https://github.com/excalidraw/excalidraw#documentation"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.documentation")} {t("helpDialog.documentation")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
<a <a
className="HelpDialog--btn" className="HelpDialog__btn"
href="https://blog.excalidraw.com" href="https://blog.excalidraw.com"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.blog")} {t("helpDialog.blog")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
<a <a
className="HelpDialog--btn" className="HelpDialog__btn"
href="https://github.com/excalidraw/excalidraw/issues" href="https://github.com/excalidraw/excalidraw/issues"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
> >
{t("helpDialog.github")} {t("helpDialog.github")}
<div className="HelpDialog__link-icon">{ExternalLinkIcon}</div>
</a> </a>
</div> </div>
); );
@@ -37,88 +43,67 @@ const Header = () => (
const Section = (props: { title: string; children: React.ReactNode }) => ( const Section = (props: { title: string; children: React.ReactNode }) => (
<> <>
<h3>{props.title}</h3> <h3>{props.title}</h3>
{props.children} <div className="HelpDialog__islands-container">{props.children}</div>
</> </>
); );
const Columns = (props: { children: React.ReactNode }) => (
<div
style={{
display: "flex",
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "space-between",
}}
>
{props.children}
</div>
);
const Column = (props: { children: React.ReactNode }) => (
<div style={{ width: "49%" }}>{props.children}</div>
);
const ShortcutIsland = (props: { const ShortcutIsland = (props: {
caption: string; caption: string;
children: React.ReactNode; children: React.ReactNode;
className?: string;
}) => ( }) => (
<div className="HelpDialog--island"> <div className={`HelpDialog__island ${props.className}`}>
<h3 className="HelpDialog--island-title">{props.caption}</h3> <h4 className="HelpDialog__island-title">{props.caption}</h4>
{props.children} <div className="HelpDialog__island-content">{props.children}</div>
</div> </div>
); );
const Shortcut = (props: { function* intersperse(as: JSX.Element[][], delim: string | null) {
let first = true;
for (const x of as) {
if (!first) {
yield delim;
}
first = false;
yield x;
}
}
const upperCaseSingleChars = (str: string) => {
return str.replace(/\b[a-z]\b/, (c) => c.toUpperCase());
};
const Shortcut = ({
label,
shortcuts,
isOr = true,
}: {
label: string; label: string;
shortcuts: string[]; shortcuts: string[];
isOr: boolean; isOr?: boolean;
}) => { }) => {
const splitShortcutKeys = shortcuts.map((shortcut) => {
const keys = shortcut.endsWith("++")
? [...shortcut.slice(0, -2).split("+"), "+"]
: shortcut.split("+");
return keys.map((key) => (
<ShortcutKey key={key}>{upperCaseSingleChars(key)}</ShortcutKey>
));
});
return ( return (
<div className="HelpDialog--shortcut"> <div className="HelpDialog__shortcut">
<div <div>{label}</div>
style={{ <div className="HelpDialog__key-container">
display: "flex", {[...intersperse(splitShortcutKeys, isOr ? t("helpDialog.or") : null)]}
margin: "0",
padding: "4px 8px",
alignItems: "center",
}}
>
<div
style={{
lineHeight: 1.4,
}}
>
{props.label}
</div>
<div
style={{
display: "flex",
flex: "0 0 auto",
justifyContent: "flex-end",
marginInlineStart: "auto",
minWidth: "30%",
}}
>
{props.shortcuts.map((shortcut, index) => (
<React.Fragment key={index}>
<ShortcutKey>{shortcut}</ShortcutKey>
{props.isOr &&
index !== props.shortcuts.length - 1 &&
t("helpDialog.or")}
</React.Fragment>
))}
</div>
</div> </div>
</div> </div>
); );
}; };
Shortcut.defaultProps = {
isOr: true,
};
const ShortcutKey = (props: { children: React.ReactNode }) => ( const ShortcutKey = (props: { children: React.ReactNode }) => (
<kbd className="HelpDialog--key" {...props} /> <kbd className="HelpDialog__key" {...props} />
); );
export const HelpDialog = ({ onClose }: { onClose?: () => void }) => { export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
@@ -137,286 +122,316 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
> >
<Header /> <Header />
<Section title={t("helpDialog.shortcuts")}> <Section title={t("helpDialog.shortcuts")}>
<Columns> <ShortcutIsland
<Column> className="HelpDialog__island--tools"
<ShortcutIsland caption={t("helpDialog.tools")}> caption={t("helpDialog.tools")}
<Shortcut >
label={t("toolBar.selection")} <Shortcut label={t("toolBar.hand")} shortcuts={[KEYS.H]} />
shortcuts={["V", "1"]} <Shortcut
/> label={t("toolBar.selection")}
<Shortcut shortcuts={[KEYS.V, KEYS["1"]]}
label={t("toolBar.rectangle")} />
shortcuts={["R", "2"]} <Shortcut
/> label={t("toolBar.rectangle")}
<Shortcut label={t("toolBar.diamond")} shortcuts={["D", "3"]} /> shortcuts={[KEYS.R, KEYS["2"]]}
<Shortcut label={t("toolBar.ellipse")} shortcuts={["O", "4"]} /> />
<Shortcut label={t("toolBar.arrow")} shortcuts={["A", "5"]} /> <Shortcut
<Shortcut label={t("toolBar.line")} shortcuts={["P", "6"]} /> label={t("toolBar.diamond")}
<Shortcut shortcuts={[KEYS.D, KEYS["3"]]}
label={t("toolBar.freedraw")} />
shortcuts={["Shift + P", "X", "7"]} <Shortcut
/> label={t("toolBar.ellipse")}
<Shortcut label={t("toolBar.text")} shortcuts={["T", "8"]} /> shortcuts={[KEYS.O, KEYS["4"]]}
<Shortcut label={t("toolBar.image")} shortcuts={["9"]} /> />
<Shortcut label={t("toolBar.library")} shortcuts={["0"]} /> <Shortcut
<Shortcut label={t("toolBar.arrow")}
label={t("toolBar.eraser")} shortcuts={[KEYS.A, KEYS["5"]]}
shortcuts={[getShortcutKey("E")]} />
/> <Shortcut
<Shortcut label={t("toolBar.line")}
label={t("helpDialog.editSelectedShape")} shortcuts={[KEYS.L, KEYS["6"]]}
shortcuts={[ />
getShortcutKey("Enter"), <Shortcut
t("helpDialog.doubleClick"), label={t("toolBar.freedraw")}
]} shortcuts={[KEYS.P, KEYS["7"]]}
/> />
<Shortcut <Shortcut
label={t("helpDialog.textNewLine")} label={t("toolBar.text")}
shortcuts={[ shortcuts={[KEYS.T, KEYS["8"]]}
getShortcutKey("Enter"), />
getShortcutKey("Shift+Enter"), <Shortcut label={t("toolBar.image")} shortcuts={[KEYS["9"]]} />
]} <Shortcut
/> label={t("toolBar.eraser")}
<Shortcut shortcuts={[KEYS.E, KEYS["0"]]}
label={t("helpDialog.textFinish")} />
shortcuts={[ <Shortcut
getShortcutKey("Esc"), label={t("helpDialog.editSelectedShape")}
getShortcutKey("CtrlOrCmd+Enter"), shortcuts={[
]} getShortcutKey("CtrlOrCmd+Enter"),
/> getShortcutKey(`CtrlOrCmd + ${t("helpDialog.doubleClick")}`),
<Shortcut ]}
label={t("helpDialog.curvedArrow")} />
shortcuts={[ <Shortcut
"A", label={t("helpDialog.textNewLine")}
t("helpDialog.click"), shortcuts={[
t("helpDialog.click"), getShortcutKey("Enter"),
t("helpDialog.click"), getShortcutKey("Shift+Enter"),
]} ]}
isOr={false} />
/> <Shortcut
<Shortcut label={t("helpDialog.textFinish")}
label={t("helpDialog.curvedLine")} shortcuts={[
shortcuts={[ getShortcutKey("Esc"),
"L", getShortcutKey("CtrlOrCmd+Enter"),
t("helpDialog.click"), ]}
t("helpDialog.click"), />
t("helpDialog.click"), <Shortcut
]} label={t("helpDialog.curvedArrow")}
isOr={false} shortcuts={[
/> "A",
<Shortcut label={t("toolBar.lock")} shortcuts={["Q"]} /> t("helpDialog.click"),
<Shortcut t("helpDialog.click"),
label={t("helpDialog.preventBinding")} t("helpDialog.click"),
shortcuts={[getShortcutKey("CtrlOrCmd")]} ]}
/> isOr={false}
<Shortcut />
label={t("toolBar.link")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+K")]} label={t("helpDialog.curvedLine")}
/> shortcuts={[
</ShortcutIsland> "L",
<ShortcutIsland caption={t("helpDialog.view")}> t("helpDialog.click"),
<Shortcut t("helpDialog.click"),
label={t("buttons.zoomIn")} t("helpDialog.click"),
shortcuts={[getShortcutKey("CtrlOrCmd++")]} ]}
/> isOr={false}
<Shortcut />
label={t("buttons.zoomOut")} <Shortcut label={t("toolBar.lock")} shortcuts={[KEYS.Q]} />
shortcuts={[getShortcutKey("CtrlOrCmd+-")]} <Shortcut
/> label={t("helpDialog.preventBinding")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd")]}
label={t("buttons.resetZoom")} />
shortcuts={[getShortcutKey("CtrlOrCmd+0")]} <Shortcut
/> label={t("toolBar.link")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+K")]}
label={t("helpDialog.zoomToFit")} />
shortcuts={["Shift+1"]} </ShortcutIsland>
/> <ShortcutIsland
<Shortcut className="HelpDialog__island--view"
label={t("helpDialog.zoomToSelection")} caption={t("helpDialog.view")}
shortcuts={["Shift+2"]} >
/> <Shortcut
<Shortcut label={t("buttons.fullScreen")} shortcuts={["F"]} /> label={t("buttons.zoomIn")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd++")]}
label={t("buttons.zenMode")} />
shortcuts={[getShortcutKey("Alt+Z")]} <Shortcut
/> label={t("buttons.zoomOut")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+-")]}
label={t("labels.showGrid")} />
shortcuts={[getShortcutKey("CtrlOrCmd+'")]} <Shortcut
/> label={t("buttons.resetZoom")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+0")]}
label={t("labels.viewMode")} />
shortcuts={[getShortcutKey("Alt+R")]} <Shortcut
/> label={t("helpDialog.zoomToFit")}
<Shortcut shortcuts={["Shift+1"]}
label={t("labels.toggleTheme")} />
shortcuts={[getShortcutKey("Alt+Shift+D")]} <Shortcut
/> label={t("helpDialog.zoomToSelection")}
<Shortcut shortcuts={["Shift+2"]}
label={t("stats.title")} />
shortcuts={[getShortcutKey("Alt+/")]} <Shortcut
/> label={t("helpDialog.movePageUpDown")}
</ShortcutIsland> shortcuts={["PgUp/PgDn"]}
</Column> />
<Column> <Shortcut
<ShortcutIsland caption={t("helpDialog.editor")}> label={t("helpDialog.movePageLeftRight")}
<Shortcut shortcuts={["Shift+PgUp/PgDn"]}
label={t("labels.selectAll")} />
shortcuts={[getShortcutKey("CtrlOrCmd+A")]} <Shortcut label={t("buttons.fullScreen")} shortcuts={["F"]} />
/> <Shortcut
<Shortcut label={t("buttons.zenMode")}
label={t("labels.multiSelect")} shortcuts={[getShortcutKey("Alt+Z")]}
shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]} />
/> <Shortcut
<Shortcut label={t("labels.showGrid")}
label={t("helpDialog.deepSelect")} shortcuts={[getShortcutKey("CtrlOrCmd+'")]}
shortcuts={[ />
getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`), <Shortcut
]} label={t("labels.viewMode")}
/> shortcuts={[getShortcutKey("Alt+R")]}
<Shortcut />
label={t("helpDialog.deepBoxSelect")} <Shortcut
shortcuts={[ label={t("labels.toggleTheme")}
getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`), shortcuts={[getShortcutKey("Alt+Shift+D")]}
]} />
/> <Shortcut
<Shortcut label={t("stats.title")}
label={t("labels.moveCanvas")} shortcuts={[getShortcutKey("Alt+/")]}
shortcuts={[ />
getShortcutKey(`Space+${t("helpDialog.drag")}`), </ShortcutIsland>
getShortcutKey(`Wheel+${t("helpDialog.drag")}`), <ShortcutIsland
]} className="HelpDialog__island--editor"
isOr={true} caption={t("helpDialog.editor")}
/> >
<Shortcut <Shortcut
label={t("labels.cut")} label={t("labels.selectAll")}
shortcuts={[getShortcutKey("CtrlOrCmd+X")]} shortcuts={[getShortcutKey("CtrlOrCmd+A")]}
/> />
<Shortcut <Shortcut
label={t("labels.copy")} label={t("labels.multiSelect")}
shortcuts={[getShortcutKey("CtrlOrCmd+C")]} shortcuts={[getShortcutKey(`Shift+${t("helpDialog.click")}`)]}
/> />
<Shortcut <Shortcut
label={t("labels.paste")} label={t("helpDialog.deepSelect")}
shortcuts={[getShortcutKey("CtrlOrCmd+V")]} shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.click")}`)]}
/> />
<Shortcut <Shortcut
label={t("labels.copyAsPng")} label={t("helpDialog.deepBoxSelect")}
shortcuts={[getShortcutKey("Shift+Alt+C")]} shortcuts={[getShortcutKey(`CtrlOrCmd+${t("helpDialog.drag")}`)]}
/> />
<Shortcut <Shortcut
label={t("labels.copyStyles")} label={t("labels.moveCanvas")}
shortcuts={[getShortcutKey("CtrlOrCmd+Alt+C")]} shortcuts={[
/> getShortcutKey(`Space+${t("helpDialog.drag")}`),
<Shortcut getShortcutKey(`Wheel+${t("helpDialog.drag")}`),
label={t("labels.pasteStyles")} ]}
shortcuts={[getShortcutKey("CtrlOrCmd+Alt+V")]} isOr={true}
/> />
<Shortcut <Shortcut
label={t("labels.delete")} label={t("labels.cut")}
shortcuts={[getShortcutKey("Del")]} shortcuts={[getShortcutKey("CtrlOrCmd+X")]}
/> />
<Shortcut <Shortcut
label={t("labels.sendToBack")} label={t("labels.copy")}
shortcuts={[ shortcuts={[getShortcutKey("CtrlOrCmd+C")]}
isDarwin />
? getShortcutKey("CtrlOrCmd+Alt+[") <Shortcut
: getShortcutKey("CtrlOrCmd+Shift+["), label={t("labels.paste")}
]} shortcuts={[getShortcutKey("CtrlOrCmd+V")]}
/> />
<Shortcut <Shortcut
label={t("labels.bringToFront")} label={t("labels.pasteAsPlaintext")}
shortcuts={[ shortcuts={[getShortcutKey("CtrlOrCmd+Shift+V")]}
isDarwin />
? getShortcutKey("CtrlOrCmd+Alt+]") {/* firefox supports clipboard API under a flag, so we'll
: getShortcutKey("CtrlOrCmd+Shift+]"), show users what they can do in the error message */}
]} {(probablySupportsClipboardBlob || isFirefox) && (
/> <Shortcut
<Shortcut label={t("labels.copyAsPng")}
label={t("labels.sendBackward")} shortcuts={[getShortcutKey("Shift+Alt+C")]}
shortcuts={[getShortcutKey("CtrlOrCmd+[")]} />
/> )}
<Shortcut <Shortcut
label={t("labels.bringForward")} label={t("labels.copyStyles")}
shortcuts={[getShortcutKey("CtrlOrCmd+]")]} shortcuts={[getShortcutKey("CtrlOrCmd+Alt+C")]}
/> />
<Shortcut <Shortcut
label={t("labels.alignTop")} label={t("labels.pasteStyles")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Up")]} shortcuts={[getShortcutKey("CtrlOrCmd+Alt+V")]}
/> />
<Shortcut <Shortcut
label={t("labels.alignBottom")} label={t("labels.delete")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Down")]} shortcuts={[getShortcutKey("Delete")]}
/> />
<Shortcut <Shortcut
label={t("labels.alignLeft")} label={t("labels.sendToBack")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Left")]} shortcuts={[
/> isDarwin
<Shortcut ? getShortcutKey("CtrlOrCmd+Alt+[")
label={t("labels.alignRight")} : getShortcutKey("CtrlOrCmd+Shift+["),
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Right")]} ]}
/> />
<Shortcut <Shortcut
label={t("labels.duplicateSelection")} label={t("labels.bringToFront")}
shortcuts={[ shortcuts={[
getShortcutKey("CtrlOrCmd+D"), isDarwin
getShortcutKey(`Alt+${t("helpDialog.drag")}`), ? getShortcutKey("CtrlOrCmd+Alt+]")
]} : getShortcutKey("CtrlOrCmd+Shift+]"),
/> ]}
<Shortcut />
label={t("helpDialog.toggleElementLock")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+L")]} label={t("labels.sendBackward")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+[")]}
<Shortcut />
label={t("buttons.undo")} <Shortcut
shortcuts={[getShortcutKey("CtrlOrCmd+Z")]} label={t("labels.bringForward")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+]")]}
<Shortcut />
label={t("buttons.redo")} <Shortcut
shortcuts={ label={t("labels.alignTop")}
isWindows shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Up")]}
? [ />
getShortcutKey("CtrlOrCmd+Y"), <Shortcut
getShortcutKey("CtrlOrCmd+Shift+Z"), label={t("labels.alignBottom")}
] shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Down")]}
: [getShortcutKey("CtrlOrCmd+Shift+Z")] />
} <Shortcut
/> label={t("labels.alignLeft")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Left")]}
label={t("labels.group")} />
shortcuts={[getShortcutKey("CtrlOrCmd+G")]} <Shortcut
/> label={t("labels.alignRight")}
<Shortcut shortcuts={[getShortcutKey("CtrlOrCmd+Shift+Right")]}
label={t("labels.ungroup")} />
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]} <Shortcut
/> label={t("labels.duplicateSelection")}
<Shortcut shortcuts={[
label={t("labels.flipHorizontal")} getShortcutKey("CtrlOrCmd+D"),
shortcuts={[getShortcutKey("Shift+H")]} getShortcutKey(`Alt+${t("helpDialog.drag")}`),
/> ]}
<Shortcut />
label={t("labels.flipVertical")} <Shortcut
shortcuts={[getShortcutKey("Shift+V")]} label={t("helpDialog.toggleElementLock")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Shift+L")]}
<Shortcut />
label={t("labels.showStroke")} <Shortcut
shortcuts={[getShortcutKey("S")]} label={t("buttons.undo")}
/> shortcuts={[getShortcutKey("CtrlOrCmd+Z")]}
<Shortcut />
label={t("labels.showBackground")} <Shortcut
shortcuts={[getShortcutKey("G")]} label={t("buttons.redo")}
/> shortcuts={
<Shortcut isWindows
label={t("labels.decreaseFontSize")} ? [
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]} getShortcutKey("CtrlOrCmd+Y"),
/> getShortcutKey("CtrlOrCmd+Shift+Z"),
<Shortcut ]
label={t("labels.increaseFontSize")} : [getShortcutKey("CtrlOrCmd+Shift+Z")]
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]} }
/> />
</ShortcutIsland> <Shortcut
</Column> label={t("labels.group")}
</Columns> shortcuts={[getShortcutKey("CtrlOrCmd+G")]}
/>
<Shortcut
label={t("labels.ungroup")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+G")]}
/>
<Shortcut
label={t("labels.flipHorizontal")}
shortcuts={[getShortcutKey("Shift+H")]}
/>
<Shortcut
label={t("labels.flipVertical")}
shortcuts={[getShortcutKey("Shift+V")]}
/>
<Shortcut
label={t("labels.showStroke")}
shortcuts={[getShortcutKey("S")]}
/>
<Shortcut
label={t("labels.showBackground")}
shortcuts={[getShortcutKey("G")]}
/>
<Shortcut
label={t("labels.decreaseFontSize")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+<")]}
/>
<Shortcut
label={t("labels.increaseFontSize")}
shortcuts={[getShortcutKey("CtrlOrCmd+Shift+>")]}
/>
</ShortcutIsland>
</Section> </Section>
</Dialog> </Dialog>
</> </>

View File

@@ -14,20 +14,24 @@ $wide-viewport-width: 1000px;
top: 100%; top: 100%;
max-width: 100%; max-width: 100%;
width: 100%; width: 100%;
margin-top: 6px; margin-top: 0.5rem;
text-align: center; text-align: center;
color: $oc-gray-6; color: var(--color-gray-40);
font-size: 0.8rem; font-size: 0.75rem;
@include isMobile { @include isMobile {
position: static; position: static;
padding-right: 2em; padding-right: 2rem;
} }
> span { > span {
padding: 0.2rem 0.4rem; padding: 0.25rem;
background-color: var(--overlay-bg-color); }
border-radius: 4px; }
&.theme--dark {
.HintViewer {
color: var(--color-gray-60);
} }
} }
} }

View File

@@ -10,7 +10,8 @@
.picker { .picker {
background: var(--popup-bg-color); background: var(--popup-bg-color);
border: 0 solid transparentize($oc-white, 0.75); border: 0 solid transparentize($oc-white, 0.75);
box-shadow: transparentize($oc-black, 0.75) 0 1px 4px; // ˇˇ yeah, i dunno, open to suggestions here :D
box-shadow: rgb(0 0 0 / 25%) 2px 2px 4px 2px;
border-radius: 4px; border-radius: 4px;
position: absolute; position: absolute;
} }
@@ -46,7 +47,6 @@
margin: 0; margin: 0;
width: 36px; width: 36px;
height: 18px; height: 18px;
opacity: 0.6;
pointer-events: none; pointer-events: none;
} }
} }

View File

@@ -4,6 +4,7 @@ import { Popover } from "./Popover";
import "./IconPicker.scss"; import "./IconPicker.scss";
import { isArrowKey, KEYS } from "../keys"; import { isArrowKey, KEYS } from "../keys";
import { getLanguage } from "../i18n"; import { getLanguage } from "../i18n";
import clsx from "clsx";
function Picker<T>({ function Picker<T>({
options, options,
@@ -102,7 +103,9 @@ function Picker<T>({
<div className="picker-content" ref={rGallery}> <div className="picker-content" ref={rGallery}>
{options.map((option, i) => ( {options.map((option, i) => (
<button <button
className="picker-option" className={clsx("picker-option", {
active: value === option.value,
})}
onClick={(event) => { onClick={(event) => {
(event.currentTarget as HTMLButtonElement).focus(); (event.currentTarget as HTMLButtonElement).focus();
onChange(option.value); onChange(option.value);
@@ -150,7 +153,7 @@ export function IconPicker<T>({
const isRTL = getLanguage().rtl; const isRTL = getLanguage().rtl;
return ( return (
<label className={"picker-container"}> <div>
<button <button
name={group} name={group}
className={isActive ? "active" : ""} className={isActive ? "active" : ""}
@@ -184,6 +187,6 @@ export function IconPicker<T>({
</> </>
) : null} ) : null}
</React.Suspense> </React.Suspense>
</label> </div>
); );
} }

View File

@@ -1,22 +1,18 @@
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { probablySupportsClipboardBlob } from "../clipboard"; import { probablySupportsClipboardBlob } from "../clipboard";
import { canvasToBlob } from "../data/blob"; import { canvasToBlob } from "../data/blob";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { CanvasError } from "../errors";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "./App";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
import { exportToCanvas } from "../scene/export"; import { exportToCanvas } from "../scene/export";
import { AppState, BinaryFiles } from "../types"; import { AppState, BinaryFiles } from "../types";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { clipboard, exportImage } from "./icons"; import { clipboard } from "./icons";
import Stack from "./Stack"; import Stack from "./Stack";
import { ToolButton } from "./ToolButton";
import "./ExportDialog.scss"; import "./ExportDialog.scss";
import OpenColor from "open-color"; import OpenColor from "open-color";
import { CheckboxItem } from "./CheckboxItem"; import { CheckboxItem } from "./CheckboxItem";
import { DEFAULT_EXPORT_PADDING } from "../constants"; import { DEFAULT_EXPORT_PADDING, isFirefox } from "../constants";
import { nativeFileSystemSupported } from "../data/filesystem"; import { nativeFileSystemSupported } from "../data/filesystem";
import { ActionManager } from "../actions/manager"; import { ActionManager } from "../actions/manager";
@@ -35,19 +31,6 @@ export const ErrorCanvasPreview = () => {
); );
}; };
const renderPreview = (
content: HTMLCanvasElement | Error,
previewNode: HTMLDivElement,
) => {
unmountComponentAtNode(previewNode);
previewNode.innerHTML = "";
if (content instanceof HTMLCanvasElement) {
previewNode.appendChild(content);
} else {
render(<ErrorCanvasPreview />, previewNode);
}
};
export type ExportCB = ( export type ExportCB = (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
scale?: number, scale?: number,
@@ -101,6 +84,7 @@ const ImageExportModal = ({
const [exportSelected, setExportSelected] = useState(someElementIsSelected); const [exportSelected, setExportSelected] = useState(someElementIsSelected);
const previewRef = useRef<HTMLDivElement>(null); const previewRef = useRef<HTMLDivElement>(null);
const { exportBackground, viewBackgroundColor } = appState; const { exportBackground, viewBackgroundColor } = appState;
const [renderError, setRenderError] = useState<Error | null>(null);
const exportedElements = exportSelected const exportedElements = exportSelected
? getSelectedElements(elements, appState, true) ? getSelectedElements(elements, appState, true)
@@ -121,15 +105,16 @@ const ImageExportModal = ({
exportPadding, exportPadding,
}) })
.then((canvas) => { .then((canvas) => {
setRenderError(null);
// if converting to blob fails, there's some problem that will // if converting to blob fails, there's some problem that will
// likely prevent preview and export (e.g. canvas too big) // likely prevent preview and export (e.g. canvas too big)
return canvasToBlob(canvas).then(() => { return canvasToBlob(canvas).then(() => {
renderPreview(canvas, previewNode); previewNode.replaceChildren(canvas);
}); });
}) })
.catch((error) => { .catch((error) => {
console.error(error); console.error(error);
renderPreview(new CanvasError(), previewNode); setRenderError(error);
}); });
}, [ }, [
appState, appState,
@@ -142,7 +127,9 @@ const ImageExportModal = ({
return ( return (
<div className="ExportDialog"> <div className="ExportDialog">
<div className="ExportDialog__preview" ref={previewRef} /> <div className="ExportDialog__preview" ref={previewRef}>
{renderError && <ErrorCanvasPreview />}
</div>
{supportsContextFilters && {supportsContextFilters &&
actionManager.renderAction("exportWithDarkMode")} actionManager.renderAction("exportWithDarkMode")}
<div style={{ display: "grid", gridTemplateColumns: "1fr" }}> <div style={{ display: "grid", gridTemplateColumns: "1fr" }}>
@@ -203,7 +190,9 @@ const ImageExportModal = ({
> >
SVG SVG
</ExportButton> </ExportButton>
{probablySupportsClipboardBlob && ( {/* firefox supports clipboard API under a flag,
so let's throw and tell people what they can do */}
{(probablySupportsClipboardBlob || isFirefox) && (
<ExportButton <ExportButton
title={t("buttons.copyPngToClipboard")} title={t("buttons.copyPngToClipboard")}
onClick={() => onExportToClipboard(exportedElements)} onClick={() => onExportToClipboard(exportedElements)}
@@ -221,6 +210,7 @@ const ImageExportModal = ({
export const ImageExportDialog = ({ export const ImageExportDialog = ({
elements, elements,
appState, appState,
setAppState,
files, files,
exportPadding = DEFAULT_EXPORT_PADDING, exportPadding = DEFAULT_EXPORT_PADDING,
actionManager, actionManager,
@@ -229,6 +219,7 @@ export const ImageExportDialog = ({
onExportToClipboard, onExportToClipboard,
}: { }: {
appState: AppState; appState: AppState;
setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
files: BinaryFiles; files: BinaryFiles;
exportPadding?: number; exportPadding?: number;
@@ -237,26 +228,13 @@ export const ImageExportDialog = ({
onExportToSvg: ExportCB; onExportToSvg: ExportCB;
onExportToClipboard: ExportCB; onExportToClipboard: ExportCB;
}) => { }) => {
const [modalIsShown, setModalIsShown] = useState(false);
const handleClose = React.useCallback(() => { const handleClose = React.useCallback(() => {
setModalIsShown(false); setAppState({ openDialog: null });
}, []); }, [setAppState]);
return ( return (
<> <>
<ToolButton {appState.openDialog === "imageExport" && (
onClick={() => {
setModalIsShown(true);
}}
data-testid="image-export-button"
icon={exportImage}
type="button"
aria-label={t("buttons.exportImage")}
showAriaLabel={useDevice().isMobile}
title={t("buttons.exportImage")}
/>
{modalIsShown && (
<Dialog onCloseRequest={handleClose} title={t("buttons.exportImage")}> <Dialog onCloseRequest={handleClose} title={t("buttons.exportImage")}>
<ImageExportModal <ImageExportModal
elements={elements} elements={elements}

View File

@@ -1,6 +1,7 @@
.excalidraw { .excalidraw {
.Island { .Island {
--padding: 0; --padding: 0;
box-sizing: border-box;
background-color: var(--island-bg-color); background-color: var(--island-bg-color);
box-shadow: var(--shadow-island); box-shadow: var(--shadow-island);
border-radius: var(--border-radius-lg); border-radius: var(--border-radius-lg);

View File

@@ -1,10 +1,10 @@
import React, { useState } from "react"; import React from "react";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { useDevice } from "./App";
import { AppState, ExportOpts, BinaryFiles } from "../types"; import { AppState, ExportOpts, BinaryFiles } from "../types";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { exportFile, exportToFileIcon, link } from "./icons"; import { exportToFileIcon, LinkIcon } from "./icons";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import { actionSaveFileToDisk } from "../actions/actionExport"; import { actionSaveFileToDisk } from "../actions/actionExport";
import { Card } from "./Card"; import { Card } from "./Card";
@@ -63,7 +63,7 @@ const JSONExportModal = ({
)} )}
{onExportToBackend && ( {onExportToBackend && (
<Card color="pink"> <Card color="pink">
<div className="Card-icon">{link}</div> <div className="Card-icon">{LinkIcon}</div>
<h2>{t("exportDialog.link_title")}</h2> <h2>{t("exportDialog.link_title")}</h2>
<div className="Card-details">{t("exportDialog.link_details")}</div> <div className="Card-details">{t("exportDialog.link_details")}</div>
<ToolButton <ToolButton
@@ -93,6 +93,7 @@ export const JSONExportDialog = ({
actionManager, actionManager,
exportOpts, exportOpts,
canvas, canvas,
setAppState,
}: { }: {
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
appState: AppState; appState: AppState;
@@ -100,27 +101,15 @@ export const JSONExportDialog = ({
actionManager: ActionManager; actionManager: ActionManager;
exportOpts: ExportOpts; exportOpts: ExportOpts;
canvas: HTMLCanvasElement | null; canvas: HTMLCanvasElement | null;
setAppState: React.Component<any, AppState>["setState"];
}) => { }) => {
const [modalIsShown, setModalIsShown] = useState(false);
const handleClose = React.useCallback(() => { const handleClose = React.useCallback(() => {
setModalIsShown(false); setAppState({ openDialog: null });
}, []); }, [setAppState]);
return ( return (
<> <>
<ToolButton {appState.openDialog === "jsonExport" && (
onClick={() => {
setModalIsShown(true);
}}
data-testid="json-export-button"
icon={exportFile}
type="button"
aria-label={t("buttons.export")}
showAriaLabel={useDevice().isMobile}
title={t("buttons.export")}
/>
{modalIsShown && (
<Dialog onCloseRequest={handleClose} title={t("buttons.export")}> <Dialog onCloseRequest={handleClose} title={t("buttons.export")}>
<JSONExportModal <JSONExportModal
elements={elements} elements={elements}

View File

@@ -16,8 +16,10 @@
height: 100%; height: 100%;
pointer-events: none; pointer-events: none;
z-index: var(--zIndex-layerUI); z-index: var(--zIndex-layerUI);
&__top-right { &__top-right {
display: flex; display: flex;
gap: 0.75rem;
} }
&__footer { &__footer {
@@ -48,13 +50,6 @@
transform: translate(-999px, 0); transform: translate(-999px, 0);
} }
:root[dir="ltr"] &.layer-ui__wrapper__footer-left--transition-left {
transform: translate(-76px, 0);
}
:root[dir="rtl"] &.layer-ui__wrapper__footer-left--transition-left {
transform: translate(76px, 0);
}
&.layer-ui__wrapper__footer-left--transition-bottom { &.layer-ui__wrapper__footer-left--transition-bottom {
transform: translate(0, 92px); transform: translate(0, 92px);
} }
@@ -85,26 +80,15 @@
} }
} }
.layer-ui__wrapper__footer-center {
pointer-events: none;
& > * {
pointer-events: all;
}
}
.layer-ui__wrapper__footer-left, .layer-ui__wrapper__footer-left,
.layer-ui__wrapper__footer-right, .layer-ui__wrapper__footer-right,
.disable-zen-mode--visible { .disable-zen-mode--visible {
pointer-events: all; pointer-events: all;
} }
.layer-ui__wrapper__footer-left {
margin-bottom: 0.2em;
}
.layer-ui__wrapper__footer-right { .layer-ui__wrapper__footer-right {
margin-top: auto; margin-top: auto;
margin-bottom: auto; margin-bottom: auto;
margin-inline-end: 1em;
} }
} }
} }

View File

@@ -9,10 +9,8 @@ import { Language, t } from "../i18n";
import { calculateScrollCenter } from "../scene"; import { calculateScrollCenter } from "../scene";
import { ExportType } from "../scene/types"; import { ExportType } from "../scene/types";
import { AppProps, AppState, ExcalidrawProps, BinaryFiles } from "../types"; import { AppProps, AppState, ExcalidrawProps, BinaryFiles } from "../types";
import { muteFSAbortError } from "../utils"; import { isShallowEqual, muteFSAbortError } from "../utils";
import { SelectedShapeActions, ShapesSwitcher } from "./Actions"; import { SelectedShapeActions, ShapesSwitcher } from "./Actions";
import { BackgroundPickerAndDarkModeToggle } from "./BackgroundPickerAndDarkModeToggle";
import CollabButton from "./CollabButton";
import { ErrorDialog } from "./ErrorDialog"; import { ErrorDialog } from "./ErrorDialog";
import { ExportCB, ImageExportDialog } from "./ImageExportDialog"; import { ExportCB, ImageExportDialog } from "./ImageExportDialog";
import { FixedSideContainer } from "./FixedSideContainer"; import { FixedSideContainer } from "./FixedSideContainer";
@@ -39,10 +37,20 @@ import { trackEvent } from "../analytics";
import { useDevice } from "../components/App"; import { useDevice } from "../components/App";
import { Stats } from "./Stats"; import { Stats } from "./Stats";
import { actionToggleStats } from "../actions/actionToggleStats"; import { actionToggleStats } from "../actions/actionToggleStats";
import Footer from "./Footer"; import Footer from "./footer/Footer";
import { hostSidebarCountersAtom } from "./Sidebar/Sidebar"; import { hostSidebarCountersAtom } from "./Sidebar/Sidebar";
import { jotaiScope } from "../jotai"; import { jotaiScope } from "../jotai";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import MainMenu from "./main-menu/MainMenu";
import { ActiveConfirmDialog } from "./ActiveConfirmDialog";
import { HandButton } from "./HandButton";
import { isHandToolActive } from "../appState";
import {
mainMenuTunnel,
welcomeScreenMenuHintTunnel,
welcomeScreenToolbarHintTunnel,
welcomeScreenCenterTunnel,
} from "./tunnels";
interface LayerUIProps { interface LayerUIProps {
actionManager: ActionManager; actionManager: ActionManager;
@@ -51,15 +59,13 @@ interface LayerUIProps {
canvas: HTMLCanvasElement | null; canvas: HTMLCanvasElement | null;
setAppState: React.Component<any, AppState>["setState"]; setAppState: React.Component<any, AppState>["setState"];
elements: readonly NonDeletedExcalidrawElement[]; elements: readonly NonDeletedExcalidrawElement[];
onCollabButtonClick?: () => void;
onLockToggle: () => void; onLockToggle: () => void;
onHandToolToggle: () => void;
onPenModeToggle: () => void; onPenModeToggle: () => void;
onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void; onInsertElements: (elements: readonly NonDeletedExcalidrawElement[]) => void;
showExitZenModeBtn: boolean; showExitZenModeBtn: boolean;
langCode: Language["code"]; langCode: Language["code"];
isCollaborating: boolean;
renderTopRightUI?: ExcalidrawProps["renderTopRightUI"]; renderTopRightUI?: ExcalidrawProps["renderTopRightUI"];
renderCustomFooter?: ExcalidrawProps["renderFooter"];
renderCustomStats?: ExcalidrawProps["renderCustomStats"]; renderCustomStats?: ExcalidrawProps["renderCustomStats"];
renderCustomSidebar?: ExcalidrawProps["renderSidebar"]; renderCustomSidebar?: ExcalidrawProps["renderSidebar"];
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"]; libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
@@ -68,7 +74,36 @@ interface LayerUIProps {
library: Library; library: Library;
id: string; id: string;
onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void; onImageAction: (data: { insertOnCanvasDirectly: boolean }) => void;
renderWelcomeScreen: boolean;
children?: React.ReactNode;
} }
const DefaultMainMenu: React.FC<{
UIOptions: AppProps["UIOptions"];
}> = ({ UIOptions }) => {
return (
<MainMenu __fallback>
<MainMenu.DefaultItems.LoadScene />
<MainMenu.DefaultItems.SaveToActiveFile />
{/* FIXME we should to test for this inside the item itself */}
{UIOptions.canvasActions.export && <MainMenu.DefaultItems.Export />}
{/* FIXME we should to test for this inside the item itself */}
{UIOptions.canvasActions.saveAsImage && (
<MainMenu.DefaultItems.SaveAsImage />
)}
<MainMenu.DefaultItems.Help />
<MainMenu.DefaultItems.ClearCanvas />
<MainMenu.Separator />
<MainMenu.Group title="Excalidraw links">
<MainMenu.DefaultItems.Socials />
</MainMenu.Group>
<MainMenu.Separator />
<MainMenu.DefaultItems.ToggleTheme />
<MainMenu.DefaultItems.ChangeCanvasBackground />
</MainMenu>
);
};
const LayerUI = ({ const LayerUI = ({
actionManager, actionManager,
appState, appState,
@@ -76,14 +111,12 @@ const LayerUI = ({
setAppState, setAppState,
elements, elements,
canvas, canvas,
onCollabButtonClick,
onLockToggle, onLockToggle,
onHandToolToggle,
onPenModeToggle, onPenModeToggle,
onInsertElements, onInsertElements,
showExitZenModeBtn, showExitZenModeBtn,
isCollaborating,
renderTopRightUI, renderTopRightUI,
renderCustomFooter,
renderCustomStats, renderCustomStats,
renderCustomSidebar, renderCustomSidebar,
libraryReturnUrl, libraryReturnUrl,
@@ -92,6 +125,8 @@ const LayerUI = ({
library, library,
id, id,
onImageAction, onImageAction,
renderWelcomeScreen,
children,
}: LayerUIProps) => { }: LayerUIProps) => {
const device = useDevice(); const device = useDevice();
@@ -108,6 +143,7 @@ const LayerUI = ({
actionManager={actionManager} actionManager={actionManager}
exportOpts={UIOptions.canvasActions.export} exportOpts={UIOptions.canvasActions.export}
canvas={canvas} canvas={canvas}
setAppState={setAppState}
/> />
); );
}; };
@@ -151,6 +187,7 @@ const LayerUI = ({
<ImageExportDialog <ImageExportDialog
elements={elements} elements={elements}
appState={appState} appState={appState}
setAppState={setAppState}
files={files} files={files}
actionManager={actionManager} actionManager={actionManager}
onExportToPng={createExporter("png")} onExportToPng={createExporter("png")}
@@ -160,71 +197,19 @@ const LayerUI = ({
); );
}; };
const Separator = () => {
return <div style={{ width: ".625em" }} />;
};
const renderViewModeCanvasActions = () => {
return (
<Section
heading="canvasActions"
className={clsx("zen-mode-transition", {
"transition-left": appState.zenModeEnabled,
})}
>
{/* the zIndex ensures this menu has higher stacking order,
see https://github.com/excalidraw/excalidraw/pull/1445 */}
<Island padding={2} style={{ zIndex: 1 }}>
<Stack.Col gap={4}>
<Stack.Row gap={1} justifyContent="space-between">
{renderJSONExportDialog()}
{renderImageExportDialog()}
</Stack.Row>
</Stack.Col>
</Island>
</Section>
);
};
const renderCanvasActions = () => ( const renderCanvasActions = () => (
<Section <div style={{ position: "relative" }}>
heading="canvasActions" {/* wrapping to Fragment stops React from occasionally complaining
className={clsx("zen-mode-transition", { about identical Keys */}
"transition-left": appState.zenModeEnabled, <mainMenuTunnel.Out />
})} {renderWelcomeScreen && <welcomeScreenMenuHintTunnel.Out />}
> </div>
{/* the zIndex ensures this menu has higher stacking order,
see https://github.com/excalidraw/excalidraw/pull/1445 */}
<Island padding={2} style={{ zIndex: 1 }}>
<Stack.Col gap={4}>
<Stack.Row gap={1} justifyContent="space-between">
{actionManager.renderAction("clearCanvas")}
<Separator />
{actionManager.renderAction("loadScene")}
{renderJSONExportDialog()}
{renderImageExportDialog()}
<Separator />
{onCollabButtonClick && (
<CollabButton
isCollaborating={isCollaborating}
collaboratorCount={appState.collaborators.size}
onClick={onCollabButtonClick}
/>
)}
</Stack.Row>
<BackgroundPickerAndDarkModeToggle actionManager={actionManager} />
{appState.fileHandle && (
<>{actionManager.renderAction("saveToActiveFile")}</>
)}
</Stack.Col>
</Island>
</Section>
); );
const renderSelectedShapeActions = () => ( const renderSelectedShapeActions = () => (
<Section <Section
heading="selectedShapeActions" heading="selectedShapeActions"
className={clsx("zen-mode-transition", { className={clsx("selected-shape-actions zen-mode-transition", {
"transition-left": appState.zenModeEnabled, "transition-left": appState.zenModeEnabled,
})} })}
> >
@@ -232,10 +217,9 @@ 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 subtracting 200 // we want to make sure this doesn't overflow so subtracting the
// which is approximately height of zoom footer and top left menu items with some buffer // approximate height of hamburgerMenu + footer
// if active file name is displayed, subtracting 248 to account for its height maxHeight: `${appState.height - 166}px`,
maxHeight: `${appState.height - (appState.fileHandle ? 248 : 200)}px`,
}} }}
> >
<SelectedShapeActions <SelectedShapeActions
@@ -257,72 +241,80 @@ const LayerUI = ({
<FixedSideContainer side="top"> <FixedSideContainer side="top">
<div className="App-menu App-menu_top"> <div className="App-menu App-menu_top">
<Stack.Col <Stack.Col
gap={4} gap={6}
className={clsx({ className={clsx("App-menu_top__left", {
"disable-pointerEvents": appState.zenModeEnabled, "disable-pointerEvents": appState.zenModeEnabled,
})} })}
> >
{appState.viewModeEnabled {renderCanvasActions()}
? renderViewModeCanvasActions()
: renderCanvasActions()}
{shouldRenderSelectedShapeActions && renderSelectedShapeActions()} {shouldRenderSelectedShapeActions && renderSelectedShapeActions()}
</Stack.Col> </Stack.Col>
{!appState.viewModeEnabled && ( {!appState.viewModeEnabled && (
<Section heading="shapes"> <Section heading="shapes" className="shapes-section">
{(heading: React.ReactNode) => ( {(heading: React.ReactNode) => (
<Stack.Col gap={4} align="start"> <div style={{ position: "relative" }}>
<Stack.Row {renderWelcomeScreen && (
gap={1} <welcomeScreenToolbarHintTunnel.Out />
className={clsx("App-toolbar-container", { )}
"zen-mode": appState.zenModeEnabled, <Stack.Col gap={4} align="start">
})} <Stack.Row
> gap={1}
<PenModeButton className={clsx("App-toolbar-container", {
zenModeEnabled={appState.zenModeEnabled}
checked={appState.penMode}
onChange={onPenModeToggle}
title={t("toolBar.penMode")}
penDetected={appState.penDetected}
/>
<LockButton
zenModeEnabled={appState.zenModeEnabled}
checked={appState.activeTool.locked}
onChange={() => onLockToggle()}
title={t("toolBar.lock")}
/>
<Island
padding={1}
className={clsx("App-toolbar", {
"zen-mode": appState.zenModeEnabled, "zen-mode": appState.zenModeEnabled,
})} })}
> >
<HintViewer <Island
appState={appState} padding={1}
elements={elements} className={clsx("App-toolbar", {
isMobile={device.isMobile} "zen-mode": appState.zenModeEnabled,
device={device} })}
/> >
{heading} <HintViewer
<Stack.Row gap={1}>
<ShapesSwitcher
appState={appState} appState={appState}
canvas={canvas} elements={elements}
activeTool={appState.activeTool} isMobile={device.isMobile}
setAppState={setAppState} device={device}
onImageAction={({ pointerType }) => {
onImageAction({
insertOnCanvasDirectly: pointerType !== "mouse",
});
}}
/> />
</Stack.Row> {heading}
</Island> <Stack.Row gap={1}>
<LibraryButton <PenModeButton
appState={appState} zenModeEnabled={appState.zenModeEnabled}
setAppState={setAppState} checked={appState.penMode}
/> onChange={onPenModeToggle}
</Stack.Row> title={t("toolBar.penMode")}
</Stack.Col> penDetected={appState.penDetected}
/>
<LockButton
checked={appState.activeTool.locked}
onChange={onLockToggle}
title={t("toolBar.lock")}
/>
<div className="App-toolbar__divider"></div>
<HandButton
checked={isHandToolActive(appState)}
onChange={() => onHandToolToggle()}
title={t("toolBar.hand")}
isMobile
/>
<ShapesSwitcher
appState={appState}
canvas={canvas}
activeTool={appState.activeTool}
setAppState={setAppState}
onImageAction={({ pointerType }) => {
onImageAction({
insertOnCanvasDirectly: pointerType !== "mouse",
});
}}
/>
</Stack.Row>
</Island>
</Stack.Row>
</Stack.Col>
</div>
)} )}
</Section> </Section>
)} )}
@@ -334,11 +326,11 @@ const LayerUI = ({
}, },
)} )}
> >
<UserList <UserList collaborators={appState.collaborators} />
collaborators={appState.collaborators}
actionManager={actionManager}
/>
{renderTopRightUI?.(device.isMobile, appState)} {renderTopRightUI?.(device.isMobile, appState)}
{!appState.viewModeEnabled && (
<LibraryButton appState={appState} setAppState={setAppState} />
)}
</div> </div>
</div> </div>
</FixedSideContainer> </FixedSideContainer>
@@ -364,6 +356,16 @@ const LayerUI = ({
return ( return (
<> <>
{/* ------------------------- tunneled UI ---------------------------- */}
{/* make sure we render host app components first so that we can detect
them first on initial render to optimize layout shift */}
{children}
{/* render component fallbacks. Can be rendered anywhere as they'll be
tunneled away. We only render tunneled components that actually
have defaults when host do not render anything. */}
<DefaultMainMenu UIOptions={UIOptions} />
{/* ------------------------------------------------------------------ */}
{appState.isLoading && <LoadingMessage delay={250} />} {appState.isLoading && <LoadingMessage delay={250} />}
{appState.errorMessage && ( {appState.errorMessage && (
<ErrorDialog <ErrorDialog
@@ -371,13 +373,16 @@ const LayerUI = ({
onClose={() => setAppState({ errorMessage: null })} onClose={() => setAppState({ errorMessage: null })}
/> />
)} )}
{appState.showHelpDialog && ( {appState.openDialog === "help" && (
<HelpDialog <HelpDialog
onClose={() => { onClose={() => {
setAppState({ showHelpDialog: false }); setAppState({ openDialog: null });
}} }}
/> />
)} )}
<ActiveConfirmDialog />
{renderImageExportDialog()}
{renderJSONExportDialog()}
{appState.pasteDialog.shown && ( {appState.pasteDialog.shown && (
<PasteChartDialog <PasteChartDialog
setAppState={setAppState} setAppState={setAppState}
@@ -398,12 +403,10 @@ const LayerUI = ({
renderJSONExportDialog={renderJSONExportDialog} renderJSONExportDialog={renderJSONExportDialog}
renderImageExportDialog={renderImageExportDialog} renderImageExportDialog={renderImageExportDialog}
setAppState={setAppState} setAppState={setAppState}
onCollabButtonClick={onCollabButtonClick} onLockToggle={onLockToggle}
onLockToggle={() => onLockToggle()} onHandToolToggle={onHandToolToggle}
onPenModeToggle={onPenModeToggle} onPenModeToggle={onPenModeToggle}
canvas={canvas} canvas={canvas}
isCollaborating={isCollaborating}
renderCustomFooter={renderCustomFooter}
onImageAction={onImageAction} onImageAction={onImageAction}
renderTopRightUI={renderTopRightUI} renderTopRightUI={renderTopRightUI}
renderCustomStats={renderCustomStats} renderCustomStats={renderCustomStats}
@@ -431,12 +434,13 @@ const LayerUI = ({
: {} : {}
} }
> >
{renderWelcomeScreen && <welcomeScreenCenterTunnel.Out />}
{renderFixedSideContainer()} {renderFixedSideContainer()}
<Footer <Footer
appState={appState} appState={appState}
actionManager={actionManager} actionManager={actionManager}
renderCustomFooter={renderCustomFooter}
showExitZenModeBtn={showExitZenModeBtn} showExitZenModeBtn={showExitZenModeBtn}
renderWelcomeScreen={renderWelcomeScreen}
/> />
{appState.showStats && ( {appState.showStats && (
<Stats <Stats
@@ -469,29 +473,39 @@ const LayerUI = ({
); );
}; };
const areEqual = (prev: LayerUIProps, next: LayerUIProps) => { const stripIrrelevantAppStateProps = (
const getNecessaryObj = (appState: AppState): Partial<AppState> => { appState: AppState,
const { ): Partial<AppState> => {
suggestedBindings, const { suggestedBindings, startBoundElement, cursorButton, ...ret } =
startBoundElement: boundElement, appState;
...ret return ret;
} = appState; };
return ret;
};
const prevAppState = getNecessaryObj(prev.appState);
const nextAppState = getNecessaryObj(next.appState);
const keys = Object.keys(prevAppState) as (keyof Partial<AppState>)[]; const areEqual = (prevProps: LayerUIProps, nextProps: LayerUIProps) => {
// short-circuit early
if (prevProps.children !== nextProps.children) {
return false;
}
const {
canvas: _prevCanvas,
// not stable, but shouldn't matter in our case
onInsertElements: _prevOnInsertElements,
appState: prevAppState,
...prev
} = prevProps;
const {
canvas: _nextCanvas,
onInsertElements: _nextOnInsertElements,
appState: nextAppState,
...next
} = nextProps;
return ( return (
prev.renderCustomFooter === next.renderCustomFooter && isShallowEqual(
prev.renderTopRightUI === next.renderTopRightUI && stripIrrelevantAppStateProps(prevAppState),
prev.renderCustomStats === next.renderCustomStats && stripIrrelevantAppStateProps(nextAppState),
prev.renderCustomSidebar === next.renderCustomSidebar && ) && isShallowEqual(prev, next)
prev.langCode === next.langCode &&
prev.elements === next.elements &&
prev.files === next.files &&
keys.every((key) => prevAppState[key] === nextAppState[key])
); );
}; };

View File

@@ -0,0 +1,32 @@
@import "../css/variables.module";
.library-button {
@include outlineButtonStyles;
background-color: var(--island-bg-color);
width: auto;
height: var(--lg-button-size);
display: flex;
align-items: center;
gap: 0.5rem;
line-height: 0;
font-size: 0.75rem;
letter-spacing: 0.4px;
svg {
width: var(--lg-icon-size);
height: var(--lg-icon-size);
}
&__label {
display: none;
@media screen and (min-width: 1024px) {
display: block;
}
}
}

View File

@@ -1,19 +1,11 @@
import React from "react"; import React from "react";
import clsx from "clsx";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppState } from "../types"; import { AppState } from "../types";
import { capitalizeString } from "../utils"; import { capitalizeString } from "../utils";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { useDevice } from "./App"; import { useDevice } from "./App";
import "./LibraryButton.scss";
const LIBRARY_ICON = ( import { LibraryIcon } from "./icons";
<svg viewBox="0 0 576 512">
<path
fill="currentColor"
d="M542.22 32.05c-54.8 3.11-163.72 14.43-230.96 55.59-4.64 2.84-7.27 7.89-7.27 13.17v363.87c0 11.55 12.63 18.85 23.28 13.49 69.18-34.82 169.23-44.32 218.7-46.92 16.89-.89 30.02-14.43 30.02-30.66V62.75c.01-17.71-15.35-31.74-33.77-30.7zM264.73 87.64C197.5 46.48 88.58 35.17 33.78 32.05 15.36 31.01 0 45.04 0 62.75V400.6c0 16.24 13.13 29.78 30.02 30.66 49.49 2.6 149.59 12.11 218.77 46.95 10.62 5.35 23.21-1.94 23.21-13.46V100.63c0-5.29-2.62-10.14-7.27-12.99z"
></path>
</svg>
);
export const LibraryButton: React.FC<{ export const LibraryButton: React.FC<{
appState: AppState; appState: AppState;
@@ -21,17 +13,16 @@ export const LibraryButton: React.FC<{
isMobile?: boolean; isMobile?: boolean;
}> = ({ appState, setAppState, isMobile }) => { }> = ({ appState, setAppState, isMobile }) => {
const device = useDevice(); const device = useDevice();
const showLabel = !isMobile;
// TODO barnabasmolnar/redesign
// not great, toolbar jumps in a jarring manner
if (appState.isSidebarDocked && appState.openSidebar === "library") {
return null;
}
return ( return (
<label <label title={`${capitalizeString(t("toolBar.library"))}`}>
className={clsx(
"ToolIcon ToolIcon_type_floating ToolIcon__library",
`ToolIcon_size_medium`,
{
"is-mobile": isMobile,
},
)}
title={`${capitalizeString(t("toolBar.library"))} — 0`}
>
<input <input
className="ToolIcon_type_checkbox" className="ToolIcon_type_checkbox"
type="checkbox" type="checkbox"
@@ -55,7 +46,12 @@ export const LibraryButton: React.FC<{
aria-label={capitalizeString(t("toolBar.library"))} aria-label={capitalizeString(t("toolBar.library"))}
aria-keyshortcuts="0" aria-keyshortcuts="0"
/> />
<div className="ToolIcon__icon">{LIBRARY_ICON}</div> <div className="library-button">
<div>{LibraryIcon}</div>
{showLabel && (
<div className="library-button__label">{t("toolBar.library")}</div>
)}
</div>
</label> </label>
); );
}; };

View File

@@ -35,103 +35,32 @@
} }
} }
.library-actions { .library-actions-counter {
width: 100%; background-color: var(--color-primary);
color: var(--color-primary-light);
font-weight: bold;
display: flex; display: flex;
margin-right: auto;
align-items: center; align-items: center;
justify-content: center;
button .library-actions-counter { border-radius: 50%;
position: absolute; width: 1rem;
right: 2px; height: 1rem;
bottom: 2px; position: absolute;
border-radius: 50%; bottom: -0.25rem;
width: 1em; right: -0.25rem;
height: 1em; font-size: 0.625rem;
padding: 1px; pointer-events: none;
font-size: 0.7rem;
background: #fff;
}
&--remove {
background-color: $oc-red-7;
&:hover {
background-color: $oc-red-8;
}
&:active {
background-color: $oc-red-9;
}
svg {
color: $oc-white;
}
.library-actions-counter {
color: $oc-red-7;
}
}
&--export {
background-color: $oc-lime-5;
&:hover {
background-color: $oc-lime-7;
}
&:active {
background-color: $oc-lime-8;
}
svg {
color: $oc-white;
}
.library-actions-counter {
color: $oc-lime-5;
}
}
&--publish {
background-color: $oc-cyan-6;
&:hover {
background-color: $oc-cyan-7;
}
&:active {
background-color: $oc-cyan-9;
}
svg {
color: $oc-white;
}
label {
margin-left: -0.2em;
margin-right: 1.1em;
color: $oc-white;
font-size: 0.86em;
}
.library-actions-counter {
color: $oc-cyan-6;
}
}
&--load {
background-color: $oc-blue-6;
&:hover {
background-color: $oc-blue-7;
}
&:active {
background-color: $oc-blue-9;
}
svg {
color: $oc-white;
}
}
} }
.layer-ui__library-message { .layer-ui__library-message {
padding: 2em 4em; padding: 2rem;
min-width: 200px; min-width: 200px;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
.Spinner { flex-grow: 1;
margin-bottom: 1em; justify-content: center;
}
span { span {
font-size: 0.8em; font-size: 0.8em;
} }
@@ -159,11 +88,10 @@
} }
.library-menu-browse-button { .library-menu-browse-button {
width: 80%; margin: 1rem auto;
min-height: 22px;
margin: 0 auto; padding: 0.875rem 1rem;
margin-top: 1rem;
padding: 10px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
@@ -176,6 +104,10 @@
text-align: center; text-align: center;
white-space: nowrap; white-space: nowrap;
text-decoration: none !important; text-decoration: none !important;
font-weight: 600;
font-size: 0.75rem;
&:hover { &:hover {
background-color: var(--color-primary-darker); background-color: var(--color-primary-darker);
} }
@@ -184,6 +116,12 @@
} }
} }
&.theme--dark {
.library-menu-browse-button {
color: var(--color-gray-100);
}
}
.library-menu-browse-button--mobile { .library-menu-browse-button--mobile {
min-height: 22px; min-height: 22px;
margin-left: auto; margin-left: auto;
@@ -191,4 +129,27 @@
padding-right: 0; padding-right: 0;
} }
} }
.layer-ui__sidebar__header .dropdown-menu {
&.dropdown-menu--mobile {
top: 100%;
}
.dropdown-menu-container {
--gap: 0;
z-index: 1;
position: absolute;
top: 100%;
left: 0;
:root[dir="rtl"] & {
right: 0;
left: auto;
}
width: 196px;
box-shadow: var(--library-dropdown-shadow);
border-radius: var(--border-radius-lg);
padding: 0.25rem 0.5rem;
}
}
} }

View File

@@ -16,7 +16,7 @@ import { LibraryItems, LibraryItem, AppState, ExcalidrawProps } from "../types";
import "./LibraryMenu.scss"; import "./LibraryMenu.scss";
import LibraryMenuItems from "./LibraryMenuItems"; import LibraryMenuItems from "./LibraryMenuItems";
import { EVENT, VERSIONS } from "../constants"; import { EVENT } from "../constants";
import { KEYS } from "../keys"; import { KEYS } from "../keys";
import { trackEvent } from "../analytics"; import { trackEvent } from "../analytics";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
@@ -31,6 +31,7 @@ import { Sidebar } from "./Sidebar/Sidebar";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { LibraryMenuHeader } from "./LibraryMenuHeaderContent"; import { LibraryMenuHeader } from "./LibraryMenuHeaderContent";
import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton";
const useOnClickOutside = ( const useOnClickOutside = (
ref: RefObject<HTMLElement>, ref: RefObject<HTMLElement>,
@@ -94,9 +95,6 @@ export const LibraryMenuContent = ({
selectedItems: LibraryItem["id"][]; selectedItems: LibraryItem["id"][];
onSelectItems: (id: LibraryItem["id"][]) => void; onSelectItems: (id: LibraryItem["id"][]) => void;
}) => { }) => {
const referrer =
libraryReturnUrl || window.location.origin + window.location.pathname;
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope); const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
const addToLibrary = useCallback( const addToLibrary = useCallback(
@@ -131,13 +129,18 @@ export const LibraryMenuContent = ({
return ( return (
<LibraryMenuWrapper> <LibraryMenuWrapper>
<div className="layer-ui__library-message"> <div className="layer-ui__library-message">
<Spinner size="2em" /> <div>
<span>{t("labels.libraryLoadingMessage")}</span> <Spinner size="2em" />
<span>{t("labels.libraryLoadingMessage")}</span>
</div>
</div> </div>
</LibraryMenuWrapper> </LibraryMenuWrapper>
); );
} }
const showBtn =
libraryItemsData.libraryItems.length > 0 || pendingElements.length > 0;
return ( return (
<LibraryMenuWrapper> <LibraryMenuWrapper>
<LibraryMenuItems <LibraryMenuItems
@@ -150,18 +153,17 @@ export const LibraryMenuContent = ({
pendingElements={pendingElements} pendingElements={pendingElements}
selectedItems={selectedItems} selectedItems={selectedItems}
onSelectItems={onSelectItems} onSelectItems={onSelectItems}
id={id}
libraryReturnUrl={libraryReturnUrl}
theme={appState.theme}
/> />
<a {showBtn && (
className="library-menu-browse-button" <LibraryMenuBrowseButton
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${ id={id}
window.name || "_blank" libraryReturnUrl={libraryReturnUrl}
}&referrer=${referrer}&useHash=true&token=${id}&theme=${ theme={appState.theme}
appState.theme />
}&version=${VERSIONS.excalidrawLibrary}`} )}
target="_excalidraw_libraries"
>
{t("labels.libraries")}
</a>
</LibraryMenuWrapper> </LibraryMenuWrapper>
); );
}; };
@@ -265,6 +267,7 @@ export const LibraryMenu: React.FC<{
// is colled correctly // is colled correctly
key="library" key="library"
className="layer-ui__library-sidebar" className="layer-ui__library-sidebar"
initialDockedState={appState.isSidebarDocked}
onDock={(docked) => { onDock={(docked) => {
trackEvent( trackEvent(
"library", "library",

View File

@@ -0,0 +1,31 @@
import { VERSIONS } from "../constants";
import { t } from "../i18n";
import { AppState, ExcalidrawProps } from "../types";
const LibraryMenuBrowseButton = ({
theme,
id,
libraryReturnUrl,
}: {
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
theme: AppState["theme"];
id: string;
}) => {
const referrer =
libraryReturnUrl || window.location.origin + window.location.pathname;
return (
<a
className="library-menu-browse-button"
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
window.name || "_blank"
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}&version=${
VERSIONS.excalidrawLibrary
}`}
target="_excalidraw_libraries"
>
{t("labels.libraries")}
</a>
);
};
export default LibraryMenuBrowseButton;

View File

@@ -3,17 +3,26 @@ import { saveLibraryAsJSON } from "../data/json";
import Library, { libraryItemsAtom } from "../data/library"; import Library, { libraryItemsAtom } from "../data/library";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppState, LibraryItem, LibraryItems } from "../types"; import { AppState, LibraryItem, LibraryItems } from "../types";
import { exportToFileIcon, load, publishIcon, trash } from "./icons"; import {
DotsIcon,
ExportIcon,
LoadIcon,
publishIcon,
TrashIcon,
} from "./icons";
import { ToolButton } from "./ToolButton"; import { ToolButton } from "./ToolButton";
import { Tooltip } from "./Tooltip";
import { fileOpen } from "../data/filesystem"; import { fileOpen } from "../data/filesystem";
import { muteFSAbortError } from "../utils"; import { muteFSAbortError } from "../utils";
import { useAtom } from "jotai"; import { atom, useAtom } from "jotai";
import { jotaiScope } from "../jotai"; import { jotaiScope } from "../jotai";
import ConfirmDialog from "./ConfirmDialog"; import ConfirmDialog from "./ConfirmDialog";
import PublishLibrary from "./PublishLibrary"; import PublishLibrary from "./PublishLibrary";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import DropdownMenu from "./dropdownMenu/DropdownMenu";
export const isLibraryMenuOpenAtom = atom(false);
const getSelectedItems = ( const getSelectedItems = (
libraryItems: LibraryItems, libraryItems: LibraryItems,
selectedItems: LibraryItem["id"][], selectedItems: LibraryItem["id"][],
@@ -37,7 +46,9 @@ export const LibraryMenuHeader: React.FC<{
appState, appState,
}) => { }) => {
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope); const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
const [isLibraryMenuOpen, setIsLibraryMenuOpen] = useAtom(
isLibraryMenuOpenAtom,
);
const renderRemoveLibAlert = useCallback(() => { const renderRemoveLibAlert = useCallback(() => {
const content = selectedItems.length const content = selectedItems.length
? t("alerts.removeItemsFromsLibrary", { count: selectedItems.length }) ? t("alerts.removeItemsFromsLibrary", { count: selectedItems.length })
@@ -165,8 +176,65 @@ export const LibraryMenuHeader: React.FC<{
}); });
}; };
const renderLibraryMenu = () => {
return (
<DropdownMenu open={isLibraryMenuOpen}>
<DropdownMenu.Trigger
className="Sidebar__dropdown-btn"
onToggle={() => setIsLibraryMenuOpen(!isLibraryMenuOpen)}
>
{DotsIcon}
</DropdownMenu.Trigger>
<DropdownMenu.Content
onClickOutside={() => setIsLibraryMenuOpen(false)}
onSelect={() => setIsLibraryMenuOpen(false)}
className="library-menu"
>
{!itemsSelected && (
<DropdownMenu.Item
onSelect={onLibraryImport}
icon={LoadIcon}
data-testid="lib-dropdown--load"
>
{t("buttons.load")}
</DropdownMenu.Item>
)}
{!!items.length && (
<DropdownMenu.Item
onSelect={onLibraryExport}
icon={ExportIcon}
data-testid="lib-dropdown--export"
>
{t("buttons.export")}
</DropdownMenu.Item>
)}
{!!items.length && (
<DropdownMenu.Item
onSelect={() => setShowRemoveLibAlert(true)}
icon={TrashIcon}
>
{resetLabel}
</DropdownMenu.Item>
)}
{itemsSelected && (
<DropdownMenu.Item
icon={publishIcon}
onSelect={() => setShowPublishLibraryDialog(true)}
data-testid="lib-dropdown--remove"
>
{t("buttons.publishLibrary")}
</DropdownMenu.Item>
)}
</DropdownMenu.Content>
</DropdownMenu>
);
};
return ( return (
<div className="library-actions"> <div style={{ position: "relative" }}>
{renderLibraryMenu()}
{selectedItems.length > 0 && (
<div className="library-actions-counter">{selectedItems.length}</div>
)}
{showRemoveLibAlert && renderRemoveLibAlert()} {showRemoveLibAlert && renderRemoveLibAlert()}
{showPublishLibraryDialog && ( {showPublishLibraryDialog && (
<PublishLibrary <PublishLibrary
@@ -189,70 +257,6 @@ export const LibraryMenuHeader: React.FC<{
/> />
)} )}
{publishLibSuccess && renderPublishSuccess()} {publishLibSuccess && renderPublishSuccess()}
{!itemsSelected && (
<ToolButton
key="import"
type="button"
title={t("buttons.load")}
aria-label={t("buttons.load")}
icon={load}
onClick={onLibraryImport}
className="library-actions--load"
/>
)}
{!!items.length && (
<>
<ToolButton
key="export"
type="button"
title={t("buttons.export")}
aria-label={t("buttons.export")}
icon={exportToFileIcon}
onClick={onLibraryExport}
className="library-actions--export"
>
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
<ToolButton
key="reset"
type="button"
title={resetLabel}
aria-label={resetLabel}
icon={trash}
onClick={() => setShowRemoveLibAlert(true)}
className="library-actions--remove"
>
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
</>
)}
{itemsSelected && (
<Tooltip label={t("hints.publishLibrary")}>
<ToolButton
type="button"
aria-label={t("buttons.publishLibrary")}
label={t("buttons.publishLibrary")}
icon={publishIcon}
className="library-actions--publish"
onClick={() => setShowPublishLibraryDialog(true)}
>
<label>{t("buttons.publishLibrary")}</label>
{selectedItems.length > 0 && (
<span className="library-actions-counter">
{selectedItems.length}
</span>
)}
</ToolButton>
</Tooltip>
)}
</div> </div>
); );
}; };

View File

@@ -1,18 +1,70 @@
@import "open-color/open-color"; @import "open-color/open-color";
.excalidraw { .excalidraw {
--container-padding-y: 1.5rem;
--container-padding-x: 0.75rem;
.library-menu-items__no-items {
text-align: center;
color: var(--color-gray-70);
line-height: 1.5;
font-size: 0.875rem;
width: 100%;
&__label {
color: var(--color-primary);
font-weight: bold;
font-size: 1.125rem;
margin-bottom: 0.75rem;
}
}
&.theme--dark {
.library-menu-items__no-items {
color: var(--color-gray-40);
}
}
.library-menu-items-container { .library-menu-items-container {
display: flex; display: flex;
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
overflow-y: auto;
flex-direction: column; flex-direction: column;
height: 100%; height: 100%;
justify-content: center;
margin: 0;
border-bottom: 1px solid var(--sidebar-border-color);
position: relative;
&__row {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1rem;
}
&__items { &__items {
row-gap: 0.5rem;
padding: var(--container-padding-y) var(--container-padding-x);
flex: 1; flex: 1;
overflow-y: auto; overflow-y: auto;
overflow-x: hidden; overflow-x: hidden;
margin-bottom: 1rem; margin-bottom: 1rem;
} }
&__header {
color: var(--color-primary);
font-size: 1.125rem;
font-weight: bold;
margin-bottom: 0.75rem;
&--excal {
margin-top: 2.5rem;
}
}
.separator { .separator {
width: 100%; width: 100%;
display: flex; display: flex;

View File

@@ -2,7 +2,7 @@ import React, { useState } from "react";
import { serializeLibraryAsJSON } from "../data/json"; import { serializeLibraryAsJSON } from "../data/json";
import { ExcalidrawElement, NonDeleted } from "../element/types"; import { ExcalidrawElement, NonDeleted } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { LibraryItem, LibraryItems } from "../types"; import { AppState, ExcalidrawProps, LibraryItem, LibraryItems } from "../types";
import { arrayToMap, chunk } from "../utils"; import { arrayToMap, chunk } from "../utils";
import { LibraryUnit } from "./LibraryUnit"; import { LibraryUnit } from "./LibraryUnit";
import Stack from "./Stack"; import Stack from "./Stack";
@@ -10,6 +10,8 @@ import Stack from "./Stack";
import "./LibraryMenuItems.scss"; import "./LibraryMenuItems.scss";
import { MIME_TYPES } from "../constants"; import { MIME_TYPES } from "../constants";
import Spinner from "./Spinner"; import Spinner from "./Spinner";
import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton";
import clsx from "clsx";
const CELLS_PER_ROW = 4; const CELLS_PER_ROW = 4;
@@ -21,6 +23,9 @@ const LibraryMenuItems = ({
pendingElements, pendingElements,
selectedItems, selectedItems,
onSelectItems, onSelectItems,
theme,
id,
libraryReturnUrl,
}: { }: {
isLoading: boolean; isLoading: boolean;
libraryItems: LibraryItems; libraryItems: LibraryItems;
@@ -29,6 +34,9 @@ const LibraryMenuItems = ({
onAddToLibrary: (elements: LibraryItem["elements"]) => void; onAddToLibrary: (elements: LibraryItem["elements"]) => void;
selectedItems: LibraryItem["id"][]; selectedItems: LibraryItem["id"][];
onSelectItems: (id: LibraryItem["id"][]) => void; onSelectItems: (id: LibraryItem["id"][]) => void;
libraryReturnUrl: ExcalidrawProps["libraryReturnUrl"];
theme: AppState["theme"];
id: string;
}) => { }) => {
const [lastSelectedItem, setLastSelectedItem] = useState< const [lastSelectedItem, setLastSelectedItem] = useState<
LibraryItem["id"] | null LibraryItem["id"] | null
@@ -167,7 +175,11 @@ const LibraryMenuItems = ({
); );
} }
return ( return (
<Stack.Row align="center" gap={1} key={index}> <Stack.Row
align="center"
key={index}
className="library-menu-items-container__row"
>
{rowItems} {rowItems}
</Stack.Row> </Stack.Row>
); );
@@ -181,19 +193,21 @@ const LibraryMenuItems = ({
(item) => item.status === "published", (item) => item.status === "published",
); );
const showBtn =
!libraryItems.length &&
!unpublishedItems.length &&
!publishedItems.length &&
!pendingElements.length;
return ( return (
<div <div
className="library-menu-items-container" className="library-menu-items-container"
style={ style={
publishedItems.length || unpublishedItems.length pendingElements.length ||
? { unpublishedItems.length ||
flex: "1 1 0", publishedItems.length
overflowY: "auto", ? { justifyContent: "flex-start" }
} : {}
: {
marginBottom: "2rem",
flex: 0,
}
} }
> >
<Stack.Col <Stack.Col
@@ -206,49 +220,37 @@ const LibraryMenuItems = ({
}} }}
> >
<> <>
<div className="separator"> <div>
{(pendingElements.length > 0 || {(pendingElements.length > 0 ||
unpublishedItems.length > 0 || unpublishedItems.length > 0 ||
publishedItems.length > 0) && ( publishedItems.length > 0) && (
<div>{t("labels.personalLib")}</div> <div className="library-menu-items-container__header">
{t("labels.personalLib")}
</div>
)} )}
{isLoading && ( {isLoading && (
<div <div
style={{ style={{
marginLeft: "auto", position: "absolute",
marginRight: "1rem", top: "var(--container-padding-y)",
display: "flex", right: "var(--container-padding-x)",
alignItems: "center", transform: "translateY(50%)",
fontWeight: "normal",
}} }}
> >
<div style={{ transform: "translateY(2px)" }}> <Spinner />
<Spinner />
</div>
</div> </div>
)} )}
</div> </div>
{!pendingElements.length && !unpublishedItems.length ? ( {!pendingElements.length && !unpublishedItems.length ? (
<div <div className="library-menu-items__no-items">
style={{
height: 65,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
width: "100%",
fontSize: ".9rem",
}}
>
{t("library.noItems")}
<div <div
style={{ className={clsx({
margin: ".6rem 0", "library-menu-items__no-items__label": showBtn,
fontSize: ".8em", })}
width: "70%",
textAlign: "center",
}}
> >
{t("library.noItems")}
</div>
<div className="library-menu-items__no-items__hint">
{publishedItems.length > 0 {publishedItems.length > 0
? t("library.hint_emptyPrivateLibrary") ? t("library.hint_emptyPrivateLibrary")
: t("library.hint_emptyLibrary")} : t("library.hint_emptyLibrary")}
@@ -269,7 +271,9 @@ const LibraryMenuItems = ({
{(publishedItems.length > 0 || {(publishedItems.length > 0 ||
pendingElements.length > 0 || pendingElements.length > 0 ||
unpublishedItems.length > 0) && ( unpublishedItems.length > 0) && (
<div className="separator">{t("labels.excalidrawLib")}</div> <div className="library-menu-items-container__header library-menu-items-container__header--excal">
{t("labels.excalidrawLib")}
</div>
)} )}
{publishedItems.length > 0 ? ( {publishedItems.length > 0 ? (
renderLibrarySection(publishedItems) renderLibrarySection(publishedItems)
@@ -289,6 +293,14 @@ const LibraryMenuItems = ({
</div> </div>
) : null} ) : null}
</> </>
{showBtn && (
<LibraryMenuBrowseButton
id={id}
libraryReturnUrl={libraryReturnUrl}
theme={theme}
/>
)}
</Stack.Col> </Stack.Col>
</div> </div>
); );

Some files were not shown because too many files have changed in this diff Show More