Compare commits

..

1 Commits

Author SHA1 Message Date
dwelle 5dbdbb0b6b docs: add excalidraw codebase section 2023-02-18 11:47:37 +01:00
179 changed files with 2194 additions and 6694 deletions
-10
View File
@@ -22,13 +22,3 @@ REACT_APP_DEV_ENABLE_SW=
REACT_APP_DEV_DISABLE_LIVE_RELOAD= REACT_APP_DEV_DISABLE_LIVE_RELOAD=
FAST_REFRESH=false FAST_REFRESH=false
# MATOMO
REACT_APP_MATOMO_URL=
REACT_APP_CDN_MATOMO_TRACKER_URL=
REACT_APP_MATOMO_SITE_ID=
#Debug flags
# To enable bounding box for text containers
REACT_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX=
-7
View File
@@ -12,13 +12,6 @@ REACT_APP_WS_SERVER_URL=
REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}' REACT_APP_FIREBASE_CONFIG='{"apiKey":"AIzaSyAd15pYlMci_xIp9ko6wkEsDzAAA0Dn0RU","authDomain":"excalidraw-room-persistence.firebaseapp.com","databaseURL":"https://excalidraw-room-persistence.firebaseio.com","projectId":"excalidraw-room-persistence","storageBucket":"excalidraw-room-persistence.appspot.com","messagingSenderId":"654800341332","appId":"1:654800341332:web:4a692de832b55bd57ce0c1"}'
# production-only vars # production-only vars
# GOOGLE ANALYTICS
REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13 REACT_APP_GOOGLE_ANALYTICS_ID=UA-387204-13
# MATOMO
REACT_APP_MATOMO_URL=https://excalidraw.matomo.cloud/
REACT_APP_CDN_MATOMO_TRACKER_URL=//cdn.matomo.cloud/excalidraw.matomo.cloud/matomo.js
REACT_APP_MATOMO_SITE_ID=1
REACT_APP_PLUS_APP=https://app.excalidraw.com REACT_APP_PLUS_APP=https://app.excalidraw.com
+2 -12
View File
@@ -12,24 +12,14 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Docker meta
id: meta
uses: docker/metadata-action@v4
with:
images: |
excalidraw/excalidraw
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Login to DockerHub - name: Login to DockerHub
uses: docker/login-action@v2 uses: docker/login-action@v2
with: with:
username: ${{ secrets.DOCKER_USERNAME }} username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }} password: ${{ secrets.DOCKER_PASSWORD }}
- name: Build and push - name: Build and push
uses: docker/build-push-action@v4 uses: docker/build-push-action@v3
with: with:
context: . context: .
push: true push: true
tags: ${{ steps.meta.outputs.tags }} tags: excalidraw/excalidraw:latest
labels: ${{ steps.meta.outputs.labels }}
-1
View File
@@ -25,4 +25,3 @@ src/packages/excalidraw/types
src/packages/excalidraw/example/public/bundle.js src/packages/excalidraw/example/public/bundle.js
src/packages/excalidraw/example/public/excalidraw-assets-dev src/packages/excalidraw/example/public/excalidraw-assets-dev
src/packages/excalidraw/example/public/excalidraw.development.js src/packages/excalidraw/example/public/excalidraw.development.js
coverage
+2 -2
View File
@@ -17,7 +17,7 @@
An open source virtual hand-drawn style whiteboard. </br> An open source virtual hand-drawn style whiteboard. </br>
Collaborative and end-to-end encrypted. </br> Collaborative and end-to-end encrypted. </br>
<br /> <br />
</h2> </h3>
</div> </div>
<br /> <br />
@@ -70,7 +70,7 @@ The Excalidraw editor (npm package) supports:
## Excalidraw.com ## Excalidraw.com
The app hosted at [excalidraw.com](https://excalidraw.com) is a minimal showcase of what you can build with Excalidraw. Its [source code](https://github.com/excalidraw/excalidraw/tree/master/src/excalidraw-app) is part of this repository as well, and the app features: The app hosted at [excalidraw.com](https://excalidraw.com) is a minimal showcase of what you can build with Excalidraw. Its [source code](https://github.com/excalidraw/excalidraw/tree/maielo/new-readme/src/excalidraw-app) is part of this repository as well, and the app features:
- 📡&nbsp;PWA support (works offline). - 📡&nbsp;PWA support (works offline).
- đŸ¤ŧ&nbsp;Real-time collaboration. - đŸ¤ŧ&nbsp;Real-time collaboration.
@@ -1,19 +1,6 @@
# ref # ref
<pre> <pre>
<a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs"> <a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs">createRef</a> &#124; <a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a> &#124; <a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">callbackRef</a> &#124; <br/>&#123; current: &#123; readyPromise: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/utils.ts#L460">resolvablePromise</a> } }
createRef
</a>{" "}
&#124;{" "}
<a href="https://reactjs.org/docs/hooks-reference.html#useref">useRef</a>{" "}
&#124;{" "}
<a href="https://reactjs.org/docs/refs-and-the-dom.html#callback-refs">
callbackRef
</a>{" "}
&#124; <br />
&#123; current: &#123; readyPromise: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/utils.ts#L460">
resolvablePromise
</a> } }
</pre> </pre>
You can pass a `ref` when you want to access some excalidraw APIs. We expose the below APIs: You can pass a `ref` when you want to access some excalidraw APIs. We expose the below APIs:
@@ -152,9 +139,7 @@ function App() {
return ( return (
<div style={{ height: "500px" }}> <div style={{ height: "500px" }}>
<p style={{ fontSize: "16px" }}> Click to update the scene</p> <p style={{ fontSize: "16px" }}> Click to update the scene</p>
<button className="custom-button" onClick={updateScene}> <button className="custom-button" onClick={updateScene}>Update Scene</button>
Update Scene
</button>
<Excalidraw ref={(api) => setExcalidrawAPI(api)} /> <Excalidraw ref={(api) => setExcalidrawAPI(api)} />
</div> </div>
); );
@@ -202,8 +187,7 @@ function App() {
return ( return (
<div style={{ height: "500px" }}> <div style={{ height: "500px" }}>
<p style={{ fontSize: "16px" }}> Click to update the library items</p> <p style={{ fontSize: "16px" }}> Click to update the library items</p>
<button <button className="custom-button"
className="custom-button"
onClick={() => { onClick={() => {
const libraryItems = [ const libraryItems = [
{ {
@@ -221,8 +205,10 @@ function App() {
]; ];
excalidrawAPI.updateLibrary({ excalidrawAPI.updateLibrary({
libraryItems, libraryItems,
openLibraryMenu: true, openLibraryMenu: true
}); });
}} }}
> >
Update Library Update Library
@@ -264,7 +250,7 @@ Resets the scene. If `resetLoadingState` is passed as true then it will also for
<pre> <pre>
() =>{" "} () =>{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115"> <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
ExcalidrawElement[] ExcalidrawElement[]
</a> </a>
</pre> </pre>
@@ -275,7 +261,7 @@ Returns all the elements including the deleted in the scene.
<pre> <pre>
() => NonDeleted&#60; () => NonDeleted&#60;
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115"> <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
ExcalidrawElement ExcalidrawElement
</a> </a>
[]&#62; []&#62;
@@ -307,31 +293,18 @@ This is the history API. history.clear() will clear the history.
## scrollToContent ## scrollToContent
<pre> <pre>
(<br /> (target?:{" "}
{" "} <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
target?:{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115">
ExcalidrawElement ExcalidrawElement
</a>{" "} </a>{" "}
&#124;{" "} &#124;{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L115"> <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">
ExcalidrawElement ExcalidrawElement
</a> </a>
[], []) => void
<br />
{" "}opts?: &#123; fitToContent?: boolean; animate?: boolean; duration?: number
&#125;
<br />) => void
</pre> </pre>
Scroll the nearest element out of the elements supplied to the center of the viewport. Defaults to the elements on the scene. Scroll the nearest element out of the elements supplied to the center. Defaults to the elements on the scene.
| Attribute | type | default | Description |
| --- | --- | --- | --- |
| target | <code>ExcalidrawElement &#124; ExcalidrawElement[]</code> | All scene elements | The element(s) to scroll to. |
| opts.fitToContent | boolean | false | Whether to fit the elements to viewport by automatically changing zoom as needed. |
| opts.animate | boolean | false | Whether to animate between starting and ending position. Note that for larger scenes the animation may not be smooth due to performance issues. |
| opts.duration | number | 500 | Duration of the animation if `opts.animate` is `true`. |
## refresh ## refresh
@@ -350,7 +323,7 @@ For any other cases if the position of excalidraw is updated (example due to scr
This API can be used to show the toast with custom message. This API can be used to show the toast with custom message.
```tsx ```tsx
({ message: string, closable?:boolean,duration?:number ({ message: string, closable?:boolean,duration?:number
} | null) => void } | null) => void
``` ```
@@ -385,18 +358,15 @@ This API can be used to get the files present in the scene. It may contain files
This API has the below signature. It sets the `tool` passed in param as the active tool. This API has the below signature. It sets the `tool` passed in param as the active tool.
<pre> <pre>
(tool: <br /> &#123; type:{" "} (tool: <br/> &#123; type: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/shapes.tsx#L15">SHAPES</a>[number]["value"]&#124; "eraser" &#125; &#124;<br/> &#123; type: "custom"; customType: string &#125;) => void
<a href="https://github.com/excalidraw/excalidraw/blob/master/src/shapes.tsx#L15">
SHAPES
</a>
[number]["value"]&#124; "eraser" &#125; &#124;
<br /> &#123; type: "custom"; customType: string &#125;) => void
</pre> </pre>
## setCursor ## setCursor
This API can be used to customise the mouse cursor on the canvas and has the below signature. It sets the mouse cursor to the cursor passed in param. This API can be used to customise the mouse cursor on the canvas and has the below signature.
It sets the mouse cursor to the cursor passed in param.
```tsx ```tsx
(cursor: string) => void (cursor: string) => void
@@ -31,29 +31,10 @@ You can pass `null` / `undefined` if not applicable.
restoreElements( restoreElements(
elements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ImportedDataState["elements"]</a>,<br/>&nbsp; elements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ImportedDataState["elements"]</a>,<br/>&nbsp;
localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined): <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a>,<br/>&nbsp; localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined): <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a>,<br/>&nbsp;
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean }<br/> refreshDimensions?: boolean<br/>
) )
</pre> </pre>
| Prop | Type | Description |
| ---- | ---- | ---- |
| `elements` | <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ImportedDataState["elements"]</a> | The `elements` to be restored |
| [`localElements`](#localelements) | <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a> &#124; null &#124; undefined | When `localElements` are supplied, they are used to ensure that existing restored elements reuse `version` (and increment it), and regenerate `versionNonce`. |
| [`opts`](#opts) | `Object` | The extra optional parameter to configure restored elements
#### localElements
When `localElements` are supplied, they are used to ensure that existing restored elements reuse `version` (and increment it), and regenerate `versionNonce`.
Use this when you `import` elements which may already be present in the scene to ensure that you do not disregard the newly imported elements if you're using element version to detect the update
#### opts
The extra optional parameter to configure restored elements. It has the following attributes
| Prop | Type | Description|
| --- | --- | ------|
| `refreshDimensions` | `boolean` | Indicates whether we should also `recalculate` text element dimensions. Since this is a potentially costly operation, you may want to disable it if you restore elements in tight loops, such as during collaboration. |
| `repairBindings` |`boolean` | Indicates whether the `bindings` for the elements should be repaired. This is to make sure there are no containers with non existent bound text element id and no bound text elements with non existent container id. |
**_How to use_** **_How to use_**
```js ```js
@@ -62,6 +43,9 @@ import { restoreElements } from "@excalidraw/excalidraw";
This function will make sure all properties of element is correctly set and if any attribute is missing, it will be set to its default value. This function will make sure all properties of element is correctly set and if any attribute is missing, it will be set to its default value.
When `localElements` are supplied, they are used to ensure that existing restored elements reuse `version` (and increment it), and regenerate `versionNonce`.
Use this when you import elements which may already be present in the scene to ensure that you do not disregard the newly imported elements if you're using element version to detect the updates.
Parameter `refreshDimensions` indicates whether we should also `recalculate` text element dimensions. Defaults to `false`. Since this is a potentially costly operation, you may want to disable it if you restore elements in tight loops, such as during collaboration. Parameter `refreshDimensions` indicates whether we should also `recalculate` text element dimensions. Defaults to `false`. Since this is a potentially costly operation, you may want to disable it if you restore elements in tight loops, such as during collaboration.
### restore ### restore
@@ -72,9 +56,7 @@ Parameter `refreshDimensions` indicates whether we should also `recalculate` tex
restore( restore(
data: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L34">ImportedDataState</a>,<br/>&nbsp; data: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L34">ImportedDataState</a>,<br/>&nbsp;
localAppState: Partial&lt;<a href="https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L95">AppState</a>> | null | undefined,<br/>&nbsp; localAppState: Partial&lt;<a href="https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L95">AppState</a>> | null | undefined,<br/>&nbsp;
localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined<br/>): <a href="https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L4">DataState</a><br/> localElements: <a href="https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L114">ExcalidrawElement[]</a> | null | undefined<br/>): <a href="https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L4">DataState</a>
opts: &#123; refreshDimensions?: boolean, repairBindings?: boolean }<br/>
) )
</pre> </pre>
@@ -339,47 +339,3 @@ The `device` has the following `attributes`
| `isMobile` | `boolean` | Set to `true` when the device is `mobile` | | `isMobile` | `boolean` | Set to `true` when the device is `mobile` |
| `isTouchScreen` | `boolean` | Set to `true` for `touch` devices | | `isTouchScreen` | `boolean` | Set to `true` for `touch` devices |
| `canDeviceFitSidebar` | `boolean` | Implies whether there is enough space to fit the `sidebar` | | `canDeviceFitSidebar` | `boolean` | Implies whether there is enough space to fit the `sidebar` |
### i18n
To help with localization, we export the following.
| name | type |
| --- | --- |
| `defaultLang` | `string` |
| `languages` | [`Language[]`](https://github.com/excalidraw/excalidraw/blob/master/src/i18n.ts#L15) |
| `useI18n` | [`() => { langCode, t }`](https://github.com/excalidraw/excalidraw/blob/master/src/i18n.ts#L15) |
```js
import { defaultLang, languages, useI18n } from "@excalidraw/excalidraw";
```
#### defaultLang
Default language code, `en`.
#### languages
List of supported language codes. You can pass any of these to `Excalidraw`'s [`langCode` prop](/docs/@excalidraw/excalidraw/api/props/#langcode).
#### useI18n
A hook that returns the current language code and translation helper function. You can use this to translate strings in the components you render as children of `<Excalidraw>`.
```jsx live
function App() {
const { t } = useI18n();
return (
<div style={{ height: "500px" }}>
<Excalidraw>
<button
style={{ position: "absolute", zIndex: 10, height: "2rem" }}
onClick={() => window.alert(t("labels.madeWithExcalidraw"))}
>
{t("buttons.confirm")}
</button>
</Excalidraw>
</div>
);
}
```
@@ -4,34 +4,6 @@
No, Excalidraw package doesn't come with collaboration built in, since the implementation is specific to each host app. We expose APIs which you can use to communicate with Excalidraw which you can use to implement it. You can check our own implementation [here](https://github.com/excalidraw/excalidraw/blob/master/src/excalidraw-app/index.tsx). Here is a [detailed answer](https://github.com/excalidraw/excalidraw/discussions/3879#discussioncomment-1110524) on how you can achieve the same. No, Excalidraw package doesn't come with collaboration built in, since the implementation is specific to each host app. We expose APIs which you can use to communicate with Excalidraw which you can use to implement it. You can check our own implementation [here](https://github.com/excalidraw/excalidraw/blob/master/src/excalidraw-app/index.tsx). Here is a [detailed answer](https://github.com/excalidraw/excalidraw/discussions/3879#discussioncomment-1110524) on how you can achieve the same.
### Turning off Aggressive Anti-Fingerprinting in Brave browser
When *Aggressive Anti-Fingerprinting* is turned on, the `measureText` API breaks which in turn breaks the Text Elements in your drawings. Here is more [info](https://github.com/excalidraw/excalidraw/pull/6336) on the same.
We strongly recommend turning it off. You can follow the steps below on how to do so.
1. Open [excalidraw.com](https://excalidraw.com) in Brave and click on the **Shield** button
![Shield button](../../assets/brave-shield.png)
<div style={{width:'30rem'}}>
2. Once opened, look for **Aggressively Block Fingerprinting**
![Aggresive block fingerprinting](../../assets/aggressive-block-fingerprint.png)
3. Switch to **Block Fingerprinting**
![Block filtering](../../assets/block-fingerprint.png)
4. Thats all. All text elements should be fixed now 🎉
</div>
If disabling this setting doesn't fix the display of text elements, please consider opening an [issue](https://github.com/excalidraw/excalidraw/issues/new) on our GitHub, or message us on [Discord](https://discord.gg/UexuTaE).
## Need help? ## Need help?
Check out the existing [Q&A](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw). If you have any queries or need help, ask us [here](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw). Check out the existing [Q&A](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw). If you have any queries or need help, ask us [here](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

@@ -0,0 +1,6 @@
---
title: Introduction to the codebase
slug: ../
---
This section is documenting the Excalidraw codebase itself for developers who want to contribute to the project.
+1 -1
View File
@@ -18,7 +18,7 @@
"@docusaurus/core": "2.2.0", "@docusaurus/core": "2.2.0",
"@docusaurus/preset-classic": "2.2.0", "@docusaurus/preset-classic": "2.2.0",
"@docusaurus/theme-live-codeblock": "2.2.0", "@docusaurus/theme-live-codeblock": "2.2.0",
"@excalidraw/excalidraw": "0.15.2", "@excalidraw/excalidraw": "0.14.2",
"@mdx-js/react": "^1.6.22", "@mdx-js/react": "^1.6.22",
"clsx": "^1.2.1", "clsx": "^1.2.1",
"docusaurus-plugin-sass": "0.2.3", "docusaurus-plugin-sass": "0.2.3",
+10
View File
@@ -92,6 +92,16 @@ const sidebars = {
"@excalidraw/excalidraw/development", "@excalidraw/excalidraw/development",
], ],
}, },
{
type: "category",
label: "Excalidraw codebase",
link: {
type: "doc",
id: "codebase/introduction-to-the-codebase",
},
items: [],
},
], ],
}; };
@@ -24,7 +24,6 @@ const ExcalidrawScope = {
Sidebar: ExcalidrawComp.Sidebar, Sidebar: ExcalidrawComp.Sidebar,
exportToCanvas: ExcalidrawComp.exportToCanvas, exportToCanvas: ExcalidrawComp.exportToCanvas,
initialData, initialData,
useI18n: ExcalidrawComp.useI18n,
}; };
export default ExcalidrawScope; export default ExcalidrawScope;
+16 -16
View File
@@ -1631,10 +1631,10 @@
url-loader "^4.1.1" url-loader "^4.1.1"
webpack "^5.73.0" webpack "^5.73.0"
"@excalidraw/excalidraw@0.15.2": "@excalidraw/excalidraw@0.14.2":
version "0.15.2" version "0.14.2"
resolved "https://registry.yarnpkg.com/@excalidraw/excalidraw/-/excalidraw-0.15.2.tgz#7dba4f6e10c52015a007efb75a9fc1afe598574c" resolved "https://registry.yarnpkg.com/@excalidraw/excalidraw/-/excalidraw-0.14.2.tgz#150cb4b7a1bf0d11cd64295936c930e7e0db8375"
integrity sha512-rTI02kgWSTXiUdIkBxt9u/581F3eXcqQgJdIxmz54TFtG3ughoxO5fr4t7Fr2LZIturBPqfocQHGKZ0t2KLKgw== integrity sha512-8LdjpTBWEK5waDWB7Bt/G9YBI4j0OxkstUhvaDGz7dwQGfzF6FW5CXBoYHNEoX0qmb+Fg/NPOlZ7FrKsrSVCqg==
"@hapi/hoek@^9.0.0": "@hapi/hoek@^9.0.0":
version "9.3.0" version "9.3.0"
@@ -1785,9 +1785,9 @@
"@hapi/hoek" "^9.0.0" "@hapi/hoek" "^9.0.0"
"@sideway/formula@^3.0.0": "@sideway/formula@^3.0.0":
version "3.0.1" version "3.0.0"
resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.1.tgz#80fcbcbaf7ce031e0ef2dd29b1bfc7c3f583611f" resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.0.tgz#fe158aee32e6bd5de85044be615bc08478a0a13c"
integrity sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg== integrity sha512-vHe7wZ4NOXVfkoRb8T5otiENVlT7a3IAiw7H5M2+GO+9CDgcVUUsX1zalAztCmwyOr2RUTGJdgB+ZvSVqmdHmg==
"@sideway/pinpoint@^2.0.0": "@sideway/pinpoint@^2.0.0":
version "2.0.0" version "2.0.0"
@@ -4376,9 +4376,9 @@ htmlparser2@^8.0.1:
entities "^4.3.0" entities "^4.3.0"
http-cache-semantics@^4.0.0: http-cache-semantics@^4.0.0:
version "4.1.1" version "4.1.0"
resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.0.tgz#49e91c5cbf36c9b94bcfcd71c23d5249ec74e390"
integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== integrity sha512-carPklcUh7ROWRK7Cv27RPtdhYhUsela/ue5/jKzjegVvXDqM2ILE9Q2BGn9JZJh1g87cp56su/FgQSzcWS8cQ==
http-deceiver@^1.2.7: http-deceiver@^1.2.7:
version "1.2.7" version "1.2.7"
@@ -7159,9 +7159,9 @@ typescript@^4.7.4:
integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ== integrity sha512-C0WQT0gezHuw6AdY1M2jxUO83Rjf0HP7Sk1DtXj6j1EwkQNZrHAg2XPWlq62oqEhYvONq5pkC2Y9oPljWToLmQ==
ua-parser-js@^0.7.30: ua-parser-js@^0.7.30:
version "0.7.33" version "0.7.31"
resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.33.tgz#1d04acb4ccef9293df6f70f2c3d22f3030d8b532" resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.31.tgz#649a656b191dffab4f21d5e053e27ca17cbff5c6"
integrity sha512-s8ax/CeZdK9R/56Sui0WM6y9OFREJarMRHqLB2EwkovemBxNQ+Bqu8GAsUnVcXKgphb++ghr/B2BZx4mahujPw== integrity sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ==
unescape@^1.0.1: unescape@^1.0.1:
version "1.0.1" version "1.0.1"
@@ -7542,9 +7542,9 @@ webpack-sources@^3.2.2, webpack-sources@^3.2.3:
integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w== integrity sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==
webpack@^5.73.0: webpack@^5.73.0:
version "5.76.1" version "5.74.0"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.76.1.tgz#7773de017e988bccb0f13c7d75ec245f377d295c" resolved "https://registry.yarnpkg.com/webpack/-/webpack-5.74.0.tgz#02a5dac19a17e0bb47093f2be67c695102a55980"
integrity sha512-4+YIK4Abzv8172/SGqObnUjaIHjLEuUasz9EwQj/9xmPPkYJy2Mh03Q/lJfSD3YLzbxy5FeTq5Uw0323Oh6SJQ== integrity sha512-A2InDwnhhGN4LYctJj6M1JEaGL7Luj6LOmyBHjcI8529cm5p6VXiTIW2sn6ffvEAKmveLzvu4jrihwXtPojlAA==
dependencies: dependencies:
"@types/eslint-scope" "^3.7.3" "@types/eslint-scope" "^3.7.3"
"@types/estree" "^0.0.51" "@types/estree" "^0.0.51"
+7 -7
View File
@@ -25,6 +25,11 @@
"@testing-library/jest-dom": "5.16.2", "@testing-library/jest-dom": "5.16.2",
"@testing-library/react": "12.1.5", "@testing-library/react": "12.1.5",
"@tldraw/vec": "1.7.1", "@tldraw/vec": "1.7.1",
"@types/jest": "27.4.0",
"@types/pica": "5.1.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"@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", "cross-env": "7.0.3",
@@ -52,6 +57,7 @@
"sass": "1.51.0", "sass": "1.51.0",
"socket.io-client": "2.3.1", "socket.io-client": "2.3.1",
"tunnel-rat": "0.1.0", "tunnel-rat": "0.1.0",
"typescript": "4.9.4",
"workbox-background-sync": "^6.5.4", "workbox-background-sync": "^6.5.4",
"workbox-broadcast-update": "^6.5.4", "workbox-broadcast-update": "^6.5.4",
"workbox-cacheable-response": "^6.5.4", "workbox-cacheable-response": "^6.5.4",
@@ -69,14 +75,9 @@
"@excalidraw/eslint-config": "1.0.0", "@excalidraw/eslint-config": "1.0.0",
"@excalidraw/prettier-config": "1.0.2", "@excalidraw/prettier-config": "1.0.2",
"@types/chai": "4.3.0", "@types/chai": "4.3.0",
"@types/jest": "27.4.0",
"@types/lodash.throttle": "4.1.7", "@types/lodash.throttle": "4.1.7",
"@types/pako": "1.0.3", "@types/pako": "1.0.3",
"@types/pica": "5.1.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"@types/resize-observer-browser": "0.1.7", "@types/resize-observer-browser": "0.1.7",
"@types/socket.io-client": "1.4.36",
"chai": "4.3.6", "chai": "4.3.6",
"dotenv": "16.0.1", "dotenv": "16.0.1",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.5.0",
@@ -87,8 +88,7 @@
"lint-staged": "12.3.7", "lint-staged": "12.3.7",
"pepjs": "0.5.3", "pepjs": "0.5.3",
"prettier": "2.6.2", "prettier": "2.6.2",
"rewire": "6.0.0", "rewire": "6.0.0"
"typescript": "4.9.4"
}, },
"engines": { "engines": {
"node": ">=14.0.0" "node": ">=14.0.0"
+2 -33
View File
@@ -79,7 +79,6 @@
</style> </style>
<!-------------------------------------------------------------------------> <!------------------------------------------------------------------------->
<% if (process.env.NODE_ENV === "production") { %>
<script> <script>
// Redirect Excalidraw+ users which have auto-redirect enabled. // Redirect Excalidraw+ users which have auto-redirect enabled.
// //
@@ -98,7 +97,6 @@
window.location.href = "https://app.excalidraw.com"; window.location.href = "https://app.excalidraw.com";
} }
</script> </script>
<% } %>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
@@ -148,10 +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_DISABLE_TRACKING !== 'true') { %> <% if (process.env.REACT_APP_DISABLE_TRACKING !== 'true' &&
process.env.REACT_APP_GOOGLE_ANALYTICS_ID) { %>
<!-- LEGACY GOOGLE ANALYTICS -->
<% if (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%"
@@ -164,33 +160,6 @@
gtag("js", new Date()); gtag("js", new Date());
gtag("config", "%REACT_APP_GOOGLE_ANALYTICS_ID%"); gtag("config", "%REACT_APP_GOOGLE_ANALYTICS_ID%");
</script> </script>
<% } %>
<!-- end LEGACY GOOGLE ANALYTICS -->
<!-- Matomo -->
<% if (process.env.REACT_APP_MATOMO_URL &&
process.env.REACT_APP_MATOMO_SITE_ID &&
process.env.REACT_APP_CDN_MATOMO_TRACKER_URL) { %>
<script>
var _paq = (window._paq = window._paq || []);
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["trackPageView"]);
_paq.push(["enableLinkTracking"]);
(function () {
var u = "%REACT_APP_MATOMO_URL%";
_paq.push(["setTrackerUrl", u + "matomo.php"]);
_paq.push(["setSiteId", "%REACT_APP_MATOMO_SITE_ID%"]);
var d = document,
g = d.createElement("script"),
s = d.getElementsByTagName("script")[0];
g.async = true;
g.src = "%REACT_APP_CDN_MATOMO_TRACKER_URL%";
s.parentNode.insertBefore(g, s);
})();
</script>
<% } %>
<!-- end Matomo analytics -->
<% } %> <% } %>
<!-- FIXME: remove this when we update CRA (fix SW caching) --> <!-- FIXME: remove this when we update CRA (fix SW caching) -->
-6
View File
@@ -2,9 +2,6 @@ const fs = require("fs");
const THRESSHOLD = 85; const THRESSHOLD = 85;
// we're using BCP 47 language tags as keys
// e.g. https://gist.github.com/typpo/b2b828a35e683b9bf8db91b5404f1bd1
const crowdinMap = { const crowdinMap = {
"ar-SA": "en-ar", "ar-SA": "en-ar",
"bg-BG": "en-bg", "bg-BG": "en-bg",
@@ -55,7 +52,6 @@ const crowdinMap = {
"kk-KZ": "en-kk", "kk-KZ": "en-kk",
"vi-VN": "en-vi", "vi-VN": "en-vi",
"mr-IN": "en-mr", "mr-IN": "en-mr",
"th-TH": "en-th",
}; };
const flags = { const flags = {
@@ -108,7 +104,6 @@ const flags = {
"eu-ES": "đŸ‡ĒđŸ‡Ļ", "eu-ES": "đŸ‡ĒđŸ‡Ļ",
"vi-VN": "đŸ‡ģđŸ‡ŗ", "vi-VN": "đŸ‡ģđŸ‡ŗ",
"mr-IN": "đŸ‡ŽđŸ‡ŗ", "mr-IN": "đŸ‡ŽđŸ‡ŗ",
"th-TH": "🇹🇭",
}; };
const languages = { const languages = {
@@ -161,7 +156,6 @@ const languages = {
"zh-TW": "įšéĢ”ä¸­æ–‡", "zh-TW": "įšéĢ”ä¸­æ–‡",
"vi-VN": "Tiáēŋng Viáģ‡t", "vi-VN": "Tiáēŋng Viáģ‡t",
"mr-IN": "ā¤Žā¤°ā¤žā¤ āĨ€", "mr-IN": "ā¤Žā¤°ā¤žā¤ āĨ€",
"th-TH": "ā¸ ā¸˛ā¸Šā¸˛āš„ā¸—ā¸ĸ",
}; };
const percentages = fs.readFileSync( const percentages = fs.readFileSync(
+20
View File
@@ -1,9 +1,22 @@
const fs = require("fs");
const { execSync } = require("child_process"); const { execSync } = require("child_process");
const excalidrawDir = `${__dirname}/../src/packages/excalidraw`; const excalidrawDir = `${__dirname}/../src/packages/excalidraw`;
const excalidrawPackage = `${excalidrawDir}/package.json`; const excalidrawPackage = `${excalidrawDir}/package.json`;
const pkg = require(excalidrawPackage); const pkg = require(excalidrawPackage);
const originalReadMe = fs.readFileSync(`${excalidrawDir}/README.md`, "utf8");
const updateReadme = () => {
const excalidrawIndex = originalReadMe.indexOf("### Excalidraw");
// remove note for stable readme
const data = originalReadMe.slice(excalidrawIndex);
// update readme
fs.writeFileSync(`${excalidrawDir}/README.md`, data, "utf8");
};
const publish = () => { const publish = () => {
try { try {
execSync(`yarn --frozen-lockfile`); execSync(`yarn --frozen-lockfile`);
@@ -17,8 +30,15 @@ const publish = () => {
}; };
const release = () => { const release = () => {
updateReadme();
console.info("Note for stable readme removed");
publish(); publish();
console.info(`Published ${pkg.version}!`); console.info(`Published ${pkg.version}!`);
// revert readme after release
fs.writeFileSync(`${excalidrawDir}/README.md`, originalReadMe, "utf8");
console.info("Readme reverted");
}; };
release(); release();
+13 -178
View File
@@ -1,14 +1,7 @@
import { import { VERTICAL_ALIGN } from "../constants";
BOUND_TEXT_PADDING, import { getNonDeletedElements, isTextElement } from "../element";
ROUNDNESS,
VERTICAL_ALIGN,
TEXT_ALIGN,
} from "../constants";
import { getNonDeletedElements, isTextElement, newElement } from "../element";
import { mutateElement } from "../element/mutateElement"; import { mutateElement } from "../element/mutateElement";
import { import {
computeBoundTextPosition,
computeContainerDimensionForBoundText,
getBoundTextElement, getBoundTextElement,
measureText, measureText,
redrawTextBoundingBox, redrawTextBoundingBox,
@@ -16,21 +9,16 @@ import {
import { import {
getOriginalContainerHeightFromCache, getOriginalContainerHeightFromCache,
resetOriginalContainerCache, resetOriginalContainerCache,
updateOriginalContainerCache,
} from "../element/textWysiwyg"; } from "../element/textWysiwyg";
import { import {
hasBoundTextElement, hasBoundTextElement,
isTextBindableContainer, isTextBindableContainer,
isUsingAdaptiveRadius,
} from "../element/typeChecks"; } from "../element/typeChecks";
import { import {
ExcalidrawElement,
ExcalidrawLinearElement,
ExcalidrawTextContainer, ExcalidrawTextContainer,
ExcalidrawTextElement, ExcalidrawTextElement,
} from "../element/types"; } from "../element/types";
import { getSelectedElements } from "../scene"; import { getSelectedElements } from "../scene";
import { AppState } from "../types";
import { getFontString } from "../utils"; import { getFontString } from "../utils";
import { register } from "./register"; import { register } from "./register";
@@ -40,7 +28,6 @@ export const actionUnbindText = register({
trackEvent: { category: "element" }, trackEvent: { category: "element" },
predicate: (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));
}, },
perform: (elements, appState) => { perform: (elements, appState) => {
@@ -54,21 +41,18 @@ export const actionUnbindText = register({
const { width, height, baseline } = measureText( const { width, height, baseline } = measureText(
boundTextElement.originalText, boundTextElement.originalText,
getFontString(boundTextElement), getFontString(boundTextElement),
boundTextElement.lineHeight,
); );
const originalContainerHeight = getOriginalContainerHeightFromCache( const originalContainerHeight = getOriginalContainerHeightFromCache(
element.id, element.id,
); );
resetOriginalContainerCache(element.id); resetOriginalContainerCache(element.id);
const { x, y } = computeBoundTextPosition(element, boundTextElement);
mutateElement(boundTextElement as ExcalidrawTextElement, { mutateElement(boundTextElement as ExcalidrawTextElement, {
containerId: null, containerId: null,
width, width,
height, height,
baseline, baseline,
text: boundTextElement.originalText, text: boundTextElement.originalText,
x,
y,
}); });
mutateElement(element, { mutateElement(element, {
boundElements: element.boundElements?.filter( boundElements: element.boundElements?.filter(
@@ -138,7 +122,6 @@ export const actionBindText = register({
mutateElement(textElement, { mutateElement(textElement, {
containerId: container.id, containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE, verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
}); });
mutateElement(container, { mutateElement(container, {
boundElements: (container.boundElements || []).concat({ boundElements: (container.boundElements || []).concat({
@@ -146,168 +129,20 @@ export const actionBindText = register({
id: textElement.id, id: textElement.id,
}), }),
}); });
const originalContainerHeight = container.height;
redrawTextBoundingBox(textElement, container); redrawTextBoundingBox(textElement, container);
// overwritting the cache with original container height so const updatedElements = elements.slice();
// it can be restored when unbind const textElementIndex = updatedElements.findIndex(
updateOriginalContainerCache(container.id, originalContainerHeight); (ele) => ele.id === textElement.id,
);
updatedElements.splice(textElementIndex, 1);
const containerIndex = updatedElements.findIndex(
(ele) => ele.id === container.id,
);
updatedElements.splice(containerIndex + 1, 0, textElement);
return { return {
elements: pushTextAboveContainer(elements, container, textElement), elements: updatedElements,
appState: { ...appState, selectedElementIds: { [container.id]: true } }, appState: { ...appState, selectedElementIds: { [container.id]: true } },
commitToHistory: true, commitToHistory: true,
}; };
}, },
}); });
const pushTextAboveContainer = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
textElement: ExcalidrawTextElement,
) => {
const updatedElements = elements.slice();
const textElementIndex = updatedElements.findIndex(
(ele) => ele.id === textElement.id,
);
updatedElements.splice(textElementIndex, 1);
const containerIndex = updatedElements.findIndex(
(ele) => ele.id === container.id,
);
updatedElements.splice(containerIndex + 1, 0, textElement);
return updatedElements;
};
const pushContainerBelowText = (
elements: readonly ExcalidrawElement[],
container: ExcalidrawElement,
textElement: ExcalidrawTextElement,
) => {
const updatedElements = elements.slice();
const containerIndex = updatedElements.findIndex(
(ele) => ele.id === container.id,
);
updatedElements.splice(containerIndex, 1);
const textElementIndex = updatedElements.findIndex(
(ele) => ele.id === textElement.id,
);
updatedElements.splice(textElementIndex, 0, container);
return updatedElements;
};
export const actionWrapTextInContainer = register({
name: "wrapTextInContainer",
contextItemLabel: "labels.createContainerFromText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
const areTextElements = selectedElements.every((el) => isTextElement(el));
return selectedElements.length > 0 && areTextElements;
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
let updatedElements: readonly ExcalidrawElement[] = elements.slice();
const containerIds: AppState["selectedElementIds"] = {};
for (const textElement of selectedElements) {
if (isTextElement(textElement)) {
const container = newElement({
type: "rectangle",
backgroundColor: appState.currentItemBackgroundColor,
boundElements: [
...(textElement.boundElements || []),
{ id: textElement.id, type: "text" },
],
angle: textElement.angle,
fillStyle: appState.currentItemFillStyle,
strokeColor: appState.currentItemStrokeColor,
roughness: appState.currentItemRoughness,
strokeWidth: appState.currentItemStrokeWidth,
strokeStyle: appState.currentItemStrokeStyle,
roundness:
appState.currentItemRoundness === "round"
? {
type: isUsingAdaptiveRadius("rectangle")
? ROUNDNESS.ADAPTIVE_RADIUS
: ROUNDNESS.PROPORTIONAL_RADIUS,
}
: null,
opacity: 100,
locked: false,
x: textElement.x - BOUND_TEXT_PADDING,
y: textElement.y - BOUND_TEXT_PADDING,
width: computeContainerDimensionForBoundText(
textElement.width,
"rectangle",
),
height: computeContainerDimensionForBoundText(
textElement.height,
"rectangle",
),
groupIds: textElement.groupIds,
});
// update bindings
if (textElement.boundElements?.length) {
const linearElementIds = textElement.boundElements
.filter((ele) => ele.type === "arrow")
.map((el) => el.id);
const linearElements = updatedElements.filter((ele) =>
linearElementIds.includes(ele.id),
) as ExcalidrawLinearElement[];
linearElements.forEach((ele) => {
let startBinding = ele.startBinding;
let endBinding = ele.endBinding;
if (startBinding?.elementId === textElement.id) {
startBinding = {
...startBinding,
elementId: container.id,
};
}
if (endBinding?.elementId === textElement.id) {
endBinding = { ...endBinding, elementId: container.id };
}
if (startBinding || endBinding) {
mutateElement(ele, { startBinding, endBinding }, false);
}
});
}
mutateElement(
textElement,
{
containerId: container.id,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
boundElements: null,
textAlign: TEXT_ALIGN.CENTER,
},
false,
);
redrawTextBoundingBox(textElement, container);
updatedElements = pushContainerBelowText(
[...updatedElements, container],
container,
textElement,
);
containerIds[container.id] = true;
}
}
return {
elements: updatedElements,
appState: {
...appState,
selectedElementIds: containerIds,
},
commitToHistory: true,
};
},
});
+1 -1
View File
@@ -226,7 +226,7 @@ const zoomValueToFitBoundsOnViewport = (
return clampedZoomValueToFitElements as NormalizedZoomValue; return clampedZoomValueToFitElements as NormalizedZoomValue;
}; };
export const zoomToFitElements = ( const zoomToFitElements = (
elements: readonly ExcalidrawElement[], elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>, appState: Readonly<AppState>,
zoomToSelection: boolean, zoomToSelection: boolean,
+1 -1
View File
@@ -18,7 +18,7 @@ export const actionCopy = register({
perform: (elements, appState, _, app) => { perform: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(elements, appState, true); const selectedElements = getSelectedElements(elements, appState, true);
copyToClipboard(selectedElements, app.files); copyToClipboard(selectedElements, appState, app.files);
return { return {
commitToHistory: false, commitToHistory: false,
+36 -65
View File
@@ -1,5 +1,4 @@
import { AppState } from "../../src/types"; import { AppState } from "../../src/types";
import { trackEvent } from "../analytics";
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";
@@ -38,7 +37,6 @@ import {
TextAlignLeftIcon, TextAlignLeftIcon,
TextAlignCenterIcon, TextAlignCenterIcon,
TextAlignRightIcon, TextAlignRightIcon,
FillZigZagIcon,
} from "../components/icons"; } from "../components/icons";
import { import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
@@ -56,7 +54,6 @@ import { mutateElement, newElementWith } from "../element/mutateElement";
import { import {
getBoundTextElement, getBoundTextElement,
getContainerElement, getContainerElement,
getDefaultLineHeight,
} from "../element/textElement"; } from "../element/textElement";
import { import {
isBoundToContainer, isBoundToContainer,
@@ -84,7 +81,7 @@ import {
isSomeElementSelected, isSomeElementSelected,
} from "../scene"; } from "../scene";
import { hasStrokeColor } from "../scene/comparisons"; import { hasStrokeColor } from "../scene/comparisons";
import { arrayToMap, getShortcutKey } from "../utils"; import { arrayToMap } from "../utils";
import { register } from "./register"; import { register } from "./register";
const FONT_SIZE_RELATIVE_INCREASE_STEP = 0.1; const FONT_SIZE_RELATIVE_INCREASE_STEP = 0.1;
@@ -296,12 +293,7 @@ export const actionChangeBackgroundColor = register({
export const actionChangeFillStyle = register({ export const actionChangeFillStyle = register({
name: "changeFillStyle", name: "changeFillStyle",
trackEvent: false, trackEvent: false,
perform: (elements, appState, value, app) => { perform: (elements, appState, value) => {
trackEvent(
"element",
"changeFillStyle",
`${value} (${app.device.isMobile ? "mobile" : "desktop"})`,
);
return { return {
elements: changeProperty(elements, appState, (el) => elements: changeProperty(elements, appState, (el) =>
newElementWith(el, { newElementWith(el, {
@@ -312,57 +304,40 @@ export const actionChangeFillStyle = register({
commitToHistory: true, commitToHistory: true,
}; };
}, },
PanelComponent: ({ elements, appState, updateData }) => { PanelComponent: ({ elements, appState, updateData }) => (
const selectedElements = getSelectedElements(elements, appState); <fieldset>
const allElementsZigZag = <legend>{t("labels.fill")}</legend>
selectedElements.length > 0 && <ButtonIconSelect
selectedElements.every((el) => el.fillStyle === "zigzag"); options={[
{
return ( value: "hachure",
<fieldset> text: t("labels.hachure"),
<legend>{t("labels.fill")}</legend> icon: FillHachureIcon,
<ButtonIconSelect },
type="button" {
options={[ value: "cross-hatch",
{ text: t("labels.crossHatch"),
value: "hachure", icon: FillCrossHatchIcon,
text: `${ },
allElementsZigZag ? t("labels.zigzag") : t("labels.hachure") {
} (${getShortcutKey("Alt-Click")})`, value: "solid",
icon: allElementsZigZag ? FillZigZagIcon : FillHachureIcon, text: t("labels.solid"),
active: allElementsZigZag ? true : undefined, icon: FillSolidIcon,
}, },
{ ]}
value: "cross-hatch", group="fill"
text: t("labels.crossHatch"), value={getFormValue(
icon: FillCrossHatchIcon, elements,
}, appState,
{ (element) => element.fillStyle,
value: "solid", appState.currentItemFillStyle,
text: t("labels.solid"), )}
icon: FillSolidIcon, onChange={(value) => {
}, updateData(value);
]} }}
value={getFormValue( />
elements, </fieldset>
appState, ),
(element) => element.fillStyle,
appState.currentItemFillStyle,
)}
onClick={(value, event) => {
const nextValue =
event.altKey &&
value === "hachure" &&
selectedElements.every((el) => el.fillStyle === "hachure")
? "zigzag"
: value;
updateData(nextValue);
}}
/>
</fieldset>
);
},
}); });
export const actionChangeStrokeWidth = register({ export const actionChangeStrokeWidth = register({
@@ -662,7 +637,6 @@ export const actionChangeFontFamily = register({
oldElement, oldElement,
{ {
fontFamily: value, fontFamily: value,
lineHeight: getDefaultLineHeight(value),
}, },
); );
redrawTextBoundingBox(newElement, getContainerElement(oldElement)); redrawTextBoundingBox(newElement, getContainerElement(oldElement));
@@ -771,19 +745,16 @@ export const actionChangeTextAlign = register({
value: "left", value: "left",
text: t("labels.left"), text: t("labels.left"),
icon: TextAlignLeftIcon, icon: TextAlignLeftIcon,
testId: "align-left",
}, },
{ {
value: "center", value: "center",
text: t("labels.center"), text: t("labels.center"),
icon: TextAlignCenterIcon, icon: TextAlignCenterIcon,
testId: "align-horizontal-center",
}, },
{ {
value: "right", value: "right",
text: t("labels.right"), text: t("labels.right"),
icon: TextAlignRightIcon, icon: TextAlignRightIcon,
testId: "align-right",
}, },
]} ]}
value={getFormValue( value={getFormValue(
+4 -13
View File
@@ -12,10 +12,7 @@ import {
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
} from "../constants"; } from "../constants";
import { import { getBoundTextElement } from "../element/textElement";
getBoundTextElement,
getDefaultLineHeight,
} from "../element/textElement";
import { import {
hasBoundTextElement, hasBoundTextElement,
canApplyRoundnessTypeToElement, canApplyRoundnessTypeToElement,
@@ -95,18 +92,12 @@ export const actionPasteStyles = register({
}); });
if (isTextElement(newElement)) { if (isTextElement(newElement)) {
const fontSize =
elementStylesToCopyFrom?.fontSize || DEFAULT_FONT_SIZE;
const fontFamily =
elementStylesToCopyFrom?.fontFamily || DEFAULT_FONT_FAMILY;
newElement = newElementWith(newElement, { newElement = newElementWith(newElement, {
fontSize, fontSize: elementStylesToCopyFrom?.fontSize || DEFAULT_FONT_SIZE,
fontFamily, fontFamily:
elementStylesToCopyFrom?.fontFamily || DEFAULT_FONT_FAMILY,
textAlign: textAlign:
elementStylesToCopyFrom?.textAlign || DEFAULT_TEXT_ALIGN, elementStylesToCopyFrom?.textAlign || DEFAULT_TEXT_ALIGN,
lineHeight:
elementStylesToCopyFrom.lineHeight ||
getDefaultLineHeight(fontFamily),
}); });
let container = null; let container = null;
if (newElement.containerId) { if (newElement.containerId) {
-1
View File
@@ -1,6 +1,5 @@
import { isDarwin } from "../constants"; import { isDarwin } from "../constants";
import { t } from "../i18n"; import { t } from "../i18n";
import { SubtypeOf } from "../utility-types";
import { getShortcutKey } from "../utils"; import { getShortcutKey } from "../utils";
import { ActionName } from "./types"; import { ActionName } from "./types";
+1 -3
View File
@@ -6,7 +6,6 @@ import {
ExcalidrawProps, ExcalidrawProps,
BinaryFiles, BinaryFiles,
} from "../types"; } from "../types";
import { MarkOptional } from "../utility-types";
export type ActionSource = "ui" | "keyboard" | "contextMenu" | "api"; export type ActionSource = "ui" | "keyboard" | "contextMenu" | "api";
@@ -114,8 +113,7 @@ export type ActionName =
| "toggleLock" | "toggleLock"
| "toggleLinearEditor" | "toggleLinearEditor"
| "toggleEraserTool" | "toggleEraserTool"
| "toggleHandTool" | "toggleHandTool";
| "wrapTextInContainer";
export type PanelComponentProps = { export type PanelComponentProps = {
elements: readonly ExcalidrawElement[]; elements: readonly ExcalidrawElement[];
+22 -30
View File
@@ -1,30 +1,22 @@
export const trackEvent = ( export const trackEvent =
category: string, typeof process !== "undefined" &&
action: string, process.env?.REACT_APP_GOOGLE_ANALYTICS_ID &&
label?: string, typeof window !== "undefined" &&
value?: number, window.gtag
) => { ? (category: string, action: string, label?: string, value?: number) => {
try { try {
// Uncomment the next line to track locally window.gtag("event", action, {
// console.log("Track Event", { category, action, label, value }); event_category: category,
event_label: label,
if (typeof window === "undefined" || process.env.JEST_WORKER_ID) { value,
return; });
} } catch (error) {
console.error("error logging to ga", error);
if (process.env.REACT_APP_GOOGLE_ANALYTICS_ID && window.gtag) { }
window.gtag("event", action, { }
event_category: category, : typeof process !== "undefined" && process.env?.JEST_WORKER_ID
event_label: label, ? (category: string, action: string, label?: string, value?: number) => {}
value, : (category: string, action: string, label?: string, value?: number) => {
}); // Uncomment the next line to track locally
} // console.log("Track Event", { category, action, label, value });
};
// MATOMO event tracking _paq must be same as the one in index.html
if (window._paq) {
window._paq.push(["trackEvent", category, action, label, value]);
}
} catch (error) {
console.error("error during analytics", error);
}
};
+8 -9
View File
@@ -1,6 +1,5 @@
import oc from "open-color"; import oc from "open-color";
import { import {
DEFAULT_ELEMENT_PROPS,
DEFAULT_FONT_FAMILY, DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE,
DEFAULT_TEXT_ALIGN, DEFAULT_TEXT_ALIGN,
@@ -24,18 +23,18 @@ export const getDefaultAppState = (): Omit<
theme: THEME.LIGHT, theme: THEME.LIGHT,
collaborators: new Map(), collaborators: new Map(),
currentChartType: "bar", currentChartType: "bar",
currentItemBackgroundColor: DEFAULT_ELEMENT_PROPS.backgroundColor, currentItemBackgroundColor: "transparent",
currentItemEndArrowhead: "arrow", currentItemEndArrowhead: "arrow",
currentItemFillStyle: DEFAULT_ELEMENT_PROPS.fillStyle, currentItemFillStyle: "hachure",
currentItemFontFamily: DEFAULT_FONT_FAMILY, currentItemFontFamily: DEFAULT_FONT_FAMILY,
currentItemFontSize: DEFAULT_FONT_SIZE, currentItemFontSize: DEFAULT_FONT_SIZE,
currentItemOpacity: DEFAULT_ELEMENT_PROPS.opacity, currentItemOpacity: 100,
currentItemRoughness: DEFAULT_ELEMENT_PROPS.roughness, currentItemRoughness: 1,
currentItemStartArrowhead: null, currentItemStartArrowhead: null,
currentItemStrokeColor: DEFAULT_ELEMENT_PROPS.strokeColor, currentItemStrokeColor: oc.black,
currentItemRoundness: "round", currentItemRoundness: "round",
currentItemStrokeStyle: DEFAULT_ELEMENT_PROPS.strokeStyle, currentItemStrokeStyle: "solid",
currentItemStrokeWidth: DEFAULT_ELEMENT_PROPS.strokeWidth, currentItemStrokeWidth: 1,
currentItemTextAlign: DEFAULT_TEXT_ALIGN, currentItemTextAlign: DEFAULT_TEXT_ALIGN,
cursorButton: "up", cursorButton: "up",
draggingElement: null, draggingElement: null,
@@ -45,7 +44,7 @@ export const getDefaultAppState = (): Omit<
activeTool: { activeTool: {
type: "selection", type: "selection",
customType: null, customType: null,
locked: DEFAULT_ELEMENT_PROPS.locked, locked: false,
lastActiveTool: null, lastActiveTool: null,
}, },
penMode: false, penMode: false,
+17 -1
View File
@@ -1,5 +1,10 @@
import colors from "./colors"; import colors from "./colors";
import { DEFAULT_FONT_SIZE, ENV } from "./constants"; import {
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
ENV,
VERTICAL_ALIGN,
} from "./constants";
import { newElement, newLinearElement, newTextElement } from "./element"; import { newElement, newLinearElement, newTextElement } from "./element";
import { NonDeletedExcalidrawElement } from "./element/types"; import { NonDeletedExcalidrawElement } from "./element/types";
import { randomId } from "./random"; import { randomId } from "./random";
@@ -161,7 +166,17 @@ const bgColors = colors.elementBackground.slice(
// Put all the common properties here so when the whole chart is selected // Put all the common properties here so when the whole chart is selected
// the properties dialog shows the correct selected values // the properties dialog shows the correct selected values
const commonProps = { const commonProps = {
fillStyle: "hachure",
fontFamily: DEFAULT_FONT_FAMILY,
fontSize: DEFAULT_FONT_SIZE,
opacity: 100,
roughness: 1,
strokeColor: colors.elementStroke[0], strokeColor: colors.elementStroke[0],
roundness: null,
strokeStyle: "solid",
strokeWidth: 1,
verticalAlign: VERTICAL_ALIGN.MIDDLE,
locked: false,
} as const; } as const;
const getChartDimentions = (spreadsheet: Spreadsheet) => { const getChartDimentions = (spreadsheet: Spreadsheet) => {
@@ -308,6 +323,7 @@ const chartBaseElements = (
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,
roundness: null, roundness: null,
strokeStyle: "solid",
textAlign: "center", textAlign: "center",
}) })
: null; : null;
+11 -27
View File
@@ -2,12 +2,12 @@ import {
ExcalidrawElement, ExcalidrawElement,
NonDeletedExcalidrawElement, NonDeletedExcalidrawElement,
} from "./element/types"; } from "./element/types";
import { BinaryFiles } from "./types"; import { AppState, BinaryFiles } from "./types";
import { SVG_EXPORT_TAG } from "./scene/export"; import { SVG_EXPORT_TAG } from "./scene/export";
import { tryParseSpreadsheet, Spreadsheet, VALID_SPREADSHEET } from "./charts"; import { tryParseSpreadsheet, Spreadsheet, VALID_SPREADSHEET } from "./charts";
import { EXPORT_DATA_TYPES, MIME_TYPES } from "./constants"; import { EXPORT_DATA_TYPES, MIME_TYPES } from "./constants";
import { isInitializedImageElement } from "./element/typeChecks"; import { isInitializedImageElement } from "./element/typeChecks";
import { isPromiseLike, isTestEnv } from "./utils"; import { isPromiseLike } from "./utils";
type ElementsClipboard = { type ElementsClipboard = {
type: typeof EXPORT_DATA_TYPES.excalidrawClipboard; type: typeof EXPORT_DATA_TYPES.excalidrawClipboard;
@@ -55,40 +55,24 @@ const clipboardContainsElements = (
export const copyToClipboard = async ( export const copyToClipboard = async (
elements: readonly NonDeletedExcalidrawElement[], elements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
files: BinaryFiles | null, files: BinaryFiles | null,
) => { ) => {
let foundFile = false;
const _files = elements.reduce((acc, element) => {
if (isInitializedImageElement(element)) {
foundFile = true;
if (files && files[element.fileId]) {
acc[element.fileId] = files[element.fileId];
}
}
return acc;
}, {} as BinaryFiles);
if (foundFile && !files) {
console.warn(
"copyToClipboard: attempting to file element(s) without providing associated `files` object.",
);
}
// select binded text elements when copying // select binded text elements when copying
const contents: ElementsClipboard = { const contents: ElementsClipboard = {
type: EXPORT_DATA_TYPES.excalidrawClipboard, type: EXPORT_DATA_TYPES.excalidrawClipboard,
elements, elements,
files: files ? _files : undefined, files: files
? elements.reduce((acc, element) => {
if (isInitializedImageElement(element) && files[element.fileId]) {
acc[element.fileId] = files[element.fileId];
}
return acc;
}, {} as BinaryFiles)
: undefined,
}; };
const json = JSON.stringify(contents); const json = JSON.stringify(contents);
if (isTestEnv()) {
return json;
}
CLIPBOARD = json; CLIPBOARD = json;
try { try {
PREFER_APP_CLIPBOARD = false; PREFER_APP_CLIPBOARD = false;
await copyTextToSystemClipboard(json); await copyTextToSystemClipboard(json);
+2 -6
View File
@@ -30,10 +30,7 @@ import clsx from "clsx";
import { actionToggleZenMode } from "../actions"; import { actionToggleZenMode } from "../actions";
import "./Actions.scss"; import "./Actions.scss";
import { Tooltip } from "./Tooltip"; import { Tooltip } from "./Tooltip";
import { import { shouldAllowVerticalAlign } from "../element/textElement";
shouldAllowVerticalAlign,
suppportsHorizontalAlign,
} from "../element/textElement";
export const SelectedShapeActions = ({ export const SelectedShapeActions = ({
appState, appState,
@@ -125,8 +122,7 @@ export const SelectedShapeActions = ({
{renderAction("changeFontFamily")} {renderAction("changeFontFamily")}
{suppportsHorizontalAlign(targetElements) && {renderAction("changeTextAlign")}
renderAction("changeTextAlign")}
</> </>
)} )}
-2
View File
@@ -1,7 +1,6 @@
import { atom, useAtom } from "jotai"; import { atom, useAtom } from "jotai";
import { actionClearCanvas } from "../actions"; import { actionClearCanvas } from "../actions";
import { t } from "../i18n"; import { t } from "../i18n";
import { jotaiScope } from "../jotai";
import { useExcalidrawActionManager } from "./App"; import { useExcalidrawActionManager } from "./App";
import ConfirmDialog from "./ConfirmDialog"; import ConfirmDialog from "./ConfirmDialog";
@@ -10,7 +9,6 @@ export const activeConfirmDialogAtom = atom<"clearCanvas" | null>(null);
export const ActiveConfirmDialog = () => { export const ActiveConfirmDialog = () => {
const [activeConfirmDialog, setActiveConfirmDialog] = useAtom( const [activeConfirmDialog, setActiveConfirmDialog] = useAtom(
activeConfirmDialogAtom, activeConfirmDialogAtom,
jotaiScope,
); );
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
-45
View File
@@ -1,45 +0,0 @@
import ReactDOM from "react-dom";
import * as Renderer from "../renderer/renderScene";
import { reseed } from "../random";
import { render, queryByTestId } from "../tests/test-utils";
import ExcalidrawApp from "../excalidraw-app";
const renderScene = jest.spyOn(Renderer, "renderScene");
describe("Test <App/>", () => {
beforeEach(async () => {
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
localStorage.clear();
renderScene.mockClear();
reseed(7);
});
it("should show error modal when using brave and measureText API is not working", async () => {
(global.navigator as any).brave = {
isBrave: {
name: "isBrave",
},
};
const originalContext = global.HTMLCanvasElement.prototype.getContext("2d");
//@ts-ignore
global.HTMLCanvasElement.prototype.getContext = (contextId) => {
return {
...originalContext,
measureText: () => ({
width: 0,
}),
};
};
await render(<ExcalidrawApp />);
expect(
queryByTestId(
document.querySelector(".excalidraw-modal-container")!,
"brave-measure-text-error",
),
).toMatchSnapshot();
});
});
+68 -212
View File
@@ -60,10 +60,8 @@ import {
ENV, ENV,
EVENT, EVENT,
GRID_SIZE, GRID_SIZE,
IMAGE_MIME_TYPES,
IMAGE_RENDER_TIMEOUT, IMAGE_RENDER_TIMEOUT,
isAndroid, isAndroid,
isBrave,
LINE_CONFIRM_THRESHOLD, LINE_CONFIRM_THRESHOLD,
MAX_ALLOWED_FILE_BYTES, MAX_ALLOWED_FILE_BYTES,
MIME_TYPES, MIME_TYPES,
@@ -110,7 +108,6 @@ import {
textWysiwyg, textWysiwyg,
transformElements, transformElements,
updateTextElement, updateTextElement,
redrawTextBoundingBox,
} from "../element"; } from "../element";
import { import {
bindOrUnbindLinearElement, bindOrUnbindLinearElement,
@@ -128,11 +125,7 @@ import {
} from "../element/binding"; } from "../element/binding";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
import { mutateElement, newElementWith } from "../element/mutateElement"; import { mutateElement, newElementWith } from "../element/mutateElement";
import { import { deepCopyElement, newFreeDrawElement } from "../element/newElement";
deepCopyElement,
duplicateElements,
newFreeDrawElement,
} from "../element/newElement";
import { import {
hasBoundTextElement, hasBoundTextElement,
isArrowElement, isArrowElement,
@@ -234,7 +227,6 @@ import {
updateActiveTool, updateActiveTool,
getShortcutKey, getShortcutKey,
isTransparent, isTransparent,
easeToValuesRAF,
} from "../utils"; } from "../utils";
import { import {
ContextMenu, ContextMenu,
@@ -266,16 +258,13 @@ import throttle from "lodash.throttle";
import { fileOpen, FileSystemHandle } from "../data/filesystem"; import { fileOpen, FileSystemHandle } from "../data/filesystem";
import { import {
bindTextToShapeAfterDuplication, bindTextToShapeAfterDuplication,
getApproxLineHeight,
getApproxMinLineHeight, getApproxMinLineHeight,
getApproxMinLineWidth, getApproxMinLineWidth,
getBoundTextElement, getBoundTextElement,
getContainerCenter, getContainerCenter,
getContainerDims, getContainerDims,
getContainerElement,
getDefaultLineHeight,
getLineHeightInPx,
getTextBindableContainerAtPosition, getTextBindableContainerAtPosition,
isMeasureTextSupported,
isValidTextContainer, isValidTextContainer,
} from "../element/textElement"; } from "../element/textElement";
import { isHittingElementNotConsideringBoundingBox } from "../element/collision"; import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
@@ -290,14 +279,9 @@ import {
import { shouldShowBoundingBox } from "../element/transformHandles"; import { shouldShowBoundingBox } from "../element/transformHandles";
import { Fonts } from "../scene/Fonts"; import { Fonts } from "../scene/Fonts";
import { actionPaste } from "../actions/actionClipboard"; import { actionPaste } from "../actions/actionClipboard";
import { import { actionToggleHandTool } from "../actions/actionCanvas";
actionToggleHandTool,
zoomToFitElements,
} from "../actions/actionCanvas";
import { jotaiStore } from "../jotai"; import { jotaiStore } from "../jotai";
import { activeConfirmDialogAtom } from "./ActiveConfirmDialog"; import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
import { actionWrapTextInContainer } from "../actions/actionBoundText";
import BraveMeasureTextError from "./BraveMeasureTextError";
const deviceContextInitialValue = { const deviceContextInitialValue = {
isSmScreen: false, isSmScreen: false,
@@ -442,6 +426,7 @@ class App extends React.Component<AppProps, AppState> {
}; };
this.id = nanoid(); this.id = nanoid();
this.library = new Library(this); this.library = new Library(this);
if (excalidrawRef) { if (excalidrawRef) {
const readyPromise = const readyPromise =
@@ -723,8 +708,6 @@ class App extends React.Component<AppProps, AppState> {
const theme = const theme =
actionResult?.appState?.theme || this.props.theme || THEME.LIGHT; actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
let name = actionResult?.appState?.name ?? this.state.name; let name = actionResult?.appState?.name ?? this.state.name;
const errorMessage =
actionResult?.appState?.errorMessage ?? this.state.errorMessage;
if (typeof this.props.viewModeEnabled !== "undefined") { if (typeof this.props.viewModeEnabled !== "undefined") {
viewModeEnabled = this.props.viewModeEnabled; viewModeEnabled = this.props.viewModeEnabled;
} }
@@ -740,6 +723,7 @@ class App extends React.Component<AppProps, AppState> {
if (typeof this.props.name !== "undefined") { if (typeof this.props.name !== "undefined") {
name = this.props.name; name = this.props.name;
} }
this.setState( this.setState(
(state) => { (state) => {
// using Object.assign instead of spread to fool TS 4.2.2+ into // using Object.assign instead of spread to fool TS 4.2.2+ into
@@ -757,7 +741,6 @@ class App extends React.Component<AppProps, AppState> {
gridSize, gridSize,
theme, theme,
name, name,
errorMessage,
}); });
}, },
() => { () => {
@@ -886,6 +869,7 @@ class App extends React.Component<AppProps, AppState> {
), ),
}; };
} }
// FontFaceSet loadingdone event we listen on may not always fire // FontFaceSet loadingdone event we listen on may not always fire
// (looking at you Safari), so on init we manually load fonts for current // (looking at you Safari), so on init we manually load fonts for current
// text elements on canvas, and rerender them once done. This also // text elements on canvas, and rerender them once done. This also
@@ -1013,13 +997,6 @@ class App extends React.Component<AppProps, AppState> {
} else { } else {
this.updateDOMRect(this.initializeScene); this.updateDOMRect(this.initializeScene);
} }
// note that this check seems to always pass in localhost
if (isBrave() && !isMeasureTextSupported()) {
this.setState({
errorMessage: <BraveMeasureTextError />,
});
}
} }
public componentWillUnmount() { public componentWillUnmount() {
@@ -1590,7 +1567,6 @@ class App extends React.Component<AppProps, AppState> {
elements: data.elements, elements: data.elements,
files: data.files || null, files: data.files || null,
position: "cursor", position: "cursor",
retainSeed: isPlainPaste,
}); });
} else if (data.text) { } else if (data.text) {
this.addTextFromPaste(data.text, isPlainPaste); this.addTextFromPaste(data.text, isPlainPaste);
@@ -1604,7 +1580,6 @@ class App extends React.Component<AppProps, AppState> {
elements: readonly ExcalidrawElement[]; elements: readonly ExcalidrawElement[];
files: BinaryFiles | null; files: BinaryFiles | null;
position: { clientX: number; clientY: number } | "cursor" | "center"; position: { clientX: number; clientY: number } | "cursor" | "center";
retainSeed?: boolean;
}) => { }) => {
const elements = restoreElements(opts.elements, null); const elements = restoreElements(opts.elements, null);
const [minX, minY, maxX, maxY] = getCommonBounds(elements); const [minX, minY, maxX, maxY] = getCommonBounds(elements);
@@ -1632,39 +1607,36 @@ class App extends React.Component<AppProps, AppState> {
const dx = x - elementsCenterX; const dx = x - elementsCenterX;
const dy = y - elementsCenterY; const dy = y - elementsCenterY;
const groupIdMap = new Map();
const [gridX, gridY] = getGridPoint(dx, dy, this.state.gridSize); const [gridX, gridY] = getGridPoint(dx, dy, this.state.gridSize);
const newElements = duplicateElements( const oldIdToDuplicatedId = new Map();
elements.map((element) => { const newElements = elements.map((element) => {
return newElementWith(element, { const newElement = duplicateElement(
this.state.editingGroupId,
groupIdMap,
element,
{
x: element.x + gridX - minX, x: element.x + gridX - minX,
y: element.y + gridY - minY, y: element.y + gridY - minY,
}); },
}), );
{ oldIdToDuplicatedId.set(element.id, newElement.id);
randomizeSeed: !opts.retainSeed, return newElement;
}, });
); bindTextToShapeAfterDuplication(newElements, elements, oldIdToDuplicatedId);
const nextElements = [ const nextElements = [
...this.scene.getElementsIncludingDeleted(), ...this.scene.getElementsIncludingDeleted(),
...newElements, ...newElements,
]; ];
fixBindingsAfterDuplication(nextElements, elements, oldIdToDuplicatedId);
this.scene.replaceAllElements(nextElements);
newElements.forEach((newElement) => {
if (isTextElement(newElement) && isBoundToContainer(newElement)) {
const container = getContainerElement(newElement);
redrawTextBoundingBox(newElement, container);
}
});
if (opts.files) { if (opts.files) {
this.files = { ...this.files, ...opts.files }; this.files = { ...this.files, ...opts.files };
} }
this.scene.replaceAllElements(nextElements);
this.history.resumeRecording(); this.history.resumeRecording();
this.setState( this.setState(
@@ -1737,14 +1709,12 @@ class App extends React.Component<AppProps, AppState> {
(acc: ExcalidrawTextElement[], line, idx) => { (acc: ExcalidrawTextElement[], line, idx) => {
const text = line.trim(); const text = line.trim();
const lineHeight = getDefaultLineHeight(textElementProps.fontFamily);
if (text.length) { if (text.length) {
const element = newTextElement({ const element = newTextElement({
...textElementProps, ...textElementProps,
x, x,
y: currentY, y: currentY,
text, text,
lineHeight,
}); });
acc.push(element); acc.push(element);
currentY += element.height + LINE_GAP; currentY += element.height + LINE_GAP;
@@ -1753,9 +1723,14 @@ class App extends React.Component<AppProps, AppState> {
// add paragraph only if previous line was not empty, IOW don't add // add paragraph only if previous line was not empty, IOW don't add
// more than one empty line // more than one empty line
if (prevLine) { if (prevLine) {
currentY += const defaultLineHeight = getApproxLineHeight(
getLineHeightInPx(textElementProps.fontSize, lineHeight) + getFontString({
LINE_GAP; fontSize: textElementProps.fontSize,
fontFamily: textElementProps.fontFamily,
}),
);
currentY += defaultLineHeight + LINE_GAP;
} }
} }
@@ -1848,89 +1823,18 @@ class App extends React.Component<AppProps, AppState> {
this.actionManager.executeAction(actionToggleHandTool); this.actionManager.executeAction(actionToggleHandTool);
}; };
/**
* Zooms on canvas viewport center
*/
zoomCanvas = (
/** decimal fraction between 0.1 (10% zoom) and 30 (3000% zoom) */
value: number,
) => {
this.setState({
...getStateForZoom(
{
viewportX: this.state.width / 2 + this.state.offsetLeft,
viewportY: this.state.height / 2 + this.state.offsetTop,
nextZoom: getNormalizedZoom(value),
},
this.state,
),
});
};
private cancelInProgresAnimation: (() => void) | null = null;
scrollToContent = ( scrollToContent = (
target: target:
| ExcalidrawElement | ExcalidrawElement
| readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(), | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
opts?: { fitToContent?: boolean; animate?: boolean; duration?: number },
) => { ) => {
this.cancelInProgresAnimation?.(); this.setState({
...calculateScrollCenter(
// convert provided target into ExcalidrawElement[] if necessary Array.isArray(target) ? target : [target],
const targets = Array.isArray(target) ? target : [target]; this.state,
this.canvas,
let zoom = this.state.zoom; ),
let scrollX = this.state.scrollX; });
let scrollY = this.state.scrollY;
if (opts?.fitToContent) {
// compute an appropriate viewport location (scroll X, Y) and zoom level
// that fit the target elements on the scene
const { appState } = zoomToFitElements(targets, this.state, false);
zoom = appState.zoom;
scrollX = appState.scrollX;
scrollY = appState.scrollY;
} else {
// compute only the viewport location, without any zoom adjustment
const scroll = calculateScrollCenter(targets, this.state, this.canvas);
scrollX = scroll.scrollX;
scrollY = scroll.scrollY;
}
// when animating, we use RequestAnimationFrame to prevent the animation
// from slowing down other processes
if (opts?.animate) {
const origScrollX = this.state.scrollX;
const origScrollY = this.state.scrollY;
// zoom animation could become problematic on scenes with large number
// of elements, setting it to its final value to improve user experience.
//
// using zoomCanvas() to zoom on current viewport center
this.zoomCanvas(zoom.value);
const cancel = easeToValuesRAF(
[origScrollX, origScrollY],
[scrollX, scrollY],
(scrollX, scrollY) => this.setState({ scrollX, scrollY }),
{ duration: opts?.duration ?? 500 },
);
this.cancelInProgresAnimation = () => {
cancel();
this.cancelInProgresAnimation = null;
};
} else {
this.setState({ scrollX, scrollY, zoom });
}
};
/** use when changing scrollX/scrollY/zoom based on user interaction */
private translateCanvas: React.Component<any, AppState>["setState"] = (
state,
) => {
this.cancelInProgresAnimation?.();
this.setState(state);
}; };
setToast = ( setToast = (
@@ -2131,13 +2035,9 @@ class App extends React.Component<AppProps, AppState> {
offset = -offset; offset = -offset;
} }
if (event.shiftKey) { if (event.shiftKey) {
this.translateCanvas((state) => ({ this.setState((state) => ({ scrollX: state.scrollX + offset }));
scrollX: state.scrollX + offset,
}));
} else { } else {
this.translateCanvas((state) => ({ this.setState((state) => ({ scrollY: state.scrollY + offset }));
scrollY: state.scrollY + offset,
}));
} }
} }
@@ -2685,13 +2585,6 @@ class App extends React.Component<AppProps, AppState> {
existingTextElement = this.getTextElementAtPosition(sceneX, sceneY); existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
} }
const fontFamily =
existingTextElement?.fontFamily || this.state.currentItemFontFamily;
const lineHeight =
existingTextElement?.lineHeight || getDefaultLineHeight(fontFamily);
const fontSize = this.state.currentItemFontSize;
if ( if (
!existingTextElement && !existingTextElement &&
shouldBindToContainer && shouldBindToContainer &&
@@ -2699,14 +2592,11 @@ class App extends React.Component<AppProps, AppState> {
!isArrowElement(container) !isArrowElement(container)
) { ) {
const fontString = { const fontString = {
fontSize, fontSize: this.state.currentItemFontSize,
fontFamily, fontFamily: this.state.currentItemFontFamily,
}; };
const minWidth = getApproxMinLineWidth( const minWidth = getApproxMinLineWidth(getFontString(fontString));
getFontString(fontString), const minHeight = getApproxMinLineHeight(getFontString(fontString));
lineHeight,
);
const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
const containerDims = getContainerDims(container); const containerDims = getContainerDims(container);
const newHeight = Math.max(containerDims.height, minHeight); const newHeight = Math.max(containerDims.height, minHeight);
const newWidth = Math.max(containerDims.width, minWidth); const newWidth = Math.max(containerDims.width, minWidth);
@@ -2738,9 +2628,10 @@ class App extends React.Component<AppProps, AppState> {
strokeStyle: this.state.currentItemStrokeStyle, strokeStyle: this.state.currentItemStrokeStyle,
roughness: this.state.currentItemRoughness, roughness: this.state.currentItemRoughness,
opacity: this.state.currentItemOpacity, opacity: this.state.currentItemOpacity,
roundness: null,
text: "", text: "",
fontSize, fontSize: this.state.currentItemFontSize,
fontFamily, fontFamily: this.state.currentItemFontFamily,
textAlign: parentCenterPosition textAlign: parentCenterPosition
? "center" ? "center"
: this.state.currentItemTextAlign, : this.state.currentItemTextAlign,
@@ -2749,8 +2640,7 @@ class App extends React.Component<AppProps, AppState> {
: DEFAULT_VERTICAL_ALIGN, : DEFAULT_VERTICAL_ALIGN,
containerId: shouldBindToContainer ? container?.id : undefined, containerId: shouldBindToContainer ? container?.id : undefined,
groupIds: container?.groupIds ?? [], groupIds: container?.groupIds ?? [],
lineHeight, locked: false,
angle: container?.angle ?? 0,
}); });
if (!existingTextElement && shouldBindToContainer && container) { if (!existingTextElement && shouldBindToContainer && container) {
@@ -2773,6 +2663,14 @@ class App extends React.Component<AppProps, AppState> {
element, element,
]); ]);
} }
// case: creating new text not centered to parent element → offset Y
// so that the text is centered to cursor position
if (!parentCenterPosition) {
mutateElement(element, {
y: element.y - element.baseline / 2,
});
}
} }
this.setState({ this.setState({
@@ -2866,6 +2764,7 @@ class App extends React.Component<AppProps, AppState> {
); );
if (container) { if (container) {
if ( if (
isArrowElement(container) ||
hasBoundTextElement(container) || hasBoundTextElement(container) ||
!isTransparent(container.backgroundColor) || !isTransparent(container.backgroundColor) ||
isHittingElementNotConsideringBoundingBox(container, this.state, [ isHittingElementNotConsideringBoundingBox(container, this.state, [
@@ -3017,12 +2916,12 @@ class App extends React.Component<AppProps, AppState> {
state, state,
); );
this.translateCanvas({ return {
zoom: zoomState.zoom, zoom: zoomState.zoom,
scrollX: zoomState.scrollX + deltaX / nextZoom, scrollX: zoomState.scrollX + deltaX / nextZoom,
scrollY: zoomState.scrollY + deltaY / nextZoom, scrollY: zoomState.scrollY + deltaY / nextZoom,
shouldCacheIgnoreZoom: true, shouldCacheIgnoreZoom: true,
}); };
}); });
this.resetShouldCacheIgnoreZoomDebounced(); this.resetShouldCacheIgnoreZoomDebounced();
} else { } else {
@@ -3500,43 +3399,6 @@ class App extends React.Component<AppProps, AppState> {
this.setState({ contextMenu: null }); this.setState({ contextMenu: null });
} }
this.updateGestureOnPointerDown(event);
// if dragging element is freedraw and another pointerdown event occurs
// a second finger is on the screen
// discard the freedraw element if it is very short because it is likely
// just a spike, otherwise finalize the freedraw element when the second
// finger is lifted
if (
event.pointerType === "touch" &&
this.state.draggingElement &&
this.state.draggingElement.type === "freedraw"
) {
const element = this.state.draggingElement as ExcalidrawFreeDrawElement;
this.updateScene({
...(element.points.length < 10
? {
elements: this.scene
.getElementsIncludingDeleted()
.filter((el) => el.id !== element.id),
}
: {}),
appState: {
draggingElement: null,
editingElement: null,
startBoundElement: null,
suggestedBindings: [],
selectedElementIds: Object.keys(this.state.selectedElementIds)
.filter((key) => key !== element.id)
.reduce((obj: { [id: string]: boolean }, key) => {
obj[key] = this.state.selectedElementIds[key];
return obj;
}, {}),
},
});
return;
}
// remove any active selection when we start to interact with canvas // remove any active selection when we start to interact with canvas
// (mainly, we care about removing selection outside the component which // (mainly, we care about removing selection outside the component which
// would prevent our copy handling otherwise) // would prevent our copy handling otherwise)
@@ -3576,6 +3438,8 @@ class App extends React.Component<AppProps, AppState> {
}); });
this.savePointer(event.clientX, event.clientY, "down"); this.savePointer(event.clientX, event.clientY, "down");
this.updateGestureOnPointerDown(event);
if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) { if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
return; return;
} }
@@ -3833,7 +3697,7 @@ class App extends React.Component<AppProps, AppState> {
window.addEventListener(EVENT.POINTER_UP, enableNextPaste); window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
} }
this.translateCanvas({ this.setState({
scrollX: this.state.scrollX - deltaX / this.state.zoom.value, scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
scrollY: this.state.scrollY - deltaY / this.state.zoom.value, scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
}); });
@@ -4726,12 +4590,7 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.drag.hasOccurred = true; pointerDownState.drag.hasOccurred = true;
// prevent dragging even if we're no longer holding cmd/ctrl otherwise // prevent dragging even if we're no longer holding cmd/ctrl otherwise
// it would have weird results (stuff jumping all over the screen) // it would have weird results (stuff jumping all over the screen)
// Checking for editingElement to avoid jump while editing on mobile #6503 if (selectedElements.length > 0 && !pointerDownState.withCmdOrCtrl) {
if (
selectedElements.length > 0 &&
!pointerDownState.withCmdOrCtrl &&
!this.state.editingElement
) {
const [dragX, dragY] = getGridPoint( const [dragX, dragY] = getGridPoint(
pointerCoords.x - pointerDownState.drag.offset.x, pointerCoords.x - pointerDownState.drag.offset.x,
pointerCoords.y - pointerDownState.drag.offset.y, pointerCoords.y - pointerDownState.drag.offset.y,
@@ -4984,7 +4843,7 @@ class App extends React.Component<AppProps, AppState> {
if (pointerDownState.scrollbars.isOverHorizontal) { if (pointerDownState.scrollbars.isOverHorizontal) {
const x = event.clientX; const x = event.clientX;
const dx = x - pointerDownState.lastCoords.x; const dx = x - pointerDownState.lastCoords.x;
this.translateCanvas({ this.setState({
scrollX: this.state.scrollX - dx / this.state.zoom.value, scrollX: this.state.scrollX - dx / this.state.zoom.value,
}); });
pointerDownState.lastCoords.x = x; pointerDownState.lastCoords.x = x;
@@ -4994,7 +4853,7 @@ class App extends React.Component<AppProps, AppState> {
if (pointerDownState.scrollbars.isOverVertical) { if (pointerDownState.scrollbars.isOverVertical) {
const y = event.clientY; const y = event.clientY;
const dy = y - pointerDownState.lastCoords.y; const dy = y - pointerDownState.lastCoords.y;
this.translateCanvas({ this.setState({
scrollY: this.state.scrollY - dy / this.state.zoom.value, scrollY: this.state.scrollY - dy / this.state.zoom.value,
}); });
pointerDownState.lastCoords.y = y; pointerDownState.lastCoords.y = y;
@@ -5754,9 +5613,7 @@ class App extends React.Component<AppProps, AppState> {
const imageFile = await fileOpen({ const imageFile = await fileOpen({
description: "Image", description: "Image",
extensions: Object.keys( extensions: ["jpg", "png", "svg", "gif"],
IMAGE_MIME_TYPES,
) as (keyof typeof IMAGE_MIME_TYPES)[],
}); });
const imageElement = this.createImageElement({ const imageElement = this.createImageElement({
@@ -6378,7 +6235,6 @@ class App extends React.Component<AppProps, AppState> {
actionGroup, actionGroup,
actionUnbindText, actionUnbindText,
actionBindText, actionBindText,
actionWrapTextInContainer,
actionUngroup, actionUngroup,
CONTEXT_MENU_SEPARATOR, CONTEXT_MENU_SEPARATOR,
actionAddToLibrary, actionAddToLibrary,
@@ -6425,7 +6281,7 @@ class App extends React.Component<AppProps, AppState> {
// reduced amplification for small deltas (small movements on a trackpad) // reduced amplification for small deltas (small movements on a trackpad)
Math.min(1, absDelta / 20); Math.min(1, absDelta / 20);
this.translateCanvas((state) => ({ this.setState((state) => ({
...getStateForZoom( ...getStateForZoom(
{ {
viewportX: cursorX, viewportX: cursorX,
@@ -6442,14 +6298,14 @@ class App extends React.Component<AppProps, AppState> {
// scroll horizontally when shift pressed // scroll horizontally when shift pressed
if (event.shiftKey) { if (event.shiftKey) {
this.translateCanvas(({ zoom, scrollX }) => ({ this.setState(({ zoom, scrollX }) => ({
// on Mac, shift+wheel tends to result in deltaX // on Mac, shift+wheel tends to result in deltaX
scrollX: scrollX - (deltaY || deltaX) / zoom.value, scrollX: scrollX - (deltaY || deltaX) / zoom.value,
})); }));
return; return;
} }
this.translateCanvas(({ zoom, scrollX, scrollY }) => ({ this.setState(({ zoom, scrollX, scrollY }) => ({
scrollX: scrollX - deltaX / zoom.value, scrollX: scrollX - deltaX / zoom.value,
scrollY: scrollY - deltaY / zoom.value, scrollY: scrollY - deltaY / zoom.value,
})); }));
-42
View File
@@ -1,42 +0,0 @@
import { t } from "../i18n";
const BraveMeasureTextError = () => {
return (
<div data-testid="brave-measure-text-error">
<p>
{t("errors.brave_measure_text_error.start")} &nbsp;
<span style={{ fontWeight: 600 }}>
{t("errors.brave_measure_text_error.aggressive_block_fingerprint")}
</span>{" "}
{t("errors.brave_measure_text_error.setting_enabled")}.
<br />
<br />
{t("errors.brave_measure_text_error.break")}{" "}
<span style={{ fontWeight: 600 }}>
{t("errors.brave_measure_text_error.text_elements")}
</span>{" "}
{t("errors.brave_measure_text_error.in_your_drawings")}.
</p>
<p>
{t("errors.brave_measure_text_error.strongly_recommend")}{" "}
<a href="http://docs.excalidraw.com/docs/@excalidraw/excalidraw/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser">
{" "}
{t("errors.brave_measure_text_error.steps")}
</a>{" "}
{t("errors.brave_measure_text_error.how")}.
</p>
<p>
{t("errors.brave_measure_text_error.disable_setting")}{" "}
<a href="https://github.com/excalidraw/excalidraw/issues/new">
{t("errors.brave_measure_text_error.issue")}
</a>{" "}
{t("errors.brave_measure_text_error.write")}{" "}
<a href="https://discord.gg/UexuTaE">
{t("errors.brave_measure_text_error.discord")}
</a>
.
</p>
</div>
);
};
export default BraveMeasureTextError;
+26 -52
View File
@@ -1,59 +1,33 @@
import clsx from "clsx"; import clsx from "clsx";
// TODO: It might be "clever" to add option.icon to the existing component <ButtonSelect /> // TODO: It might be "clever" to add option.icon to the existing component <ButtonSelect />
export const ButtonIconSelect = <T extends Object>( export const ButtonIconSelect = <T extends Object>({
props: { options,
options: { value,
value: T; onChange,
text: string; group,
icon: JSX.Element; }: {
testId?: string; options: { value: T; text: string; icon: JSX.Element; testId?: string }[];
/** if not supplied, defaults to value identity check */ value: T | null;
active?: boolean; onChange: (value: T) => void;
}[]; group: string;
value: T | null; }) => (
type?: "radio" | "button";
} & (
| { type?: "radio"; group: string; onChange: (value: T) => void }
| {
type: "button";
onClick: (
value: T,
event: React.MouseEvent<HTMLButtonElement, MouseEvent>,
) => void;
}
),
) => (
<div className="buttonList buttonListIcon"> <div className="buttonList buttonListIcon">
{props.options.map((option) => {options.map((option) => (
props.type === "button" ? ( <label
<button key={option.text}
key={option.text} className={clsx({ active: value === option.value })}
onClick={(event) => props.onClick(option.value, event)} title={option.text}
className={clsx({ >
active: option.active ?? props.value === option.value, <input
})} type="radio"
name={group}
onChange={() => onChange(option.value)}
checked={value === option.value}
data-testid={option.testId} data-testid={option.testId}
title={option.text} />
> {option.icon}
{option.icon} </label>
</button> ))}
) : (
<label
key={option.text}
className={clsx({ active: props.value === option.value })}
title={option.text}
>
<input
type="radio"
name={props.group}
onChange={() => props.onChange(option.value)}
checked={props.value === option.value}
data-testid={option.testId}
/>
{option.icon}
</label>
),
)}
</div> </div>
); );
-1
View File
@@ -183,7 +183,6 @@
width: 100%; width: 100%;
margin: 0; margin: 0;
font-size: 0.875rem; font-size: 0.875rem;
font-family: inherit;
background-color: transparent; background-color: transparent;
color: var(--text-primary-color); color: var(--text-primary-color);
border: 0; border: 0;
+1 -2
View File
@@ -6,7 +6,6 @@ import DialogActionButton from "./DialogActionButton";
import { useSetAtom } from "jotai"; import { useSetAtom } from "jotai";
import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent"; import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent";
import { useExcalidrawSetAppState } from "./App"; import { useExcalidrawSetAppState } from "./App";
import { jotaiScope } from "../jotai";
interface Props extends Omit<DialogProps, "onCloseRequest"> { interface Props extends Omit<DialogProps, "onCloseRequest"> {
onConfirm: () => void; onConfirm: () => void;
@@ -25,7 +24,7 @@ const ConfirmDialog = (props: Props) => {
...rest ...rest
} = props; } = props;
const setAppState = useExcalidrawSetAppState(); const setAppState = useExcalidrawSetAppState();
const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom, jotaiScope); const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
return ( return (
<Dialog <Dialog
-1
View File
@@ -30,7 +30,6 @@
background-color: transparent; background-color: transparent;
border: none; border: none;
white-space: nowrap; white-space: nowrap;
font-family: inherit;
display: grid; display: grid;
grid-template-columns: 1fr 0.2fr; grid-template-columns: 1fr 0.2fr;
+1 -2
View File
@@ -16,7 +16,6 @@ import { AppState } from "../types";
import { queryFocusableElements } from "../utils"; import { queryFocusableElements } from "../utils";
import { useSetAtom } from "jotai"; import { useSetAtom } from "jotai";
import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent"; import { isLibraryMenuOpenAtom } from "./LibraryMenuHeaderContent";
import { jotaiScope } from "../jotai";
export interface DialogProps { export interface DialogProps {
children: React.ReactNode; children: React.ReactNode;
@@ -73,7 +72,7 @@ export const Dialog = (props: DialogProps) => {
}, [islandNode, props.autofocus]); }, [islandNode, props.autofocus]);
const setAppState = useExcalidrawSetAppState(); const setAppState = useExcalidrawSetAppState();
const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom, jotaiScope); const setIsLibraryMenuOpen = useSetAtom(isLibraryMenuOpenAtom);
const onClose = () => { const onClose = () => {
setAppState({ openMenu: null }); setAppState({ openMenu: null });
+4 -4
View File
@@ -5,13 +5,13 @@ import { Dialog } from "./Dialog";
import { useExcalidrawContainer } from "./App"; import { useExcalidrawContainer } from "./App";
export const ErrorDialog = ({ export const ErrorDialog = ({
children, message,
onClose, onClose,
}: { }: {
children?: React.ReactNode; message: string;
onClose?: () => void; onClose?: () => void;
}) => { }) => {
const [modalIsShown, setModalIsShown] = useState(!!children); const [modalIsShown, setModalIsShown] = useState(!!message);
const { container: excalidrawContainer } = useExcalidrawContainer(); const { container: excalidrawContainer } = useExcalidrawContainer();
const handleClose = React.useCallback(() => { const handleClose = React.useCallback(() => {
@@ -32,7 +32,7 @@ export const ErrorDialog = ({
onCloseRequest={handleClose} onCloseRequest={handleClose}
title={t("errorDialog.title")} title={t("errorDialog.title")}
> >
<div style={{ whiteSpace: "pre-wrap" }}>{children}</div> <div style={{ whiteSpace: "pre-wrap" }}>{message}</div>
</Dialog> </Dialog>
)} )}
</> </>
-4
View File
@@ -9,10 +9,6 @@
text-align: center; text-align: center;
padding: var(--preview-padding); padding: var(--preview-padding);
margin-bottom: calc(var(--space-factor) * 3); margin-bottom: calc(var(--space-factor) * 3);
display: flex;
justify-content: center;
align-items: center;
} }
.ExportDialog__preview canvas { .ExportDialog__preview canvas {
+3 -3
View File
@@ -1,7 +1,7 @@
import { t } from "../i18n";
import { HelpIcon } from "./icons"; import { HelpIcon } from "./icons";
type HelpButtonProps = { type HelpButtonProps = {
title?: string;
name?: string; name?: string;
id?: string; id?: string;
onClick?(): void; onClick?(): void;
@@ -12,8 +12,8 @@ export const HelpButton = (props: HelpButtonProps) => (
className="help-icon" className="help-icon"
onClick={props.onClick} onClick={props.onClick}
type="button" type="button"
title={`${t("helpDialog.title")} — ?`} title={`${props.title} — ?`}
aria-label={t("helpDialog.title")} aria-label={props.title}
> >
{HelpIcon} {HelpIcon}
</button> </button>
+5 -6
View File
@@ -165,12 +165,11 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
shortcuts={[KEYS.E, KEYS["0"]]} shortcuts={[KEYS.E, KEYS["0"]]}
/> />
<Shortcut <Shortcut
label={t("helpDialog.editLineArrowPoints")} label={t("helpDialog.editSelectedShape")}
shortcuts={[getShortcutKey("CtrlOrCmd+Enter")]} shortcuts={[
/> getShortcutKey("CtrlOrCmd+Enter"),
<Shortcut getShortcutKey(`CtrlOrCmd + ${t("helpDialog.doubleClick")}`),
label={t("helpDialog.editText")} ]}
shortcuts={[getShortcutKey("Enter")]}
/> />
<Shortcut <Shortcut
label={t("helpDialog.textNewLine")} label={t("helpDialog.textNewLine")}
+13 -11
View File
@@ -4,6 +4,7 @@ import { canvasToBlob } from "../data/blob";
import { NonDeletedExcalidrawElement } from "../element/types"; import { NonDeletedExcalidrawElement } from "../element/types";
import { t } from "../i18n"; import { t } from "../i18n";
import { getSelectedElements, isSomeElementSelected } from "../scene"; import { getSelectedElements, isSomeElementSelected } from "../scene";
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 } from "./icons"; import { clipboard } from "./icons";
@@ -14,7 +15,6 @@ import { CheckboxItem } from "./CheckboxItem";
import { DEFAULT_EXPORT_PADDING, isFirefox } 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";
import { exportToCanvas } from "../packages/utils";
const supportsContextFilters = const supportsContextFilters =
"filter" in document.createElement("canvas").getContext("2d")!; "filter" in document.createElement("canvas").getContext("2d")!;
@@ -83,6 +83,7 @@ const ImageExportModal = ({
const someElementIsSelected = isSomeElementSelected(elements, appState); const someElementIsSelected = isSomeElementSelected(elements, appState);
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 [renderError, setRenderError] = useState<Error | null>(null); const [renderError, setRenderError] = useState<Error | null>(null);
const exportedElements = exportSelected const exportedElements = exportSelected
@@ -98,16 +99,10 @@ const ImageExportModal = ({
if (!previewNode) { if (!previewNode) {
return; return;
} }
const maxWidth = previewNode.offsetWidth; exportToCanvas(exportedElements, appState, files, {
if (!maxWidth) { exportBackground,
return; viewBackgroundColor,
}
exportToCanvas({
elements: exportedElements,
appState,
files,
exportPadding, exportPadding,
maxWidthOrHeight: maxWidth,
}) })
.then((canvas) => { .then((canvas) => {
setRenderError(null); setRenderError(null);
@@ -121,7 +116,14 @@ const ImageExportModal = ({
console.error(error); console.error(error);
setRenderError(error); setRenderError(error);
}); });
}, [appState, files, exportedElements, exportPadding]); }, [
appState,
files,
exportedElements,
exportBackground,
exportPadding,
viewBackgroundColor,
]);
return ( return (
<div className="ExportDialog"> <div className="ExportDialog">
+4 -3
View File
@@ -364,9 +364,10 @@ const LayerUI = ({
{appState.isLoading && <LoadingMessage delay={250} />} {appState.isLoading && <LoadingMessage delay={250} />}
{appState.errorMessage && ( {appState.errorMessage && (
<ErrorDialog onClose={() => setAppState({ errorMessage: null })}> <ErrorDialog
{appState.errorMessage} message={appState.errorMessage}
</ErrorDialog> onClose={() => setAppState({ errorMessage: null })}
/>
)} )}
{appState.openDialog === "help" && ( {appState.openDialog === "help" && (
<HelpDialog <HelpDialog
@@ -48,7 +48,6 @@ export const LibraryMenuHeader: React.FC<{
const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope); const [libraryItemsData] = useAtom(libraryItemsAtom, jotaiScope);
const [isLibraryMenuOpen, setIsLibraryMenuOpen] = useAtom( const [isLibraryMenuOpen, setIsLibraryMenuOpen] = useAtom(
isLibraryMenuOpenAtom, isLibraryMenuOpenAtom,
jotaiScope,
); );
const renderRemoveLibAlert = useCallback(() => { const renderRemoveLibAlert = useCallback(() => {
const content = selectedItems.length const content = selectedItems.length
+1 -9
View File
@@ -12,7 +12,6 @@ import { MIME_TYPES } from "../constants";
import Spinner from "./Spinner"; import Spinner from "./Spinner";
import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton"; import LibraryMenuBrowseButton from "./LibraryMenuBrowseButton";
import clsx from "clsx"; import clsx from "clsx";
import { duplicateElements } from "../element/newElement";
const CELLS_PER_ROW = 4; const CELLS_PER_ROW = 4;
@@ -97,14 +96,7 @@ const LibraryMenuItems = ({
} else { } else {
targetElements = libraryItems.filter((item) => item.id === id); targetElements = libraryItems.filter((item) => item.id === id);
} }
return targetElements.map((item) => { return targetElements;
return {
...item,
// duplicate each library item before inserting on canvas to confine
// ids and bindings to each library item. See #6465
elements: duplicateElements(item.elements, { randomizeSeed: true }),
};
});
}; };
const createLibraryItemCompo = (params: { const createLibraryItemCompo = (params: {
+5 -5
View File
@@ -2,7 +2,7 @@ import clsx from "clsx";
import oc from "open-color"; import oc from "open-color";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useDevice } from "../components/App"; import { useDevice } from "../components/App";
import { exportToSvg } from "../packages/utils"; import { exportToSvg } from "../scene/export";
import { LibraryItem } from "../types"; import { LibraryItem } from "../types";
import "./LibraryUnit.scss"; import "./LibraryUnit.scss";
import { CheckboxItem } from "./CheckboxItem"; import { CheckboxItem } from "./CheckboxItem";
@@ -36,14 +36,14 @@ export const LibraryUnit = ({
if (!elements) { if (!elements) {
return; return;
} }
const svg = await exportToSvg({ const svg = await exportToSvg(
elements, elements,
appState: { {
exportBackground: false, exportBackground: false,
viewBackgroundColor: oc.white, viewBackgroundColor: oc.white,
}, },
files: null, null,
}); );
svg.querySelector(".style-fonts")?.remove(); svg.querySelector(".style-fonts")?.remove();
node.innerHTML = svg.outerHTML; node.innerHTML = svg.outerHTML;
})(); })();
-1
View File
@@ -3,6 +3,5 @@
position: absolute; position: absolute;
z-index: 10; z-index: 10;
padding: 5px 0 5px; padding: 5px 0 5px;
outline: none;
} }
} }
+25 -65
View File
@@ -29,21 +29,13 @@ export const Popover = ({
}: Props) => { }: Props) => {
const popoverRef = useRef<HTMLDivElement>(null); const popoverRef = useRef<HTMLDivElement>(null);
useEffect(() => { const container = popoverRef.current;
const container = popoverRef.current;
useEffect(() => {
if (!container) { if (!container) {
return; return;
} }
// focus popover only if the caller didn't focus on something else nested
// within the popover, which should take precedence. Fixes cases
// like color picker listening to keydown events on containers nested
// in the popover.
if (!container.contains(document.activeElement)) {
container.focus();
}
const handleKeyDown = (event: KeyboardEvent) => { const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === KEYS.TAB) { if (event.key === KEYS.TAB) {
const focusableElements = queryFocusableElements(container); const focusableElements = queryFocusableElements(container);
@@ -52,23 +44,15 @@ export const Popover = ({
(element) => element === activeElement, (element) => element === activeElement,
); );
if (activeElement === container) { if (currentIndex === 0 && event.shiftKey) {
if (event.shiftKey) { focusableElements[focusableElements.length - 1].focus();
focusableElements[focusableElements.length - 1]?.focus();
} else {
focusableElements[0].focus();
}
event.preventDefault();
event.stopImmediatePropagation();
} else if (currentIndex === 0 && event.shiftKey) {
focusableElements[focusableElements.length - 1]?.focus();
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
} else if ( } else if (
currentIndex === focusableElements.length - 1 && currentIndex === focusableElements.length - 1 &&
!event.shiftKey !event.shiftKey
) { ) {
focusableElements[0]?.focus(); focusableElements[0].focus();
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
} }
@@ -78,59 +62,35 @@ export const Popover = ({
container.addEventListener("keydown", handleKeyDown); container.addEventListener("keydown", handleKeyDown);
return () => container.removeEventListener("keydown", handleKeyDown); return () => container.removeEventListener("keydown", handleKeyDown);
}, []); }, [container]);
const lastInitializedPosRef = useRef<{ top: number; left: number } | null>(
null,
);
// ensure the popover doesn't overflow the viewport // ensure the popover doesn't overflow the viewport
useLayoutEffect(() => { useLayoutEffect(() => {
if (fitInViewport && popoverRef.current && top != null && left != null) { if (fitInViewport && popoverRef.current) {
const container = popoverRef.current; const element = popoverRef.current;
const { width, height } = container.getBoundingClientRect(); const { x, y, width, height } = element.getBoundingClientRect();
// hack for StrictMode so this effect only runs once for //Position correctly when clicked on rightmost part or the bottom part of viewport
// the same top/left position, otherwise if (x + width - offsetLeft > viewportWidth) {
// we'd potentically reposition twice (once for viewport overflow) element.style.left = `${viewportWidth - width - 10}px`;
// and once for top/left position afterwards
if (
lastInitializedPosRef.current?.top === top &&
lastInitializedPosRef.current?.left === left
) {
return;
} }
lastInitializedPosRef.current = { top, left }; if (y + height - offsetTop > viewportHeight) {
element.style.top = `${viewportHeight - height}px`;
if (width >= viewportWidth) {
container.style.width = `${viewportWidth}px`;
container.style.left = "0px";
container.style.overflowX = "scroll";
} else if (left + width - offsetLeft > viewportWidth) {
container.style.left = `${viewportWidth - width - 10}px`;
} else {
container.style.left = `${left}px`;
} }
//Resize to fit viewport on smaller screens
if (height >= viewportHeight) { if (height >= viewportHeight) {
container.style.height = `${viewportHeight - 20}px`; element.style.height = `${viewportHeight - 20}px`;
container.style.top = "10px"; element.style.top = "10px";
container.style.overflowY = "scroll"; element.style.overflowY = "scroll";
} else if (top + height - offsetTop > viewportHeight) { }
container.style.top = `${viewportHeight - height}px`; if (width >= viewportWidth) {
} else { element.style.width = `${viewportWidth}px`;
container.style.top = `${top}px`; element.style.left = "0px";
element.style.overflowX = "scroll";
} }
} }
}, [ }, [fitInViewport, viewportWidth, viewportHeight, offsetLeft, offsetTop]);
top,
left,
fitInViewport,
viewportWidth,
viewportHeight,
offsetLeft,
offsetTop,
]);
useEffect(() => { useEffect(() => {
if (onCloseRequest) { if (onCloseRequest) {
@@ -145,7 +105,7 @@ export const Popover = ({
}, [onCloseRequest]); }, [onCloseRequest]);
return ( return (
<div className="popover" ref={popoverRef} tabIndex={-1}> <div className="popover" style={{ top, left }} ref={popoverRef}>
{children} {children}
</div> </div>
); );
-76
View File
@@ -93,80 +93,4 @@
display: block; display: block;
} }
} }
.single-library-item {
position: relative;
&-status {
position: absolute;
top: 0.3rem;
left: 0.3rem;
font-size: 0.7rem;
color: $oc-red-7;
background: rgba(255, 255, 255, 0.9);
padding: 0.1rem 0.2rem;
border-radius: 0.2rem;
}
&__svg {
background-color: $oc-white;
padding: 0.3rem;
width: 7.5rem;
height: 7.5rem;
border: 1px solid var(--button-gray-2);
svg {
width: 100%;
height: 100%;
}
}
.ToolIcon__icon {
background-color: $oc-white;
width: auto;
height: auto;
margin: 0 0.5rem;
}
.ToolIcon,
.ToolIcon_type_button:hover {
background-color: white;
}
.required,
.error {
color: $oc-red-8;
font-weight: bold;
font-size: 1rem;
margin: 0.2rem;
}
.error {
font-weight: 500;
margin: 0;
padding: 0.3em 0;
}
&--remove {
position: absolute;
top: 0.2rem;
right: 1rem;
.ToolIcon__icon {
margin: 0;
}
.ToolIcon__icon {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-7;
}
&:active {
background-color: $oc-red-8;
}
}
svg {
color: $oc-white;
padding: 0.26rem;
border-radius: 0.3em;
width: 1rem;
height: 1rem;
}
}
}
} }
+5 -99
View File
@@ -1,11 +1,11 @@
import { ReactNode, useCallback, useEffect, useRef, useState } from "react"; import { ReactNode, useCallback, useEffect, useState } from "react";
import OpenColor from "open-color"; import OpenColor from "open-color";
import { Dialog } from "./Dialog"; import { Dialog } from "./Dialog";
import { t } from "../i18n"; import { t } from "../i18n";
import { AppState, LibraryItems, LibraryItem } from "../types"; import { AppState, LibraryItems, LibraryItem } from "../types";
import { exportToCanvas, exportToSvg } from "../packages/utils"; import { exportToCanvas } from "../packages/utils";
import { import {
EXPORT_DATA_TYPES, EXPORT_DATA_TYPES,
EXPORT_SOURCE, EXPORT_SOURCE,
@@ -13,13 +13,12 @@ import {
VERSIONS, VERSIONS,
} from "../constants"; } from "../constants";
import { ExportedLibraryData } from "../data/types"; import { ExportedLibraryData } from "../data/types";
import "./PublishLibrary.scss";
import SingleLibraryItem from "./SingleLibraryItem";
import { canvasToBlob, resizeImageFile } from "../data/blob"; import { canvasToBlob, resizeImageFile } from "../data/blob";
import { chunk } from "../utils"; import { chunk } from "../utils";
import DialogActionButton from "./DialogActionButton"; import DialogActionButton from "./DialogActionButton";
import { CloseIcon } from "./icons";
import { ToolButton } from "./ToolButton";
import "./PublishLibrary.scss";
interface PublishLibraryDataParams { interface PublishLibraryDataParams {
authorName: string; authorName: string;
@@ -127,99 +126,6 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
); );
}; };
const SingleLibraryItem = ({
libItem,
appState,
index,
onChange,
onRemove,
}: {
libItem: LibraryItem;
appState: AppState;
index: number;
onChange: (val: string, index: number) => void;
onRemove: (id: string) => void;
}) => {
const svgRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
const node = svgRef.current;
if (!node) {
return;
}
(async () => {
const svg = await exportToSvg({
elements: libItem.elements,
appState: {
...appState,
viewBackgroundColor: OpenColor.white,
exportBackground: true,
},
files: null,
});
node.innerHTML = svg.outerHTML;
})();
}, [libItem.elements, appState]);
return (
<div className="single-library-item">
{libItem.status === "published" && (
<span className="single-library-item-status">
{t("labels.statusPublished")}
</span>
)}
<div ref={svgRef} className="single-library-item__svg" />
<ToolButton
aria-label={t("buttons.remove")}
type="button"
icon={CloseIcon}
className="single-library-item--remove"
onClick={onRemove.bind(null, libItem.id)}
title={t("buttons.remove")}
/>
<div
style={{
display: "flex",
margin: "0.8rem 0",
width: "100%",
fontSize: "14px",
fontWeight: 500,
flexDirection: "column",
}}
>
<label
style={{
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
}}
>
<div style={{ padding: "0.5em 0" }}>
<span style={{ fontWeight: 500, color: OpenColor.gray[6] }}>
{t("publishDialog.itemName")}
</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<input
type="text"
ref={inputRef}
style={{ width: "80%", padding: "0.2rem" }}
defaultValue={libItem.name}
placeholder="Item name"
onChange={(event) => {
onChange(event.target.value, index);
}}
/>
</label>
<span className="error">{libItem.error}</span>
</div>
</div>
);
};
const PublishLibrary = ({ const PublishLibrary = ({
onClose, onClose,
libraryItems, libraryItems,
+79
View File
@@ -0,0 +1,79 @@
@import "../css/variables.module";
.excalidraw {
.single-library-item {
position: relative;
&-status {
position: absolute;
top: 0.3rem;
left: 0.3rem;
font-size: 0.7rem;
color: $oc-red-7;
background: rgba(255, 255, 255, 0.9);
padding: 0.1rem 0.2rem;
border-radius: 0.2rem;
}
&__svg {
background-color: $oc-white;
padding: 0.3rem;
width: 7.5rem;
height: 7.5rem;
border: 1px solid var(--button-gray-2);
svg {
width: 100%;
height: 100%;
}
}
.ToolIcon__icon {
background-color: $oc-white;
width: auto;
height: auto;
margin: 0 0.5rem;
}
.ToolIcon,
.ToolIcon_type_button:hover {
background-color: white;
}
.required,
.error {
color: $oc-red-8;
font-weight: bold;
font-size: 1rem;
margin: 0.2rem;
}
.error {
font-weight: 500;
margin: 0;
padding: 0.3em 0;
}
&--remove {
position: absolute;
top: 0.2rem;
right: 1rem;
.ToolIcon__icon {
margin: 0;
}
.ToolIcon__icon {
background-color: $oc-red-6;
&:hover {
background-color: $oc-red-7;
}
&:active {
background-color: $oc-red-8;
}
}
svg {
color: $oc-white;
padding: 0.26rem;
border-radius: 0.3em;
width: 1rem;
height: 1rem;
}
}
}
}
+104
View File
@@ -0,0 +1,104 @@
import oc from "open-color";
import { useEffect, useRef } from "react";
import { t } from "../i18n";
import { exportToSvg } from "../packages/utils";
import { AppState, LibraryItem } from "../types";
import { CloseIcon } from "./icons";
import "./SingleLibraryItem.scss";
import { ToolButton } from "./ToolButton";
const SingleLibraryItem = ({
libItem,
appState,
index,
onChange,
onRemove,
}: {
libItem: LibraryItem;
appState: AppState;
index: number;
onChange: (val: string, index: number) => void;
onRemove: (id: string) => void;
}) => {
const svgRef = useRef<HTMLDivElement | null>(null);
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
const node = svgRef.current;
if (!node) {
return;
}
(async () => {
const svg = await exportToSvg({
elements: libItem.elements,
appState: {
...appState,
viewBackgroundColor: oc.white,
exportBackground: true,
},
files: null,
});
node.innerHTML = svg.outerHTML;
})();
}, [libItem.elements, appState]);
return (
<div className="single-library-item">
{libItem.status === "published" && (
<span className="single-library-item-status">
{t("labels.statusPublished")}
</span>
)}
<div ref={svgRef} className="single-library-item__svg" />
<ToolButton
aria-label={t("buttons.remove")}
type="button"
icon={CloseIcon}
className="single-library-item--remove"
onClick={onRemove.bind(null, libItem.id)}
title={t("buttons.remove")}
/>
<div
style={{
display: "flex",
margin: "0.8rem 0",
width: "100%",
fontSize: "14px",
fontWeight: 500,
flexDirection: "column",
}}
>
<label
style={{
display: "flex",
justifyContent: "space-between",
flexDirection: "column",
}}
>
<div style={{ padding: "0.5em 0" }}>
<span style={{ fontWeight: 500, color: oc.gray[6] }}>
{t("publishDialog.itemName")}
</span>
<span aria-hidden="true" className="required">
*
</span>
</div>
<input
type="text"
ref={inputRef}
style={{ width: "80%", padding: "0.2rem" }}
defaultValue={libItem.name}
placeholder="Item name"
onChange={(event) => {
onChange(event.target.value, index);
}}
/>
</label>
<span className="error">{libItem.error}</span>
</div>
</div>
);
};
export default SingleLibraryItem;
-3
View File
@@ -2,9 +2,6 @@
// container in body where the actual tooltip is appended to // container in body where the actual tooltip is appended to
.excalidraw-tooltip { .excalidraw-tooltip {
--ui-font: Assistant, system-ui, BlinkMacSystemFont, -apple-system, Segoe UI,
Roboto, Helvetica, Arial, sans-serif;
font-family: var(--ui-font);
position: fixed; position: fixed;
z-index: 1000; z-index: 1000;
@@ -1,63 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Test <App/> should show error modal when using brave and measureText API is not working 1`] = `
<div
data-testid="brave-measure-text-error"
>
<p>
Looks like you are using Brave browser with the
 
<span
style="font-weight: 600;"
>
Aggressively Block Fingerprinting
</span>
setting enabled
.
<br />
<br />
This could result in breaking the
<span
style="font-weight: 600;"
>
Text Elements
</span>
in your drawings
.
</p>
<p>
We strongly recommend disabling this setting. You can follow
<a
href="http://docs.excalidraw.com/docs/@excalidraw/excalidraw/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser"
>
these steps
</a>
on how to do so
.
</p>
<p>
If disabling this setting doesn't fix the display of text elements, please open an
<a
href="https://github.com/excalidraw/excalidraw/issues/new"
>
issue
</a>
on our GitHub, or write us on
<a
href="https://discord.gg/UexuTaE"
>
Discord
</a>
.
</p>
</div>
`;
-7
View File
@@ -1008,13 +1008,6 @@ export const UngroupIcon = React.memo(({ theme }: { theme: Theme }) =>
), ),
); );
export const FillZigZagIcon = createIcon(
<g strokeWidth={1.25}>
<path d="M5.879 2.625h8.242a3.27 3.27 0 0 1 3.254 3.254v8.242a3.27 3.27 0 0 1-3.254 3.254H5.88a3.27 3.27 0 0 1-3.254-3.254V5.88A3.27 3.27 0 0 1 5.88 2.626l-.001-.001ZM4.518 16.118l7.608-12.83m.198 13.934 5.051-9.897M2.778 9.675l9.348-6.387m-7.608 12.83 12.857-8.793" />
</g>,
modifiedTablerIconProps,
);
export const FillHachureIcon = createIcon( export const FillHachureIcon = createIcon(
<> <>
<path <path
+23 -16
View File
@@ -1,5 +1,5 @@
import { getShortcutFromShortcutName } from "../../actions/shortcuts"; import { getShortcutFromShortcutName } from "../../actions/shortcuts";
import { useI18n } from "../../i18n"; import { t } from "../../i18n";
import { import {
useExcalidrawAppState, useExcalidrawAppState,
useExcalidrawSetAppState, useExcalidrawSetAppState,
@@ -31,10 +31,11 @@ import "./DefaultItems.scss";
import clsx from "clsx"; import clsx from "clsx";
import { useSetAtom } from "jotai"; import { useSetAtom } from "jotai";
import { activeConfirmDialogAtom } from "../ActiveConfirmDialog"; import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
import { jotaiScope } from "../../jotai";
export const LoadScene = () => { export const LoadScene = () => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
if (!actionManager.isActionEnabled(actionLoadScene)) { if (!actionManager.isActionEnabled(actionLoadScene)) {
@@ -56,7 +57,9 @@ export const LoadScene = () => {
LoadScene.displayName = "LoadScene"; LoadScene.displayName = "LoadScene";
export const SaveToActiveFile = () => { export const SaveToActiveFile = () => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
if (!actionManager.isActionEnabled(actionSaveToActiveFile)) { if (!actionManager.isActionEnabled(actionSaveToActiveFile)) {
@@ -77,7 +80,9 @@ SaveToActiveFile.displayName = "SaveToActiveFile";
export const SaveAsImage = () => { export const SaveAsImage = () => {
const setAppState = useExcalidrawSetAppState(); const setAppState = useExcalidrawSetAppState();
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
return ( return (
<DropdownMenuItem <DropdownMenuItem
icon={ExportImageIcon} icon={ExportImageIcon}
@@ -93,7 +98,9 @@ export const SaveAsImage = () => {
SaveAsImage.displayName = "SaveAsImage"; SaveAsImage.displayName = "SaveAsImage";
export const Help = () => { export const Help = () => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
@@ -112,12 +119,10 @@ export const Help = () => {
Help.displayName = "Help"; Help.displayName = "Help";
export const ClearCanvas = () => { export const ClearCanvas = () => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const setActiveConfirmDialog = useSetAtom( const appState = useExcalidrawAppState();
activeConfirmDialogAtom, const setActiveConfirmDialog = useSetAtom(activeConfirmDialogAtom);
jotaiScope,
);
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
if (!actionManager.isActionEnabled(actionClearCanvas)) { if (!actionManager.isActionEnabled(actionClearCanvas)) {
@@ -138,7 +143,6 @@ export const ClearCanvas = () => {
ClearCanvas.displayName = "ClearCanvas"; ClearCanvas.displayName = "ClearCanvas";
export const ToggleTheme = () => { export const ToggleTheme = () => {
const { t } = useI18n();
const appState = useExcalidrawAppState(); const appState = useExcalidrawAppState();
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
@@ -171,7 +175,6 @@ export const ToggleTheme = () => {
ToggleTheme.displayName = "ToggleTheme"; ToggleTheme.displayName = "ToggleTheme";
export const ChangeCanvasBackground = () => { export const ChangeCanvasBackground = () => {
const { t } = useI18n();
const appState = useExcalidrawAppState(); const appState = useExcalidrawAppState();
const actionManager = useExcalidrawActionManager(); const actionManager = useExcalidrawActionManager();
@@ -192,7 +195,9 @@ export const ChangeCanvasBackground = () => {
ChangeCanvasBackground.displayName = "ChangeCanvasBackground"; ChangeCanvasBackground.displayName = "ChangeCanvasBackground";
export const Export = () => { export const Export = () => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
const setAppState = useExcalidrawSetAppState(); const setAppState = useExcalidrawSetAppState();
return ( return (
<DropdownMenuItem <DropdownMenuItem
@@ -243,7 +248,9 @@ export const LiveCollaborationTrigger = ({
onSelect: () => void; onSelect: () => void;
isCollaborating: boolean; isCollaborating: boolean;
}) => { }) => {
const { t } = useI18n(); // FIXME Hack until we tie "t" to lang state
// eslint-disable-next-line
const appState = useExcalidrawAppState();
return ( return (
<DropdownMenuItem <DropdownMenuItem
data-testid="collab-button" data-testid="collab-button"
@@ -1,6 +1,6 @@
import { actionLoadScene, actionShortcuts } from "../../actions"; import { actionLoadScene, actionShortcuts } from "../../actions";
import { getShortcutFromShortcutName } from "../../actions/shortcuts"; import { getShortcutFromShortcutName } from "../../actions/shortcuts";
import { t, useI18n } from "../../i18n"; import { t } from "../../i18n";
import { import {
useDevice, useDevice,
useExcalidrawActionManager, useExcalidrawActionManager,
@@ -172,7 +172,10 @@ const MenuItemLiveCollaborationTrigger = ({
}: { }: {
onSelect: () => any; onSelect: () => any;
}) => { }) => {
const { t } = useI18n(); // FIXME when we tie t() to lang state
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const appState = useExcalidrawAppState();
return ( return (
<WelcomeScreenMenuItem shortcut={null} onSelect={onSelect} icon={usersIcon}> <WelcomeScreenMenuItem shortcut={null} onSelect={onSelect} icon={usersIcon}>
{t("labels.liveCollaboration")} {t("labels.liveCollaboration")}
+17 -44
View File
@@ -1,7 +1,6 @@
import cssVariables from "./css/variables.module.scss"; import cssVariables from "./css/variables.module.scss";
import { AppProps } from "./types"; import { AppProps } from "./types";
import { ExcalidrawElement, FontFamilyValues } from "./element/types"; import { FontFamilyValues } from "./element/types";
import oc from "open-color";
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform); export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
export const isWindows = /^Win/.test(navigator.platform); export const isWindows = /^Win/.test(navigator.platform);
@@ -10,12 +9,6 @@ export const isFirefox =
"netscape" in window && "netscape" in window &&
navigator.userAgent.indexOf("rv:") > 1 && navigator.userAgent.indexOf("rv:") > 1 &&
navigator.userAgent.indexOf("Gecko") > 1; navigator.userAgent.indexOf("Gecko") > 1;
export const isChrome = navigator.userAgent.indexOf("Chrome") !== -1;
export const isSafari =
!isChrome && navigator.userAgent.indexOf("Safari") !== -1;
// keeping function so it can be mocked in test
export const isBrave = () =>
(navigator as any).brave?.isBrave?.name === "isBrave";
export const APP_NAME = "Excalidraw"; export const APP_NAME = "Excalidraw";
@@ -105,30 +98,20 @@ export const CANVAS_ONLY_ACTIONS = ["selectAll"];
export const GRID_SIZE = 20; // TODO make it configurable? export const GRID_SIZE = 20; // TODO make it configurable?
export const IMAGE_MIME_TYPES = { export const MIME_TYPES = {
excalidraw: "application/vnd.excalidraw+json",
excalidrawlib: "application/vnd.excalidrawlib+json",
json: "application/json",
svg: "image/svg+xml", svg: "image/svg+xml",
"excalidraw.svg": "image/svg+xml",
png: "image/png", png: "image/png",
"excalidraw.png": "image/png",
jpg: "image/jpeg", jpg: "image/jpeg",
gif: "image/gif", gif: "image/gif",
webp: "image/webp", webp: "image/webp",
bmp: "image/bmp", bmp: "image/bmp",
ico: "image/x-icon", ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
export const MIME_TYPES = {
json: "application/json",
// excalidraw data
excalidraw: "application/vnd.excalidraw+json",
excalidrawlib: "application/vnd.excalidrawlib+json",
// image-encoded excalidraw data
"excalidraw.svg": "image/svg+xml",
"excalidraw.png": "image/png",
// binary
binary: "application/octet-stream", binary: "application/octet-stream",
// image
...IMAGE_MIME_TYPES,
} as const; } as const;
export const EXPORT_DATA_TYPES = { export const EXPORT_DATA_TYPES = {
@@ -199,6 +182,16 @@ export const DEFAULT_EXPORT_PADDING = 10; // px
export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT = 1440; export const DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT = 1440;
export const ALLOWED_IMAGE_MIME_TYPES = [
MIME_TYPES.png,
MIME_TYPES.jpg,
MIME_TYPES.svg,
MIME_TYPES.gif,
MIME_TYPES.webp,
MIME_TYPES.bmp,
MIME_TYPES.ico,
] as const;
export const MAX_ALLOWED_FILE_BYTES = 2 * 1024 * 1024; export const MAX_ALLOWED_FILE_BYTES = 2 * 1024 * 1024;
export const SVG_NS = "http://www.w3.org/2000/svg"; export const SVG_NS = "http://www.w3.org/2000/svg";
@@ -255,23 +248,3 @@ export const ROUNDNESS = {
/** key containt id of precedeing elemnt id we use in reconciliation during /** key containt id of precedeing elemnt id we use in reconciliation during
* collaboration */ * collaboration */
export const PRECEDING_ELEMENT_KEY = "__precedingElement__"; export const PRECEDING_ELEMENT_KEY = "__precedingElement__";
export const DEFAULT_ELEMENT_PROPS: {
strokeColor: ExcalidrawElement["strokeColor"];
backgroundColor: ExcalidrawElement["backgroundColor"];
fillStyle: ExcalidrawElement["fillStyle"];
strokeWidth: ExcalidrawElement["strokeWidth"];
strokeStyle: ExcalidrawElement["strokeStyle"];
roughness: ExcalidrawElement["roughness"];
opacity: ExcalidrawElement["opacity"];
locked: ExcalidrawElement["locked"];
} = {
strokeColor: oc.black,
backgroundColor: "transparent",
fillStyle: "hachure",
strokeWidth: 1,
strokeStyle: "solid",
roughness: 1,
opacity: 100,
locked: false,
};
+2 -8
View File
@@ -155,9 +155,6 @@
margin: 1px; margin: 1px;
} }
.welcome-screen-menu-item:focus-visible,
.dropdown-menu-item:focus-visible,
button:focus-visible,
.buttonList label:focus-within, .buttonList label:focus-within,
input:focus-visible { input:focus-visible {
outline: transparent; outline: transparent;
@@ -354,7 +351,6 @@
border-radius: var(--space-factor); border-radius: var(--space-factor);
border: 1px solid var(--button-gray-2); border: 1px solid var(--button-gray-2);
font-size: 0.8rem; font-size: 0.8rem;
font-family: inherit;
outline: none; outline: none;
appearance: none; appearance: none;
background-image: var(--dropdown-icon); background-image: var(--dropdown-icon);
@@ -414,7 +410,6 @@
bottom: 30px; bottom: 30px;
transform: translateX(-50%); transform: translateX(-50%);
pointer-events: all; pointer-events: all;
font-family: inherit;
&:hover { &:hover {
background-color: var(--button-hover-bg); background-color: var(--button-hover-bg);
@@ -535,7 +530,6 @@
// (doesn't work in Firefox) // (doesn't work in Firefox)
::-webkit-scrollbar { ::-webkit-scrollbar {
width: 3px; width: 3px;
height: 3px;
} }
::-webkit-scrollbar-thumb { ::-webkit-scrollbar-thumb {
@@ -573,8 +567,8 @@
} }
.App-toolbar--mobile { .App-toolbar--mobile {
overflow-x: auto; overflow-x: hidden;
max-width: 90vw; max-width: 100vw;
.ToolIcon__keybinding { .ToolIcon__keybinding {
display: none; display: none;
+6 -5
View File
@@ -1,13 +1,12 @@
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { cleanAppStateForExport } from "../appState"; import { cleanAppStateForExport } from "../appState";
import { IMAGE_MIME_TYPES, MIME_TYPES } from "../constants"; import { ALLOWED_IMAGE_MIME_TYPES, MIME_TYPES } from "../constants";
import { clearElementsForExport } from "../element"; import { clearElementsForExport } from "../element";
import { ExcalidrawElement, FileId } from "../element/types"; import { ExcalidrawElement, FileId } from "../element/types";
import { CanvasError } from "../errors"; import { CanvasError } from "../errors";
import { t } from "../i18n"; import { t } from "../i18n";
import { calculateScrollCenter } from "../scene"; import { calculateScrollCenter } from "../scene";
import { AppState, DataURL, LibraryItem } from "../types"; import { AppState, DataURL, LibraryItem } from "../types";
import { ValueOf } from "../utility-types";
import { bytesToHexString } from "../utils"; import { bytesToHexString } from "../utils";
import { FileSystemHandle, nativeFileSystemSupported } from "./filesystem"; import { FileSystemHandle, nativeFileSystemSupported } from "./filesystem";
import { isValidExcalidrawData, isValidLibrary } from "./json"; import { isValidExcalidrawData, isValidLibrary } from "./json";
@@ -117,9 +116,11 @@ export const isImageFileHandle = (handle: FileSystemHandle | null) => {
export const isSupportedImageFile = ( export const isSupportedImageFile = (
blob: Blob | null | undefined, blob: Blob | null | undefined,
): blob is Blob & { type: ValueOf<typeof IMAGE_MIME_TYPES> } => { ): blob is Blob & { type: typeof ALLOWED_IMAGE_MIME_TYPES[number] } => {
const { type } = blob || {}; const { type } = blob || {};
return !!type && (Object.values(IMAGE_MIME_TYPES) as string[]).includes(type); return (
!!type && (ALLOWED_IMAGE_MIME_TYPES as readonly string[]).includes(type)
);
}; };
export const loadSceneOrLibraryFromBlob = async ( export const loadSceneOrLibraryFromBlob = async (
@@ -155,7 +156,7 @@ export const loadSceneOrLibraryFromBlob = async (
}, },
localAppState, localAppState,
localElements, localElements,
{ repairBindings: true, refreshDimensions: false }, { repairBindings: true },
), ),
}; };
} else if (isValidLibrary(data)) { } else if (isValidLibrary(data)) {
+10 -1
View File
@@ -8,7 +8,16 @@ import { EVENT, MIME_TYPES } from "../constants";
import { AbortError } from "../errors"; import { AbortError } from "../errors";
import { debounce } from "../utils"; import { debounce } from "../utils";
type FILE_EXTENSION = Exclude<keyof typeof MIME_TYPES, "binary">; type FILE_EXTENSION =
| "gif"
| "jpg"
| "png"
| "excalidraw.png"
| "svg"
| "excalidraw.svg"
| "json"
| "excalidraw"
| "excalidrawlib";
const INPUT_CHANGE_INTERVAL_MS = 500; const INPUT_CHANGE_INTERVAL_MS = 500;
+1 -3
View File
@@ -89,9 +89,7 @@ export const exportCanvas = async (
return await fileSave(blob, { return await fileSave(blob, {
description: "Export to PNG", description: "Export to PNG",
name, name,
// FIXME reintroduce `excalidraw.png` when most people upgrade away extension: appState.exportEmbedScene ? "excalidraw.png" : "png",
// from 111.0.5563.64 (arm64), see #6349
extension: /* appState.exportEmbedScene ? "excalidraw.png" : */ "png",
fileHandle, fileHandle,
}); });
} else if (type === "clipboard") { } else if (type === "clipboard") {
+6 -43
View File
@@ -31,15 +31,9 @@ import {
import { getDefaultAppState } from "../appState"; import { getDefaultAppState } from "../appState";
import { LinearElementEditor } from "../element/linearElementEditor"; import { LinearElementEditor } from "../element/linearElementEditor";
import { bumpVersion } from "../element/mutateElement"; import { bumpVersion } from "../element/mutateElement";
import { getFontString, getUpdatedTimestamp, updateActiveTool } from "../utils"; import { getUpdatedTimestamp, updateActiveTool } from "../utils";
import { arrayToMap } from "../utils"; import { arrayToMap } from "../utils";
import oc from "open-color"; import oc from "open-color";
import { MarkOptional, Mutable } from "../utility-types";
import {
detectLineHeight,
getDefaultLineHeight,
measureBaseline,
} from "../element/textElement";
type RestoredAppState = Omit< type RestoredAppState = Omit<
AppState, AppState,
@@ -170,40 +164,18 @@ const restoreElement = (
const [fontPx, _fontFamily]: [string, string] = ( const [fontPx, _fontFamily]: [string, string] = (
element as any element as any
).font.split(" "); ).font.split(" ");
fontSize = parseFloat(fontPx); fontSize = parseInt(fontPx, 10);
fontFamily = getFontFamilyByName(_fontFamily); fontFamily = getFontFamilyByName(_fontFamily);
} }
const text = element.text ?? "";
// line-height might not be specified either when creating elements
// programmatically, or when importing old diagrams.
// For the latter we want to detect the original line height which
// will likely differ from our per-font fixed line height we now use,
// to maintain backward compatibility.
const lineHeight =
element.lineHeight ||
(element.height
? // detect line-height from current element height and font-size
detectLineHeight(element)
: // no element height likely means programmatic use, so default
// to a fixed line height
getDefaultLineHeight(element.fontFamily));
const baseline = measureBaseline(
element.text,
getFontString(element),
lineHeight,
);
element = restoreElementWithProperties(element, { element = restoreElementWithProperties(element, {
fontSize, fontSize,
fontFamily, fontFamily,
text, text: element.text ?? "",
baseline: element.baseline,
textAlign: element.textAlign || DEFAULT_TEXT_ALIGN, textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN, verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
containerId: element.containerId ?? null, containerId: element.containerId ?? null,
originalText: element.originalText || text, originalText: element.originalText || element.text,
lineHeight,
baseline,
}); });
if (refreshDimensions) { if (refreshDimensions) {
@@ -369,9 +341,6 @@ export const restoreElements = (
localElements: readonly ExcalidrawElement[] | null | undefined, localElements: readonly ExcalidrawElement[] | null | undefined,
opts?: { refreshDimensions?: boolean; repairBindings?: boolean } | undefined, opts?: { refreshDimensions?: boolean; repairBindings?: boolean } | undefined,
): ExcalidrawElement[] => { ): ExcalidrawElement[] => {
// used to detect duplicate top-level element ids
const existingIds = new Set<string>();
const localElementsMap = localElements ? arrayToMap(localElements) : null; const localElementsMap = localElements ? arrayToMap(localElements) : null;
const restoredElements = (elements || []).reduce((elements, element) => { const restoredElements = (elements || []).reduce((elements, element) => {
// filtering out selection, which is legacy, no longer kept in elements, // filtering out selection, which is legacy, no longer kept in elements,
@@ -386,10 +355,6 @@ export const restoreElements = (
if (localElement && localElement.version > migratedElement.version) { if (localElement && localElement.version > migratedElement.version) {
migratedElement = bumpVersion(migratedElement, localElement.version); migratedElement = bumpVersion(migratedElement, localElement.version);
} }
if (existingIds.has(migratedElement.id)) {
migratedElement = { ...migratedElement, id: randomId() };
}
existingIds.add(migratedElement.id);
elements.push(migratedElement); elements.push(migratedElement);
} }
} }
@@ -514,9 +479,7 @@ export const restoreAppState = (
? { ? {
value: appState.zoom as NormalizedZoomValue, value: appState.zoom as NormalizedZoomValue,
} }
: appState.zoom?.value : appState.zoom || defaultAppState.zoom,
? appState.zoom
: defaultAppState.zoom,
// when sidebar docked and user left it open in last session, // when sidebar docked and user left it open in last session,
// keep it open. If not docked, keep it closed irrespective of last state. // keep it open. If not docked, keep it closed irrespective of last state.
openSidebar: openSidebar:
-1
View File
@@ -23,7 +23,6 @@ import {
import { rescalePoints } from "../points"; import { rescalePoints } from "../points";
import { getBoundTextElement, getContainerElement } from "./textElement"; import { getBoundTextElement, getContainerElement } from "./textElement";
import { LinearElementEditor } from "./linearElementEditor"; import { LinearElementEditor } from "./linearElementEditor";
import { Mutable } from "../utility-types";
// x and y position of top left corner, x and y position of bottom right corner // x and y position of top left corner, x and y position of bottom right corner
export type Bounds = readonly [number, number, number, number]; export type Bounds = readonly [number, number, number, number];
+1 -7
View File
@@ -38,7 +38,6 @@ import { isTextElement } from ".";
import { isTransparent } from "../utils"; import { isTransparent } from "../utils";
import { shouldShowBoundingBox } from "./transformHandles"; import { shouldShowBoundingBox } from "./transformHandles";
import { getBoundTextElement } from "./textElement"; import { getBoundTextElement } from "./textElement";
import { Mutable } from "../utility-types";
const isElementDraggableFromInside = ( const isElementDraggableFromInside = (
element: NonDeletedExcalidrawElement, element: NonDeletedExcalidrawElement,
@@ -786,12 +785,7 @@ export const findFocusPointForEllipse = (
orientation * py * Math.sqrt(Math.max(0, squares - a ** 2 * b ** 2))) / orientation * py * Math.sqrt(Math.max(0, squares - a ** 2 * b ** 2))) /
squares; squares;
let n = (-m * px - 1) / py; const n = (-m * px - 1) / py;
if (n === 0) {
// if zero {-0, 0}, fall back to a same-sign value in the similar range
n = (Object.is(n, -0) ? -1 : 1) * 0.01;
}
const x = -(a ** 2 * m) / (n ** 2 * b ** 2 + m ** 2 * a ** 2); const x = -(a ** 2 * m) / (n ** 2 * b ** 2 + m ** 2 * a ** 2);
return GA.point(x, (-m * x - 1) / n); return GA.point(x, (-m * x - 1) / n);
+1 -16
View File
@@ -40,12 +40,7 @@ import { isBindingElement } from "./typeChecks";
import { shouldRotateWithDiscreteAngle } from "../keys"; import { shouldRotateWithDiscreteAngle } from "../keys";
import { getBoundTextElement, handleBindTextResize } from "./textElement"; import { getBoundTextElement, handleBindTextResize } from "./textElement";
import { getShapeForElement } from "../renderer/renderElement"; import { getShapeForElement } from "../renderer/renderElement";
import { import { DRAGGING_THRESHOLD } from "../constants";
BOUND_TEXT_PADDING,
DRAGGING_THRESHOLD,
VERTICAL_ALIGN,
} from "../constants";
import { Mutable } from "../utility-types";
const editorMidPointsCache: { const editorMidPointsCache: {
version: number | null; version: number | null;
@@ -1308,16 +1303,6 @@ export class LinearElementEditor {
} }
x = midSegmentMidpoint[0] - boundTextElement.width / 2; x = midSegmentMidpoint[0] - boundTextElement.width / 2;
y = midSegmentMidpoint[1] - boundTextElement.height / 2; y = midSegmentMidpoint[1] - boundTextElement.height / 2;
if (element.points.length === 2) {
if (boundTextElement.verticalAlign === VERTICAL_ALIGN.TOP) {
y =
midSegmentMidpoint[1] -
boundTextElement.height -
BOUND_TEXT_PADDING * 2;
} else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
y = midSegmentMidpoint[1] + BOUND_TEXT_PADDING * 2;
}
}
} }
return { x, y }; return { x, y };
}; };
-1
View File
@@ -5,7 +5,6 @@ import { getSizeFromPoints } from "../points";
import { randomInteger } from "../random"; import { randomInteger } from "../random";
import { Point } from "../types"; import { Point } from "../types";
import { getUpdatedTimestamp } from "../utils"; import { getUpdatedTimestamp } from "../utils";
import { Mutable } from "../utility-types";
type ElementUpdate<TElement extends ExcalidrawElement> = Omit< type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>, Partial<TElement>,
+64 -339
View File
@@ -1,9 +1,8 @@
import { duplicateElement, duplicateElements } from "./newElement"; import { duplicateElement } from "./newElement";
import { mutateElement } from "./mutateElement"; import { mutateElement } from "./mutateElement";
import { API } from "../tests/helpers/api"; import { API } from "../tests/helpers/api";
import { FONT_FAMILY, ROUNDNESS } from "../constants"; import { FONT_FAMILY, ROUNDNESS } from "../constants";
import { isPrimitive } from "../utils"; import { isPrimitive } from "../utils";
import { ExcalidrawLinearElement } from "./types";
const assertCloneObjects = (source: any, clone: any) => { const assertCloneObjects = (source: any, clone: any) => {
for (const key in clone) { for (const key in clone) {
@@ -16,353 +15,79 @@ const assertCloneObjects = (source: any, clone: any) => {
} }
}; };
describe("duplicating single elements", () => { it("clones arrow element", () => {
it("clones arrow element", () => { const element = API.createElement({
const element = API.createElement({ type: "arrow",
type: "arrow", x: 0,
x: 0, y: 0,
y: 0, strokeColor: "#000000",
strokeColor: "#000000", backgroundColor: "transparent",
backgroundColor: "transparent", fillStyle: "hachure",
fillStyle: "hachure", strokeWidth: 1,
strokeWidth: 1, strokeStyle: "solid",
strokeStyle: "solid", roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS },
roundness: { type: ROUNDNESS.PROPORTIONAL_RADIUS }, roughness: 1,
roughness: 1, opacity: 100,
opacity: 100,
});
// @ts-ignore
element.__proto__ = { hello: "world" };
mutateElement(element, {
points: [
[1, 2],
[3, 4],
],
});
const copy = duplicateElement(null, new Map(), element);
assertCloneObjects(element, copy);
// assert we clone the object's prototype
// @ts-ignore
expect(copy.__proto__).toEqual({ hello: "world" });
expect(copy.hasOwnProperty("hello")).toBe(false);
expect(copy.points).not.toBe(element.points);
expect(copy).not.toHaveProperty("shape");
expect(copy.id).not.toBe(element.id);
expect(typeof copy.id).toBe("string");
expect(copy.seed).not.toBe(element.seed);
expect(typeof copy.seed).toBe("number");
expect(copy).toEqual({
...element,
id: copy.id,
seed: copy.seed,
});
}); });
it("clones text element", () => { // @ts-ignore
const element = API.createElement({ element.__proto__ = { hello: "world" };
type: "text",
x: 0,
y: 0,
strokeColor: "#000000",
backgroundColor: "transparent",
fillStyle: "hachure",
strokeWidth: 1,
strokeStyle: "solid",
roundness: null,
roughness: 1,
opacity: 100,
text: "hello",
fontSize: 20,
fontFamily: FONT_FAMILY.Virgil,
textAlign: "left",
verticalAlign: "top",
});
const copy = duplicateElement(null, new Map(), element); mutateElement(element, {
points: [
[1, 2],
[3, 4],
],
});
assertCloneObjects(element, copy); const copy = duplicateElement(null, new Map(), element);
expect(copy).not.toHaveProperty("points"); assertCloneObjects(element, copy);
expect(copy).not.toHaveProperty("shape");
expect(copy.id).not.toBe(element.id); // @ts-ignore
expect(typeof copy.id).toBe("string"); expect(copy.__proto__).toEqual({ hello: "world" });
expect(typeof copy.seed).toBe("number"); expect(copy.hasOwnProperty("hello")).toBe(false);
expect(copy.points).not.toBe(element.points);
expect(copy).not.toHaveProperty("shape");
expect(copy.id).not.toBe(element.id);
expect(typeof copy.id).toBe("string");
expect(copy.seed).not.toBe(element.seed);
expect(typeof copy.seed).toBe("number");
expect(copy).toEqual({
...element,
id: copy.id,
seed: copy.seed,
}); });
}); });
describe("duplicating multiple elements", () => { it("clones text element", () => {
it("duplicateElements should clone bindings", () => { const element = API.createElement({
const rectangle1 = API.createElement({ type: "text",
type: "rectangle", x: 0,
id: "rectangle1", y: 0,
boundElements: [ strokeColor: "#000000",
{ id: "arrow1", type: "arrow" }, backgroundColor: "transparent",
{ id: "arrow2", type: "arrow" }, fillStyle: "hachure",
{ id: "text1", type: "text" }, strokeWidth: 1,
], strokeStyle: "solid",
}); roundness: null,
roughness: 1,
const text1 = API.createElement({ opacity: 100,
type: "text", text: "hello",
id: "text1", fontSize: 20,
containerId: "rectangle1", fontFamily: FONT_FAMILY.Virgil,
}); textAlign: "left",
verticalAlign: "top",
const arrow1 = API.createElement({
type: "arrow",
id: "arrow1",
startBinding: {
elementId: "rectangle1",
focus: 0.2,
gap: 7,
},
});
const arrow2 = API.createElement({
type: "arrow",
id: "arrow2",
endBinding: {
elementId: "rectangle1",
focus: 0.2,
gap: 7,
},
boundElements: [{ id: "text2", type: "text" }],
});
const text2 = API.createElement({
type: "text",
id: "text2",
containerId: "arrow2",
});
// -------------------------------------------------------------------------
const origElements = [rectangle1, text1, arrow1, arrow2, text2] as const;
const clonedElements = duplicateElements(origElements);
// generic id in-equality checks
// --------------------------------------------------------------------------
expect(origElements.map((e) => e.type)).toEqual(
clonedElements.map((e) => e.type),
);
origElements.forEach((origElement, idx) => {
const clonedElement = clonedElements[idx];
expect(origElement).toEqual(
expect.objectContaining({
id: expect.not.stringMatching(clonedElement.id),
type: clonedElement.type,
}),
);
if ("containerId" in origElement) {
expect(origElement.containerId).not.toBe(
(clonedElement as any).containerId,
);
}
if ("endBinding" in origElement) {
if (origElement.endBinding) {
expect(origElement.endBinding.elementId).not.toBe(
(clonedElement as any).endBinding?.elementId,
);
} else {
expect((clonedElement as any).endBinding).toBeNull();
}
}
if ("startBinding" in origElement) {
if (origElement.startBinding) {
expect(origElement.startBinding.elementId).not.toBe(
(clonedElement as any).startBinding?.elementId,
);
} else {
expect((clonedElement as any).startBinding).toBeNull();
}
}
});
// --------------------------------------------------------------------------
const clonedArrows = clonedElements.filter(
(e) => e.type === "arrow",
) as ExcalidrawLinearElement[];
const [clonedRectangle, clonedText1, , clonedArrow2, clonedArrowLabel] =
clonedElements as any as typeof origElements;
expect(clonedText1.containerId).toBe(clonedRectangle.id);
expect(
clonedRectangle.boundElements!.find((e) => e.id === clonedText1.id),
).toEqual(
expect.objectContaining({
id: clonedText1.id,
type: clonedText1.type,
}),
);
clonedArrows.forEach((arrow) => {
// console.log(arrow);
expect(
clonedRectangle.boundElements!.find((e) => e.id === arrow.id),
).toEqual(
expect.objectContaining({
id: arrow.id,
type: arrow.type,
}),
);
if (arrow.endBinding) {
expect(arrow.endBinding.elementId).toBe(clonedRectangle.id);
}
if (arrow.startBinding) {
expect(arrow.startBinding.elementId).toBe(clonedRectangle.id);
}
});
expect(clonedArrow2.boundElements).toEqual([
{ type: "text", id: clonedArrowLabel.id },
]);
expect(clonedArrowLabel.containerId).toBe(clonedArrow2.id);
}); });
it("should remove id references of elements that aren't found", () => { const copy = duplicateElement(null, new Map(), element);
const rectangle1 = API.createElement({
type: "rectangle",
id: "rectangle1",
boundElements: [
// should keep
{ id: "arrow1", type: "arrow" },
// should drop
{ id: "arrow-not-exists", type: "arrow" },
// should drop
{ id: "text-not-exists", type: "text" },
],
});
const arrow1 = API.createElement({ assertCloneObjects(element, copy);
type: "arrow",
id: "arrow1",
startBinding: {
elementId: "rectangle1",
focus: 0.2,
gap: 7,
},
});
const text1 = API.createElement({ expect(copy).not.toHaveProperty("points");
type: "text", expect(copy).not.toHaveProperty("shape");
id: "text1", expect(copy.id).not.toBe(element.id);
containerId: "rectangle-not-exists", expect(typeof copy.id).toBe("string");
}); expect(typeof copy.seed).toBe("number");
const arrow2 = API.createElement({
type: "arrow",
id: "arrow2",
startBinding: {
elementId: "rectangle1",
focus: 0.2,
gap: 7,
},
endBinding: {
elementId: "rectangle-not-exists",
focus: 0.2,
gap: 7,
},
});
const arrow3 = API.createElement({
type: "arrow",
id: "arrow2",
startBinding: {
elementId: "rectangle-not-exists",
focus: 0.2,
gap: 7,
},
endBinding: {
elementId: "rectangle1",
focus: 0.2,
gap: 7,
},
});
// -------------------------------------------------------------------------
const origElements = [rectangle1, text1, arrow1, arrow2, arrow3] as const;
const clonedElements = duplicateElements(
origElements,
) as any as typeof origElements;
const [
clonedRectangle,
clonedText1,
clonedArrow1,
clonedArrow2,
clonedArrow3,
] = clonedElements;
expect(clonedRectangle.boundElements).toEqual([
{ id: clonedArrow1.id, type: "arrow" },
]);
expect(clonedText1.containerId).toBe(null);
expect(clonedArrow2.startBinding).toEqual({
...arrow2.startBinding,
elementId: clonedRectangle.id,
});
expect(clonedArrow2.endBinding).toBe(null);
expect(clonedArrow3.startBinding).toBe(null);
expect(clonedArrow3.endBinding).toEqual({
...arrow3.endBinding,
elementId: clonedRectangle.id,
});
});
describe("should duplicate all group ids", () => {
it("should regenerate all group ids and keep them consistent across elements", () => {
const rectangle1 = API.createElement({
type: "rectangle",
groupIds: ["g1"],
});
const rectangle2 = API.createElement({
type: "rectangle",
groupIds: ["g2", "g1"],
});
const rectangle3 = API.createElement({
type: "rectangle",
groupIds: ["g2", "g1"],
});
const origElements = [rectangle1, rectangle2, rectangle3] as const;
const clonedElements = duplicateElements(
origElements,
) as any as typeof origElements;
const [clonedRectangle1, clonedRectangle2, clonedRectangle3] =
clonedElements;
expect(rectangle1.groupIds[0]).not.toBe(clonedRectangle1.groupIds[0]);
expect(rectangle2.groupIds[0]).not.toBe(clonedRectangle2.groupIds[0]);
expect(rectangle2.groupIds[1]).not.toBe(clonedRectangle2.groupIds[1]);
expect(clonedRectangle1.groupIds[0]).toBe(clonedRectangle2.groupIds[1]);
expect(clonedRectangle2.groupIds[0]).toBe(clonedRectangle3.groupIds[0]);
expect(clonedRectangle2.groupIds[1]).toBe(clonedRectangle3.groupIds[1]);
});
it("should keep and regenerate ids of groups even if invalid", () => {
// lone element shouldn't be able to be grouped with itself,
// but hard to check against in a performant way so we ignore it
const rectangle1 = API.createElement({
type: "rectangle",
groupIds: ["g1"],
});
const [clonedRectangle1] = duplicateElements([rectangle1]);
expect(typeof clonedRectangle1.groupIds[0]).toBe("string");
expect(rectangle1.groupIds[0]).not.toBe(clonedRectangle1.groupIds[0]);
});
});
}); });
+85 -253
View File
@@ -13,39 +13,25 @@ import {
FontFamilyValues, FontFamilyValues,
ExcalidrawTextContainer, ExcalidrawTextContainer,
} from "../element/types"; } from "../element/types";
import { import { getFontString, getUpdatedTimestamp, isTestEnv } from "../utils";
arrayToMap,
getFontString,
getUpdatedTimestamp,
isTestEnv,
} from "../utils";
import { randomInteger, randomId } from "../random"; import { randomInteger, randomId } from "../random";
import { bumpVersion, mutateElement, newElementWith } from "./mutateElement"; import { mutateElement, newElementWith } from "./mutateElement";
import { getNewGroupIdsForDuplication } from "../groups"; import { getNewGroupIdsForDuplication } from "../groups";
import { AppState } from "../types"; import { AppState } from "../types";
import { getElementAbsoluteCoords } from "."; import { getElementAbsoluteCoords } from ".";
import { adjustXYWithRotation } from "../math"; import { adjustXYWithRotation } from "../math";
import { getResizedElementAbsoluteCoords } from "./bounds"; import { getResizedElementAbsoluteCoords } from "./bounds";
import { import {
getBoundTextElement,
getBoundTextElementOffset, getBoundTextElementOffset,
getContainerDims, getContainerDims,
getContainerElement, getContainerElement,
measureText, measureText,
normalizeText, normalizeText,
wrapText, wrapText,
getBoundTextMaxWidth,
getDefaultLineHeight,
} from "./textElement"; } from "./textElement";
import { import { BOUND_TEXT_PADDING, VERTICAL_ALIGN } from "../constants";
DEFAULT_ELEMENT_PROPS,
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
DEFAULT_TEXT_ALIGN,
DEFAULT_VERTICAL_ALIGN,
VERTICAL_ALIGN,
} from "../constants";
import { isArrowElement } from "./typeChecks"; import { isArrowElement } from "./typeChecks";
import { MarkOptional, Merge, Mutable } from "../utility-types";
type ElementConstructorOpts = MarkOptional< type ElementConstructorOpts = MarkOptional<
Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">, Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted" | "updated">,
@@ -58,15 +44,6 @@ type ElementConstructorOpts = MarkOptional<
| "version" | "version"
| "versionNonce" | "versionNonce"
| "link" | "link"
| "strokeStyle"
| "fillStyle"
| "strokeColor"
| "backgroundColor"
| "roughness"
| "strokeWidth"
| "roundness"
| "locked"
| "opacity"
>; >;
const _newElementBase = <T extends ExcalidrawElement>( const _newElementBase = <T extends ExcalidrawElement>(
@@ -74,13 +51,13 @@ const _newElementBase = <T extends ExcalidrawElement>(
{ {
x, x,
y, y,
strokeColor = DEFAULT_ELEMENT_PROPS.strokeColor, strokeColor,
backgroundColor = DEFAULT_ELEMENT_PROPS.backgroundColor, backgroundColor,
fillStyle = DEFAULT_ELEMENT_PROPS.fillStyle, fillStyle,
strokeWidth = DEFAULT_ELEMENT_PROPS.strokeWidth, strokeWidth,
strokeStyle = DEFAULT_ELEMENT_PROPS.strokeStyle, strokeStyle,
roughness = DEFAULT_ELEMENT_PROPS.roughness, roughness,
opacity = DEFAULT_ELEMENT_PROPS.opacity, opacity,
width = 0, width = 0,
height = 0, height = 0,
angle = 0, angle = 0,
@@ -88,7 +65,7 @@ const _newElementBase = <T extends ExcalidrawElement>(
roundness = null, roundness = null,
boundElements = null, boundElements = null,
link = null, link = null,
locked = DEFAULT_ELEMENT_PROPS.locked, locked,
...rest ...rest
}: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">, }: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">,
) => { ) => {
@@ -154,39 +131,24 @@ const getTextElementPositionOffsets = (
export const newTextElement = ( export const newTextElement = (
opts: { opts: {
text: string; text: string;
fontSize?: number; fontSize: number;
fontFamily?: FontFamilyValues; fontFamily: FontFamilyValues;
textAlign?: TextAlign; textAlign: TextAlign;
verticalAlign?: VerticalAlign; verticalAlign: VerticalAlign;
containerId?: ExcalidrawTextContainer["id"]; containerId?: ExcalidrawTextContainer["id"];
lineHeight?: ExcalidrawTextElement["lineHeight"];
strokeWidth?: ExcalidrawTextElement["strokeWidth"];
} & ElementConstructorOpts, } & ElementConstructorOpts,
): NonDeleted<ExcalidrawTextElement> => { ): NonDeleted<ExcalidrawTextElement> => {
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
const fontSize = opts.fontSize || DEFAULT_FONT_SIZE;
const lineHeight = opts.lineHeight || getDefaultLineHeight(fontFamily);
const text = normalizeText(opts.text); const text = normalizeText(opts.text);
const metrics = measureText( const metrics = measureText(text, getFontString(opts));
text, const offsets = getTextElementPositionOffsets(opts, metrics);
getFontString({ fontFamily, fontSize }),
lineHeight,
);
const textAlign = opts.textAlign || DEFAULT_TEXT_ALIGN;
const verticalAlign = opts.verticalAlign || DEFAULT_VERTICAL_ALIGN;
const offsets = getTextElementPositionOffsets(
{ textAlign, verticalAlign },
metrics,
);
const textElement = newElementWith( const textElement = newElementWith(
{ {
..._newElementBase<ExcalidrawTextElement>("text", opts), ..._newElementBase<ExcalidrawTextElement>("text", opts),
text, text,
fontSize, fontSize: opts.fontSize,
fontFamily, fontFamily: opts.fontFamily,
textAlign, textAlign: opts.textAlign,
verticalAlign, verticalAlign: opts.verticalAlign,
x: opts.x - offsets.x, x: opts.x - offsets.x,
y: opts.y - offsets.y, y: opts.y - offsets.y,
width: metrics.width, width: metrics.width,
@@ -194,7 +156,6 @@ export const newTextElement = (
baseline: metrics.baseline, baseline: metrics.baseline,
containerId: opts.containerId || null, containerId: opts.containerId || null,
originalText: text, originalText: text,
lineHeight,
}, },
{}, {},
); );
@@ -211,13 +172,16 @@ const getAdjustedDimensions = (
height: number; height: number;
baseline: number; baseline: number;
} => { } => {
let maxWidth = null;
const container = getContainerElement(element); const container = getContainerElement(element);
if (container) {
maxWidth = getMaxContainerWidth(container);
}
const { const {
width: nextWidth, width: nextWidth,
height: nextHeight, height: nextHeight,
baseline: nextBaseline, baseline: nextBaseline,
} = measureText(nextText, getFontString(element), element.lineHeight); } = measureText(nextText, getFontString(element), maxWidth);
const { textAlign, verticalAlign } = element; const { textAlign, verticalAlign } = element;
let x: number; let x: number;
let y: number; let y: number;
@@ -229,7 +193,7 @@ const getAdjustedDimensions = (
const prevMetrics = measureText( const prevMetrics = measureText(
element.text, element.text,
getFontString(element), getFontString(element),
element.lineHeight, maxWidth,
); );
const offsets = getTextElementPositionOffsets(element, { const offsets = getTextElementPositionOffsets(element, {
width: nextWidth - prevMetrics.width, width: nextWidth - prevMetrics.width,
@@ -292,9 +256,9 @@ const getAdjustedDimensions = (
return { return {
width: nextWidth, width: nextWidth,
height: nextHeight, height: nextHeight,
baseline: nextBaseline,
x: Number.isFinite(x) ? x : element.x, x: Number.isFinite(x) ? x : element.x,
y: Number.isFinite(y) ? y : element.y, y: Number.isFinite(y) ? y : element.y,
baseline: nextBaseline,
}; };
}; };
@@ -302,21 +266,50 @@ export const refreshTextDimensions = (
textElement: ExcalidrawTextElement, textElement: ExcalidrawTextElement,
text = textElement.text, text = textElement.text,
) => { ) => {
if (textElement.isDeleted) {
return;
}
const container = getContainerElement(textElement); const container = getContainerElement(textElement);
if (container) { if (container) {
text = wrapText( text = wrapText(
text, text,
getFontString(textElement), getFontString(textElement),
getBoundTextMaxWidth(container), getMaxContainerWidth(container),
); );
} }
const dimensions = getAdjustedDimensions(textElement, text); const dimensions = getAdjustedDimensions(textElement, text);
return { text, ...dimensions }; return { text, ...dimensions };
}; };
export const getMaxContainerWidth = (container: ExcalidrawElement) => {
const width = getContainerDims(container).width;
if (isArrowElement(container)) {
const containerWidth = width - BOUND_TEXT_PADDING * 8 * 2;
if (containerWidth <= 0) {
const boundText = getBoundTextElement(container);
if (boundText) {
return boundText.width;
}
return BOUND_TEXT_PADDING * 8 * 2;
}
return containerWidth;
}
return width - BOUND_TEXT_PADDING * 2;
};
export const getMaxContainerHeight = (container: ExcalidrawElement) => {
const height = getContainerDims(container).height;
if (isArrowElement(container)) {
const containerHeight = height - BOUND_TEXT_PADDING * 8 * 2;
if (containerHeight <= 0) {
const boundText = getBoundTextElement(container);
if (boundText) {
return boundText.height;
}
return BOUND_TEXT_PADDING * 8 * 2;
}
return height;
}
return height - BOUND_TEXT_PADDING * 2;
};
export const updateTextElement = ( export const updateTextElement = (
textElement: ExcalidrawTextElement, textElement: ExcalidrawTextElement,
{ {
@@ -390,24 +383,16 @@ export const newImageElement = (
}; };
}; };
// Simplified deep clone for the purpose of cloning ExcalidrawElement. // Simplified deep clone for the purpose of cloning ExcalidrawElement only
// // (doesn't clone Date, RegExp, Map, Set, Typed arrays etc.)
// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,
// Typed arrays and other non-null objects.
// //
// Adapted from https://github.com/lukeed/klona // Adapted from https://github.com/lukeed/klona
// export const deepCopyElement = (val: any, depth: number = 0) => {
// The reason for `deepCopyElement()` wrapper is type safety (only allow
// passing ExcalidrawElement as the top-level argument).
const _deepCopyElement = (val: any, depth: number = 0) => {
// only clone non-primitives
if (val == null || typeof val !== "object") { if (val == null || typeof val !== "object") {
return val; return val;
} }
const objectType = Object.prototype.toString.call(val); if (Object.prototype.toString.call(val) === "[object Object]") {
if (objectType === "[object Object]") {
const tmp = const tmp =
typeof val.constructor === "function" typeof val.constructor === "function"
? Object.create(Object.getPrototypeOf(val)) ? Object.create(Object.getPrototypeOf(val))
@@ -419,7 +404,7 @@ const _deepCopyElement = (val: any, depth: number = 0) => {
if (depth === 0 && (key === "shape" || key === "canvas")) { if (depth === 0 && (key === "shape" || key === "canvas")) {
continue; continue;
} }
tmp[key] = _deepCopyElement(val[key], depth + 1); tmp[key] = deepCopyElement(val[key], depth + 1);
} }
} }
return tmp; return tmp;
@@ -429,67 +414,14 @@ const _deepCopyElement = (val: any, depth: number = 0) => {
let k = val.length; let k = val.length;
const arr = new Array(k); const arr = new Array(k);
while (k--) { while (k--) {
arr[k] = _deepCopyElement(val[k], depth + 1); arr[k] = deepCopyElement(val[k], depth + 1);
} }
return arr; return arr;
} }
// we're not cloning non-array & non-plain-object objects because we
// don't support them on excalidraw elements yet. If we do, we need to make
// sure we start cloning them, so let's warn about it.
if (process.env.NODE_ENV === "development") {
if (
objectType !== "[object Object]" &&
objectType !== "[object Array]" &&
objectType.startsWith("[object ")
) {
console.warn(
`_deepCloneElement: unexpected object type ${objectType}. This value will not be cloned!`,
);
}
}
return val; return val;
}; };
/**
* Clones ExcalidrawElement data structure. Does not regenerate id, nonce, or
* any value. The purpose is to to break object references for immutability
* reasons, whenever we want to keep the original element, but ensure it's not
* mutated.
*
* Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,
* Typed arrays and other non-null objects.
*/
export const deepCopyElement = <T extends ExcalidrawElement>(
val: T,
): Mutable<T> => {
return _deepCopyElement(val);
};
/**
* utility wrapper to generate new id. In test env it reuses the old + postfix
* for test assertions.
*/
const regenerateId = (
/** supply null if no previous id exists */
previousId: string | null,
) => {
if (isTestEnv() && previousId) {
let nextId = `${previousId}_copy`;
// `window.h` may not be defined in some unit tests
if (
window.h?.app
?.getSceneElementsIncludingDeleted()
.find((el) => el.id === nextId)
) {
nextId += "_copy";
}
return nextId;
}
return randomId();
};
/** /**
* Duplicate an element, often used in the alt-drag operation. * Duplicate an element, often used in the alt-drag operation.
* Note that this method has gotten a bit complicated since the * Note that this method has gotten a bit complicated since the
@@ -504,15 +436,27 @@ const regenerateId = (
* @param element Element to duplicate * @param element Element to duplicate
* @param overrides Any element properties to override * @param overrides Any element properties to override
*/ */
export const duplicateElement = <TElement extends ExcalidrawElement>( export const duplicateElement = <TElement extends Mutable<ExcalidrawElement>>(
editingGroupId: AppState["editingGroupId"], editingGroupId: AppState["editingGroupId"],
groupIdMapForOperation: Map<GroupId, GroupId>, groupIdMapForOperation: Map<GroupId, GroupId>,
element: TElement, element: TElement,
overrides?: Partial<TElement>, overrides?: Partial<TElement>,
): Readonly<TElement> => { ): TElement => {
let copy = deepCopyElement(element); let copy: TElement = deepCopyElement(element);
copy.id = regenerateId(copy.id); if (isTestEnv()) {
copy.id = `${copy.id}_copy`;
// `window.h` may not be defined in some unit tests
if (
window.h?.app
?.getSceneElementsIncludingDeleted()
.find((el) => el.id === copy.id)
) {
copy.id += "_copy";
}
} else {
copy.id = randomId();
}
copy.boundElements = null; copy.boundElements = null;
copy.updated = getUpdatedTimestamp(); copy.updated = getUpdatedTimestamp();
copy.seed = randomInteger(); copy.seed = randomInteger();
@@ -521,7 +465,7 @@ export const duplicateElement = <TElement extends ExcalidrawElement>(
editingGroupId, editingGroupId,
(groupId) => { (groupId) => {
if (!groupIdMapForOperation.has(groupId)) { if (!groupIdMapForOperation.has(groupId)) {
groupIdMapForOperation.set(groupId, regenerateId(groupId)); groupIdMapForOperation.set(groupId, randomId());
} }
return groupIdMapForOperation.get(groupId)!; return groupIdMapForOperation.get(groupId)!;
}, },
@@ -531,115 +475,3 @@ export const duplicateElement = <TElement extends ExcalidrawElement>(
} }
return copy; return copy;
}; };
/**
* Clones elements, regenerating their ids (including bindings) and group ids.
*
* If bindings don't exist in the elements array, they are removed. Therefore,
* it's advised to supply the whole elements array, or sets of elements that
* are encapsulated (such as library items), if the purpose is to retain
* bindings to the cloned elements intact.
*
* NOTE by default does not randomize or regenerate anything except the id.
*/
export const duplicateElements = (
elements: readonly ExcalidrawElement[],
opts?: {
/** NOTE also updates version flags and `updated` */
randomizeSeed: boolean;
},
) => {
const clonedElements: ExcalidrawElement[] = [];
const origElementsMap = arrayToMap(elements);
// used for for migrating old ids to new ids
const elementNewIdsMap = new Map<
/* orig */ ExcalidrawElement["id"],
/* new */ ExcalidrawElement["id"]
>();
const maybeGetNewId = (id: ExcalidrawElement["id"]) => {
// if we've already migrated the element id, return the new one directly
if (elementNewIdsMap.has(id)) {
return elementNewIdsMap.get(id)!;
}
// if we haven't migrated the element id, but an old element with the same
// id exists, generate a new id for it and return it
if (origElementsMap.has(id)) {
const newId = regenerateId(id);
elementNewIdsMap.set(id, newId);
return newId;
}
// if old element doesn't exist, return null to mark it for removal
return null;
};
const groupNewIdsMap = new Map</* orig */ GroupId, /* new */ GroupId>();
for (const element of elements) {
const clonedElement: Mutable<ExcalidrawElement> = _deepCopyElement(element);
clonedElement.id = maybeGetNewId(element.id)!;
if (opts?.randomizeSeed) {
clonedElement.seed = randomInteger();
bumpVersion(clonedElement);
}
if (clonedElement.groupIds) {
clonedElement.groupIds = clonedElement.groupIds.map((groupId) => {
if (!groupNewIdsMap.has(groupId)) {
groupNewIdsMap.set(groupId, regenerateId(groupId));
}
return groupNewIdsMap.get(groupId)!;
});
}
if ("containerId" in clonedElement && clonedElement.containerId) {
const newContainerId = maybeGetNewId(clonedElement.containerId);
clonedElement.containerId = newContainerId;
}
if ("boundElements" in clonedElement && clonedElement.boundElements) {
clonedElement.boundElements = clonedElement.boundElements.reduce(
(
acc: Mutable<NonNullable<ExcalidrawElement["boundElements"]>>,
binding,
) => {
const newBindingId = maybeGetNewId(binding.id);
if (newBindingId) {
acc.push({ ...binding, id: newBindingId });
}
return acc;
},
[],
);
}
if ("endBinding" in clonedElement && clonedElement.endBinding) {
const newEndBindingId = maybeGetNewId(clonedElement.endBinding.elementId);
clonedElement.endBinding = newEndBindingId
? {
...clonedElement.endBinding,
elementId: newEndBindingId,
}
: null;
}
if ("startBinding" in clonedElement && clonedElement.startBinding) {
const newEndBindingId = maybeGetNewId(
clonedElement.startBinding.elementId,
);
clonedElement.startBinding = newEndBindingId
? {
...clonedElement.startBinding,
elementId: newEndBindingId,
}
: null;
}
clonedElements.push(clonedElement);
}
return clonedElements;
};
+28 -49
View File
@@ -39,16 +39,16 @@ import {
import { Point, PointerDownState } from "../types"; import { Point, PointerDownState } from "../types";
import Scene from "../scene/Scene"; import Scene from "../scene/Scene";
import { import {
getApproxMinLineHeight,
getApproxMinLineWidth, getApproxMinLineWidth,
getBoundTextElement, getBoundTextElement,
getBoundTextElementId, getBoundTextElementId,
getBoundTextElementOffset,
getContainerElement, getContainerElement,
handleBindTextResize, handleBindTextResize,
getBoundTextMaxWidth,
getApproxMinLineHeight,
measureText, measureText,
getBoundTextMaxHeight,
} from "./textElement"; } from "./textElement";
import { getMaxContainerWidth } from "./newElement";
export const normalizeAngle = (angle: number): number => { export const normalizeAngle = (angle: number): number => {
if (angle >= 2 * Math.PI) { if (angle >= 2 * Math.PI) {
@@ -192,7 +192,7 @@ const rescalePointsInElement = (
const MIN_FONT_SIZE = 1; const MIN_FONT_SIZE = 1;
const measureFontSizeFromWidth = ( const measureFontSizeFromWH = (
element: NonDeleted<ExcalidrawTextElement>, element: NonDeleted<ExcalidrawTextElement>,
nextWidth: number, nextWidth: number,
nextHeight: number, nextHeight: number,
@@ -204,7 +204,7 @@ const measureFontSizeFromWidth = (
if (hasContainer) { if (hasContainer) {
const container = getContainerElement(element); const container = getContainerElement(element);
if (container) { if (container) {
width = getBoundTextMaxWidth(container); width = getMaxContainerWidth(container);
} }
} }
const nextFontSize = element.fontSize * (nextWidth / width); const nextFontSize = element.fontSize * (nextWidth / width);
@@ -214,7 +214,7 @@ const measureFontSizeFromWidth = (
const metrics = measureText( const metrics = measureText(
element.text, element.text,
getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }), getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }),
element.lineHeight, element.containerId ? width : null,
); );
return { return {
size: nextFontSize, size: nextFontSize,
@@ -290,8 +290,8 @@ const resizeSingleTextElement = (
if (scale > 0) { if (scale > 0) {
const nextWidth = element.width * scale; const nextWidth = element.width * scale;
const nextHeight = element.height * scale; const nextHeight = element.height * scale;
const metrics = measureFontSizeFromWidth(element, nextWidth, nextHeight); const nextFont = measureFontSizeFromWH(element, nextWidth, nextHeight);
if (metrics === null) { if (nextFont === null) {
return; return;
} }
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords( const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
@@ -315,10 +315,10 @@ const resizeSingleTextElement = (
deltaY2, deltaY2,
); );
mutateElement(element, { mutateElement(element, {
fontSize: metrics.size, fontSize: nextFont.size,
width: nextWidth, width: nextWidth,
height: nextHeight, height: nextHeight,
baseline: metrics.baseline, baseline: nextFont.baseline,
x: nextElementX, x: nextElementX,
y: nextElementY, y: nextElementY,
}); });
@@ -427,16 +427,12 @@ export const resizeSingleElement = (
}; };
} }
if (shouldMaintainAspectRatio) { if (shouldMaintainAspectRatio) {
const updatedElement = { const boundTextElementPadding =
...element, getBoundTextElementOffset(boundTextElement);
width: eleNewWidth, const nextFont = measureFontSizeFromWH(
height: eleNewHeight,
};
const nextFont = measureFontSizeFromWidth(
boundTextElement, boundTextElement,
getBoundTextMaxWidth(updatedElement), eleNewWidth - boundTextElementPadding * 2,
getBoundTextMaxHeight(updatedElement, boundTextElement), eleNewHeight - boundTextElementPadding * 2,
); );
if (nextFont === null) { if (nextFont === null) {
return; return;
@@ -446,14 +442,8 @@ export const resizeSingleElement = (
baseline: nextFont.baseline, baseline: nextFont.baseline,
}; };
} else { } else {
const minWidth = getApproxMinLineWidth( const minWidth = getApproxMinLineWidth(getFontString(boundTextElement));
getFontString(boundTextElement), const minHeight = getApproxMinLineHeight(getFontString(boundTextElement));
boundTextElement.lineHeight,
);
const minHeight = getApproxMinLineHeight(
boundTextElement.fontSize,
boundTextElement.lineHeight,
);
eleNewWidth = Math.ceil(Math.max(eleNewWidth, minWidth)); eleNewWidth = Math.ceil(Math.max(eleNewWidth, minWidth));
eleNewHeight = Math.ceil(Math.max(eleNewHeight, minHeight)); eleNewHeight = Math.ceil(Math.max(eleNewHeight, minHeight));
} }
@@ -586,11 +576,8 @@ export const resizeSingleElement = (
}); });
mutateElement(element, resizedElement); mutateElement(element, resizedElement);
if (boundTextElement && boundTextFont != null) { if (boundTextElement && boundTextFont) {
mutateElement(boundTextElement, { mutateElement(boundTextElement, { fontSize: boundTextFont.fontSize });
fontSize: boundTextFont.fontSize,
baseline: boundTextFont.baseline,
});
} }
handleBindTextResize(element, transformHandleDirection); handleBindTextResize(element, transformHandleDirection);
} }
@@ -710,34 +697,26 @@ const resizeMultipleElements = (
const boundTextElement = getBoundTextElement(element.latest); const boundTextElement = getBoundTextElement(element.latest);
if (boundTextElement || isTextElement(element.orig)) { if (boundTextElement || isTextElement(element.orig)) {
const updatedElement = { const optionalPadding = getBoundTextElementOffset(boundTextElement) * 2;
...element.latest, const textMeasurements = measureFontSizeFromWH(
width,
height,
};
const metrics = measureFontSizeFromWidth(
boundTextElement ?? (element.orig as ExcalidrawTextElement), boundTextElement ?? (element.orig as ExcalidrawTextElement),
boundTextElement width - optionalPadding,
? getBoundTextMaxWidth(updatedElement) height - optionalPadding,
: updatedElement.width,
boundTextElement
? getBoundTextMaxHeight(updatedElement, boundTextElement)
: updatedElement.height,
); );
if (!metrics) { if (!textMeasurements) {
return; return;
} }
if (isTextElement(element.orig)) { if (isTextElement(element.orig)) {
update.fontSize = metrics.size; update.fontSize = textMeasurements.size;
update.baseline = metrics.baseline; update.baseline = textMeasurements.baseline;
} }
if (boundTextElement) { if (boundTextElement) {
boundTextUpdates = { boundTextUpdates = {
fontSize: metrics.size, fontSize: textMeasurements.size,
baseline: metrics.baseline, baseline: textMeasurements.baseline,
}; };
} }
} }
+48 -284
View File
@@ -1,17 +1,6 @@
import { BOUND_TEXT_PADDING, FONT_FAMILY } from "../constants"; import { BOUND_TEXT_PADDING } from "../constants";
import { API } from "../tests/helpers/api"; import { measureText, wrapText } from "./textElement";
import { import { FontString } from "./types";
computeContainerDimensionForBoundText,
getContainerCoords,
getBoundTextMaxWidth,
getBoundTextMaxHeight,
wrapText,
detectLineHeight,
getLineHeightInPx,
getDefaultLineHeight,
parseTokens,
} from "./textElement";
import { ExcalidrawTextElementWithContainer, FontString } from "./types";
describe("Test wrapText", () => { describe("Test wrapText", () => {
const font = "20px Cascadia, width: Segoe UI Emoji" as FontString; const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
@@ -20,7 +9,7 @@ describe("Test wrapText", () => {
const text = "Hello whats up "; const text = "Hello whats up ";
const maxWidth = 200 - BOUND_TEXT_PADDING * 2; const maxWidth = 200 - BOUND_TEXT_PADDING * 2;
const res = wrapText(text, font, maxWidth); const res = wrapText(text, font, maxWidth);
expect(res).toBe(text); expect(res).toBe("Hello whats up ");
}); });
it("should work with emojis", () => { it("should work with emojis", () => {
@@ -30,7 +19,7 @@ describe("Test wrapText", () => {
expect(res).toBe("😀"); expect(res).toBe("😀");
}); });
it("should show the text correctly when max width reached", () => { it("should show the text correctly when min width reached", () => {
const text = "Hello😀"; const text = "Hello😀";
const maxWidth = 10; const maxWidth = 10;
const res = wrapText(text, font, maxWidth); const res = wrapText(text, font, maxWidth);
@@ -39,12 +28,13 @@ describe("Test wrapText", () => {
describe("When text doesn't contain new lines", () => { describe("When text doesn't contain new lines", () => {
const text = "Hello whats up"; const text = "Hello whats up";
[ [
{ {
desc: "break all words when width of each word is less than container width", desc: "break all words when width of each word is less than container width",
width: 80, width: 90,
res: `Hello \nwhats \nup`, res: `Hello
whats
up`,
}, },
{ {
desc: "break all characters when width of each character is less than container width", desc: "break all characters when width of each character is less than container width",
@@ -65,8 +55,9 @@ p`,
{ {
desc: "break words as per the width", desc: "break words as per the width",
width: 140, width: 150,
res: `Hello whats \nup`, res: `Hello whats
up`,
}, },
{ {
desc: "fit the container", desc: "fit the container",
@@ -74,13 +65,6 @@ p`,
width: 250, width: 250,
res: "Hello whats up", res: "Hello whats up",
}, },
{
desc: "should push the word if its equal to max width",
width: 60,
res: `Hello
whats
up`,
},
].forEach((data) => { ].forEach((data) => {
it(`should ${data.desc}`, () => { it(`should ${data.desc}`, () => {
const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2); const res = wrapText(text, font, data.width - BOUND_TEXT_PADDING * 2);
@@ -88,15 +72,16 @@ up`,
}); });
}); });
}); });
describe("When text contain new lines", () => { describe("When text contain new lines", () => {
const text = `Hello const text = `Hello
whats up`; whats up`;
[ [
{ {
desc: "break all words when width of each word is less than container width", desc: "break all words when width of each word is less than container width",
width: 80, width: 90,
res: `Hello\nwhats \nup`, res: `Hello
whats
up`,
}, },
{ {
desc: "break all characters when width of each character is less than container width", desc: "break all characters when width of each character is less than container width",
@@ -135,14 +120,17 @@ whats up`,
}); });
}); });
}); });
describe("When text is long", () => { describe("When text is long", () => {
const text = `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg break it now`; const text = `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg break it now`;
[ [
{ {
desc: "fit characters of long string as per container width", desc: "fit characters of long string as per container width",
width: 170, width: 170,
res: `hellolongtextth\nisiswhatsupwith\nyouIamtypingggg\ngandtypinggg \nbreak it now`, res: `hellolongtextth
isiswhatsupwith
youIamtypingggg
gandtypinggg
break it now`,
}, },
{ {
@@ -161,7 +149,8 @@ now`,
desc: "fit the long text when container width is greater than text length and move the rest to next line", desc: "fit the long text when container width is greater than text length and move the rest to next line",
width: 600, width: 600,
res: `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg \nbreak it now`, res: `hellolongtextthisiswhatsupwithyouIamtypingggggandtypinggg
break it now`,
}, },
].forEach((data) => { ].forEach((data) => {
it(`should ${data.desc}`, () => { it(`should ${data.desc}`, () => {
@@ -170,263 +159,38 @@ now`,
}); });
}); });
}); });
it("should wrap the text correctly when word length is exactly equal to max width", () => {
const text = "Hello Excalidraw";
// Length of "Excalidraw" is 100 and exacty equal to max width
const res = wrapText(text, font, 100);
expect(res).toEqual(`Hello \nExcalidraw`);
});
it("should return the text as is if max width is invalid", () => {
const text = "Hello Excalidraw";
expect(wrapText(text, font, NaN)).toEqual(text);
expect(wrapText(text, font, -1)).toEqual(text);
expect(wrapText(text, font, Infinity)).toEqual(text);
});
it("should wrap the text correctly when text contains hyphen", () => {
let text =
"Wikipedia is hosted by Wikimedia- Foundation, a non-profit organization that also hosts a range-of other projects";
const res = wrapText(text, font, 110);
expect(res).toBe(
`Wikipedia \nis hosted \nby \nWikimedia-\nFoundation,\na non-\nprofit \norganizati\non that \nalso hosts\na range-of\nother \nprojects`,
);
text = "Hello thereusing-now";
expect(wrapText(text, font, 100)).toEqual("Hello \nthereusin\ng-now");
});
});
describe("Test parseTokens", () => {
it("should split into tokens correctly", () => {
let text = "Excalidraw is a virtual collaborative whiteboard";
expect(parseTokens(text)).toEqual([
"Excalidraw",
"is",
"a",
"virtual",
"collaborative",
"whiteboard",
]);
text =
"Wikipedia is hosted by Wikimedia- Foundation, a non-profit organization that also hosts a range-of other projects";
expect(parseTokens(text)).toEqual([
"Wikipedia",
"is",
"hosted",
"by",
"Wikimedia-",
"",
"Foundation,",
"a",
"non-",
"profit",
"organization",
"that",
"also",
"hosts",
"a",
"range-",
"of",
"other",
"projects",
]);
});
}); });
describe("Test measureText", () => { describe("Test measureText", () => {
describe("Test getContainerCoords", () => { const font = "20px Cascadia, width: Segoe UI Emoji" as FontString;
const params = { width: 200, height: 100, x: 10, y: 20 }; const text = "Hello World";
it("should compute coords correctly when ellipse", () => { it("should add correct attributes when maxWidth is passed", () => {
const element = API.createElement({ const maxWidth = 200 - BOUND_TEXT_PADDING * 2;
type: "ellipse", const res = measureText(text, font, maxWidth);
...params,
});
expect(getContainerCoords(element)).toEqual({
x: 44.2893218813452455,
y: 39.64466094067262,
});
});
it("should compute coords correctly when rectangle", () => { expect(res.container).toMatchInlineSnapshot(`
const element = API.createElement({ <div
type: "rectangle", style="position: absolute; white-space: pre-wrap; font: Emoji 20px 20px; min-height: 1em; max-width: 191px; overflow: hidden; word-break: break-word; line-height: 0px;"
...params, >
}); <span
expect(getContainerCoords(element)).toEqual({ style="display: inline-block; overflow: hidden; width: 1px; height: 1px;"
x: 15, />
y: 25, </div>
}); `);
});
it("should compute coords correctly when diamond", () => {
const element = API.createElement({
type: "diamond",
...params,
});
expect(getContainerCoords(element)).toEqual({
x: 65,
y: 50,
});
});
}); });
describe("Test computeContainerDimensionForBoundText", () => { it("should add correct attributes when maxWidth is not passed", () => {
const params = { const res = measureText(text, font);
width: 178,
height: 194,
};
it("should compute container height correctly for rectangle", () => { expect(res.container).toMatchInlineSnapshot(`
const element = API.createElement({ <div
type: "rectangle", style="position: absolute; white-space: pre; font: Emoji 20px 20px; min-height: 1em;"
...params, >
}); <span
expect(computeContainerDimensionForBoundText(150, element.type)).toEqual( style="display: inline-block; overflow: hidden; width: 1px; height: 1px;"
160, />
); </div>
}); `);
it("should compute container height correctly for ellipse", () => {
const element = API.createElement({
type: "ellipse",
...params,
});
expect(computeContainerDimensionForBoundText(150, element.type)).toEqual(
226,
);
});
it("should compute container height correctly for diamond", () => {
const element = API.createElement({
type: "diamond",
...params,
});
expect(computeContainerDimensionForBoundText(150, element.type)).toEqual(
320,
);
});
});
describe("Test getBoundTextMaxWidth", () => {
const params = {
width: 178,
height: 194,
};
it("should return max width when container is rectangle", () => {
const container = API.createElement({ type: "rectangle", ...params });
expect(getBoundTextMaxWidth(container)).toBe(168);
});
it("should return max width when container is ellipse", () => {
const container = API.createElement({ type: "ellipse", ...params });
expect(getBoundTextMaxWidth(container)).toBe(116);
});
it("should return max width when container is diamond", () => {
const container = API.createElement({ type: "diamond", ...params });
expect(getBoundTextMaxWidth(container)).toBe(79);
});
});
describe("Test getBoundTextMaxHeight", () => {
const params = {
width: 178,
height: 194,
id: '"container-id',
};
const boundTextElement = API.createElement({
type: "text",
id: "text-id",
x: 560.51171875,
y: 202.033203125,
width: 154,
height: 175,
fontSize: 20,
fontFamily: 1,
text: "Excalidraw is a\nvirtual \nopensource \nwhiteboard for \nsketching \nhand-drawn like\ndiagrams",
textAlign: "center",
verticalAlign: "middle",
containerId: params.id,
}) as ExcalidrawTextElementWithContainer;
it("should return max height when container is rectangle", () => {
const container = API.createElement({ type: "rectangle", ...params });
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(184);
});
it("should return max height when container is ellipse", () => {
const container = API.createElement({ type: "ellipse", ...params });
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(127);
});
it("should return max height when container is diamond", () => {
const container = API.createElement({ type: "diamond", ...params });
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(87);
});
it("should return max height when container is arrow", () => {
const container = API.createElement({
type: "arrow",
...params,
});
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(194);
});
it("should return max height when container is arrow and height is less than threshold", () => {
const container = API.createElement({
type: "arrow",
...params,
height: 70,
boundElements: [{ type: "text", id: "text-id" }],
});
expect(getBoundTextMaxHeight(container, boundTextElement)).toBe(
boundTextElement.height,
);
});
});
});
const textElement = API.createElement({
type: "text",
text: "Excalidraw is a\nvirtual \nopensource \nwhiteboard for \nsketching \nhand-drawn like\ndiagrams",
fontSize: 20,
fontFamily: 1,
height: 175,
});
describe("Test detectLineHeight", () => {
it("should return correct line height", () => {
expect(detectLineHeight(textElement)).toBe(1.25);
});
});
describe("Test getLineHeightInPx", () => {
it("should return correct line height", () => {
expect(
getLineHeightInPx(textElement.fontSize, textElement.lineHeight),
).toBe(25);
});
});
describe("Test getDefaultLineHeight", () => {
it("should return line height using default font family when not passed", () => {
//@ts-ignore
expect(getDefaultLineHeight()).toBe(1.25);
});
it("should return line height using default font family for unknown font", () => {
const UNKNOWN_FONT = 5;
expect(getDefaultLineHeight(UNKNOWN_FONT)).toBe(1.25);
});
it("should return correct line height", () => {
expect(getDefaultLineHeight(FONT_FAMILY.Cascadia)).toBe(1.2);
}); });
}); });
+180 -434
View File
@@ -4,24 +4,20 @@ import {
ExcalidrawTextContainer, ExcalidrawTextContainer,
ExcalidrawTextElement, ExcalidrawTextElement,
ExcalidrawTextElementWithContainer, ExcalidrawTextElementWithContainer,
FontFamilyValues,
FontString, FontString,
NonDeletedExcalidrawElement, NonDeletedExcalidrawElement,
} from "./types"; } from "./types";
import { mutateElement } from "./mutateElement"; import { mutateElement } from "./mutateElement";
import { import { BOUND_TEXT_PADDING, TEXT_ALIGN, VERTICAL_ALIGN } from "../constants";
BOUND_TEXT_PADDING,
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
FONT_FAMILY,
isSafari,
TEXT_ALIGN,
VERTICAL_ALIGN,
} from "../constants";
import { MaybeTransformHandleType } from "./transformHandles"; import { MaybeTransformHandleType } from "./transformHandles";
import Scene from "../scene/Scene"; import Scene from "../scene/Scene";
import { isTextElement } from "."; import { isTextElement } from ".";
import { isBoundToContainer, isArrowElement } from "./typeChecks"; import { getMaxContainerHeight, getMaxContainerWidth } from "./newElement";
import {
isBoundToContainer,
isImageElement,
isArrowElement,
} from "./typeChecks";
import { LinearElementEditor } from "./linearElementEditor"; import { LinearElementEditor } from "./linearElementEditor";
import { AppState } from "../types"; import { AppState } from "../types";
import { isTextBindableContainer } from "./typeChecks"; import { isTextBindableContainer } from "./typeChecks";
@@ -32,7 +28,6 @@ import {
resetOriginalContainerCache, resetOriginalContainerCache,
updateOriginalContainerCache, updateOriginalContainerCache,
} from "./textWysiwyg"; } from "./textWysiwyg";
import { ExtractSetType } from "../utility-types";
export const normalizeText = (text: string) => { export const normalizeText = (text: string) => {
return ( return (
@@ -44,72 +39,73 @@ export const normalizeText = (text: string) => {
); );
}; };
export const splitIntoLines = (text: string) => {
return normalizeText(text).split("\n");
};
export const redrawTextBoundingBox = ( export const redrawTextBoundingBox = (
textElement: ExcalidrawTextElement, textElement: ExcalidrawTextElement,
container: ExcalidrawElement | null, container: ExcalidrawElement | null,
) => { ) => {
let maxWidth = undefined; let maxWidth = undefined;
const boundTextUpdates = { let text = textElement.text;
x: textElement.x,
y: textElement.y,
text: textElement.text,
width: textElement.width,
height: textElement.height,
baseline: textElement.baseline,
};
boundTextUpdates.text = textElement.text;
if (container) { if (container) {
maxWidth = getBoundTextMaxWidth(container); maxWidth = getMaxContainerWidth(container);
boundTextUpdates.text = wrapText( text = wrapText(
textElement.originalText, textElement.originalText,
getFontString(textElement), getFontString(textElement),
maxWidth, maxWidth,
); );
} }
const metrics = measureText( const metrics = measureText(text, getFontString(textElement), maxWidth);
boundTextUpdates.text, let coordY = textElement.y;
getFontString(textElement), let coordX = textElement.x;
textElement.lineHeight, // Resize container and vertically center align the text
);
boundTextUpdates.width = metrics.width;
boundTextUpdates.height = metrics.height;
boundTextUpdates.baseline = metrics.baseline;
if (container) { if (container) {
const containerDims = getContainerDims(container);
const maxContainerHeight = getBoundTextMaxHeight(
container,
textElement as ExcalidrawTextElementWithContainer,
);
let nextHeight = containerDims.height;
if (metrics.height > maxContainerHeight) {
nextHeight = computeContainerDimensionForBoundText(
metrics.height,
container.type,
);
mutateElement(container, { height: nextHeight });
updateOriginalContainerCache(container.id, nextHeight);
}
if (!isArrowElement(container)) { if (!isArrowElement(container)) {
const updatedTextElement = { const containerDims = getContainerDims(container);
...textElement, let nextHeight = containerDims.height;
...boundTextUpdates, if (textElement.verticalAlign === VERTICAL_ALIGN.TOP) {
} as ExcalidrawTextElementWithContainer; coordY = container.y;
const { x, y } = computeBoundTextPosition(container, updatedTextElement); } else if (textElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
boundTextUpdates.x = x; coordY =
boundTextUpdates.y = y; container.y +
containerDims.height -
metrics.height -
BOUND_TEXT_PADDING;
} else {
coordY = container.y + containerDims.height / 2 - metrics.height / 2;
if (metrics.height > getMaxContainerHeight(container)) {
nextHeight = metrics.height + BOUND_TEXT_PADDING * 2;
coordY = container.y + nextHeight / 2 - metrics.height / 2;
}
}
if (textElement.textAlign === TEXT_ALIGN.LEFT) {
coordX = container.x + BOUND_TEXT_PADDING;
} else if (textElement.textAlign === TEXT_ALIGN.RIGHT) {
coordX =
container.x +
containerDims.width -
metrics.width -
BOUND_TEXT_PADDING;
} else {
coordX = container.x + containerDims.width / 2 - metrics.width / 2;
}
updateOriginalContainerCache(container.id, nextHeight);
mutateElement(container, { height: nextHeight });
} else {
const centerX = textElement.x + textElement.width / 2;
const centerY = textElement.y + textElement.height / 2;
const diffWidth = metrics.width - textElement.width;
const diffHeight = metrics.height - textElement.height;
coordY = centerY - (textElement.height + diffHeight) / 2;
coordX = centerX - (textElement.width + diffWidth) / 2;
} }
} }
mutateElement(textElement, {
mutateElement(textElement, boundTextUpdates); width: metrics.width,
height: metrics.height,
baseline: metrics.baseline,
y: coordY,
x: coordX,
text,
});
}; };
export const bindTextToShapeAfterDuplication = ( export const bindTextToShapeAfterDuplication = (
@@ -178,11 +174,8 @@ export const handleBindTextResize = (
let nextHeight = textElement.height; let nextHeight = textElement.height;
let nextWidth = textElement.width; let nextWidth = textElement.width;
const containerDims = getContainerDims(container); const containerDims = getContainerDims(container);
const maxWidth = getBoundTextMaxWidth(container); const maxWidth = getMaxContainerWidth(container);
const maxHeight = getBoundTextMaxHeight( const maxHeight = getMaxContainerHeight(container);
container,
textElement as ExcalidrawTextElementWithContainer,
);
let containerHeight = containerDims.height; let containerHeight = containerDims.height;
let nextBaseLine = textElement.baseline; let nextBaseLine = textElement.baseline;
if (transformHandleType !== "n" && transformHandleType !== "s") { if (transformHandleType !== "n" && transformHandleType !== "s") {
@@ -193,22 +186,18 @@ export const handleBindTextResize = (
maxWidth, maxWidth,
); );
} }
const metrics = measureText( const dimensions = measureText(
text, text,
getFontString(textElement), getFontString(textElement),
textElement.lineHeight, maxWidth,
); );
nextHeight = metrics.height; nextHeight = dimensions.height;
nextWidth = metrics.width; nextWidth = dimensions.width;
nextBaseLine = metrics.baseline; nextBaseLine = dimensions.baseline;
} }
// increase height in case text element height exceeds // increase height in case text element height exceeds
if (nextHeight > maxHeight) { if (nextHeight > maxHeight) {
containerHeight = computeContainerDimensionForBoundText( containerHeight = nextHeight + getBoundTextElementOffset(textElement) * 2;
nextHeight,
container.type,
);
const diff = containerHeight - containerDims.height; const diff = containerHeight - containerDims.height;
// fix the y coord when resizing from ne/nw/n // fix the y coord when resizing from ne/nw/n
const updatedY = const updatedY =
@@ -228,63 +217,53 @@ export const handleBindTextResize = (
text, text,
width: nextWidth, width: nextWidth,
height: nextHeight, height: nextHeight,
baseline: nextBaseLine, baseline: nextBaseLine,
}); });
if (!isArrowElement(container)) { if (!isArrowElement(container)) {
mutateElement( updateBoundTextPosition(
textElement, container,
computeBoundTextPosition( textElement as ExcalidrawTextElementWithContainer,
container,
textElement as ExcalidrawTextElementWithContainer,
),
); );
} }
} }
}; };
export const computeBoundTextPosition = ( const updateBoundTextPosition = (
container: ExcalidrawElement, container: ExcalidrawElement,
boundTextElement: ExcalidrawTextElementWithContainer, boundTextElement: ExcalidrawTextElementWithContainer,
) => { ) => {
if (isArrowElement(container)) { const containerDims = getContainerDims(container);
return LinearElementEditor.getBoundTextElementPosition( const boundTextElementPadding = getBoundTextElementOffset(boundTextElement);
container,
boundTextElement,
);
}
const containerCoords = getContainerCoords(container);
const maxContainerHeight = getBoundTextMaxHeight(container, boundTextElement);
const maxContainerWidth = getBoundTextMaxWidth(container);
let x;
let y; let y;
if (boundTextElement.verticalAlign === VERTICAL_ALIGN.TOP) { if (boundTextElement.verticalAlign === VERTICAL_ALIGN.TOP) {
y = containerCoords.y; y = container.y + boundTextElementPadding;
} else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) { } else if (boundTextElement.verticalAlign === VERTICAL_ALIGN.BOTTOM) {
y = containerCoords.y + (maxContainerHeight - boundTextElement.height);
} else {
y = y =
containerCoords.y + container.y +
(maxContainerHeight / 2 - boundTextElement.height / 2); containerDims.height -
} boundTextElement.height -
if (boundTextElement.textAlign === TEXT_ALIGN.LEFT) { boundTextElementPadding;
x = containerCoords.x;
} else if (boundTextElement.textAlign === TEXT_ALIGN.RIGHT) {
x = containerCoords.x + (maxContainerWidth - boundTextElement.width);
} else { } else {
x = y = container.y + containerDims.height / 2 - boundTextElement.height / 2;
containerCoords.x + (maxContainerWidth / 2 - boundTextElement.width / 2);
} }
return { x, y }; const x =
boundTextElement.textAlign === TEXT_ALIGN.LEFT
? container.x + boundTextElementPadding
: boundTextElement.textAlign === TEXT_ALIGN.RIGHT
? container.x +
containerDims.width -
boundTextElement.width -
boundTextElementPadding
: container.x + containerDims.width / 2 - boundTextElement.width / 2;
mutateElement(boundTextElement, { x, y });
}; };
// https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js // https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js
export const measureText = ( export const measureText = (
text: string, text: string,
font: FontString, font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"], maxWidth?: number | null,
) => { ) => {
text = text text = text
.split("\n") .split("\n")
@@ -292,36 +271,23 @@ export const measureText = (
// lines would be stripped from computation // lines would be stripped from computation
.map((x) => x || " ") .map((x) => x || " ")
.join("\n"); .join("\n");
const fontSize = parseFloat(font);
const height = getTextHeight(text, fontSize, lineHeight);
const width = getTextWidth(text, font);
const baseline = measureBaseline(text, font, lineHeight);
return { width, height, baseline };
};
export const measureBaseline = (
text: string,
font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"],
wrapInContainer?: boolean,
) => {
const container = document.createElement("div"); const container = document.createElement("div");
container.style.position = "absolute"; container.style.position = "absolute";
container.style.whiteSpace = "pre"; container.style.whiteSpace = "pre";
container.style.font = font; container.style.font = font;
container.style.minHeight = "1em"; container.style.minHeight = "1em";
if (wrapInContainer) {
if (maxWidth) {
const lineHeight = getApproxLineHeight(font);
// since we are adding a span of width 1px later
container.style.maxWidth = `${maxWidth + 1}px`;
container.style.overflow = "hidden"; container.style.overflow = "hidden";
container.style.wordBreak = "break-word"; container.style.wordBreak = "break-word";
container.style.lineHeight = `${String(lineHeight)}px`;
container.style.whiteSpace = "pre-wrap"; container.style.whiteSpace = "pre-wrap";
} }
container.style.lineHeight = String(lineHeight);
container.innerText = text;
// Baseline is important for positioning text on canvas
document.body.appendChild(container); document.body.appendChild(container);
container.innerText = text;
const span = document.createElement("span"); const span = document.createElement("span");
span.style.display = "inline-block"; span.style.display = "inline-block";
@@ -329,169 +295,90 @@ export const measureBaseline = (
span.style.width = "1px"; span.style.width = "1px";
span.style.height = "1px"; span.style.height = "1px";
container.appendChild(span); container.appendChild(span);
let baseline = span.offsetTop + span.offsetHeight; // Baseline is important for positioning text on canvas
const baseline = span.offsetTop + span.offsetHeight;
// since we are adding a span of width 1px
const width = container.offsetWidth + 1;
const height = container.offsetHeight; const height = container.offsetHeight;
if (isSafari) {
const canvasHeight = getTextHeight(text, parseFloat(font), lineHeight);
const fontSize = parseFloat(font);
// In Safari the font size gets rounded off when rendering hence calculating the safari height and shifting the baseline if it differs
// from the actual canvas height
const domHeight = getTextHeight(text, Math.round(fontSize), lineHeight);
if (canvasHeight > height) {
baseline += canvasHeight - domHeight;
}
if (height > canvasHeight) {
baseline -= domHeight - canvasHeight;
}
}
document.body.removeChild(container); document.body.removeChild(container);
return baseline; if (isTestEnv()) {
return { width, height, baseline, container };
}
return { width, height, baseline };
}; };
/** const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
* To get unitless line-height (if unknown) we can calculate it by dividing const cacheApproxLineHeight: { [key: FontString]: number } = {};
* height-per-line by fontSize.
*/
export const detectLineHeight = (textElement: ExcalidrawTextElement) => {
const lineCount = splitIntoLines(textElement.text).length;
return (textElement.height /
lineCount /
textElement.fontSize) as ExcalidrawTextElement["lineHeight"];
};
/** export const getApproxLineHeight = (font: FontString) => {
* We calculate the line height from the font size and the unitless line height, if (cacheApproxLineHeight[font]) {
* aligning with the W3C spec. return cacheApproxLineHeight[font];
*/ }
export const getLineHeightInPx = ( cacheApproxLineHeight[font] = measureText(DUMMY_TEXT, font, null).height;
fontSize: ExcalidrawTextElement["fontSize"], return cacheApproxLineHeight[font];
lineHeight: ExcalidrawTextElement["lineHeight"],
) => {
return fontSize * lineHeight;
};
// FIXME rename to getApproxMinContainerHeight
export const getApproxMinLineHeight = (
fontSize: ExcalidrawTextElement["fontSize"],
lineHeight: ExcalidrawTextElement["lineHeight"],
) => {
return getLineHeightInPx(fontSize, lineHeight) + BOUND_TEXT_PADDING * 2;
}; };
let canvas: HTMLCanvasElement | undefined; let canvas: HTMLCanvasElement | undefined;
const getLineWidth = (text: string, font: FontString) => { const getLineWidth = (text: string, font: FontString) => {
if (!canvas) { if (!canvas) {
canvas = document.createElement("canvas"); canvas = document.createElement("canvas");
} }
const canvas2dContext = canvas.getContext("2d")!; const canvas2dContext = canvas.getContext("2d")!;
canvas2dContext.font = font; canvas2dContext.font = font;
const width = canvas2dContext.measureText(text).width;
const metrics = canvas2dContext.measureText(text);
// since in test env the canvas measureText algo // since in test env the canvas measureText algo
// doesn't measure text and instead just returns number of // doesn't measure text and instead just returns number of
// characters hence we assume that each letteris 10px // characters hence we assume that each letteris 10px
if (isTestEnv()) { if (isTestEnv()) {
return width * 10; return metrics.width * 10;
} }
return width; // Since measureText behaves differently in different browsers
// OS so considering a adjustment factor of 0.2
const adjustmentFactor = 0.2;
return metrics.width + adjustmentFactor;
}; };
export const getTextWidth = (text: string, font: FontString) => { export const getTextWidth = (text: string, font: FontString) => {
const lines = splitIntoLines(text); const lines = text.split("\n");
let width = 0; let width = 0;
lines.forEach((line) => { lines.forEach((line) => {
width = Math.max(width, getLineWidth(line, font)); width = Math.max(width, getLineWidth(line, font));
}); });
return width; return width;
}; };
export const getTextHeight = (
text: string,
fontSize: number,
lineHeight: ExcalidrawTextElement["lineHeight"],
) => {
const lineCount = splitIntoLines(text).length;
return getLineHeightInPx(fontSize, lineHeight) * lineCount;
};
export const parseTokens = (text: string) => {
// Splitting words containing "-" as those are treated as separate words
// by css wrapping algorithm eg non-profit => non-, profit
const words = text.split("-");
if (words.length > 1) {
// non-proft org => ['non-', 'profit org']
words.forEach((word, index) => {
if (index !== words.length - 1) {
words[index] = word += "-";
}
});
}
// Joining the words with space and splitting them again with space to get the
// final list of tokens
// ['non-', 'profit org'] =>,'non- proft org' => ['non-','profit','org']
return words.join(" ").split(" ");
};
export const wrapText = (text: string, font: FontString, maxWidth: number) => { export const wrapText = (text: string, font: FontString, maxWidth: number) => {
// if maxWidth is not finite or NaN which can happen in case of bugs in
// computation, we need to make sure we don't continue as we'll end up
// in an infinite loop
if (!Number.isFinite(maxWidth) || maxWidth < 0) {
return text;
}
const lines: Array<string> = []; const lines: Array<string> = [];
const originalLines = text.split("\n"); const originalLines = text.split("\n");
const spaceWidth = getLineWidth(" ", font); const spaceWidth = getLineWidth(" ", font);
let currentLine = "";
let currentLineWidthTillNow = 0;
const push = (str: string) => { const push = (str: string) => {
if (str.trim()) { if (str.trim()) {
lines.push(str); lines.push(str);
} }
}; };
const resetParams = () => {
currentLine = "";
currentLineWidthTillNow = 0;
};
originalLines.forEach((originalLine) => { originalLines.forEach((originalLine) => {
const currentLineWidth = getTextWidth(originalLine, font); const words = originalLine.split(" ");
// This means its newline so push it
// Push the line if its <= maxWidth if (words.length === 1 && words[0] === "") {
if (currentLineWidth <= maxWidth) { lines.push(words[0]);
lines.push(originalLine);
return; // continue return; // continue
} }
let currentLine = "";
const words = parseTokens(originalLine); let currentLineWidthTillNow = 0;
resetParams();
let index = 0; let index = 0;
while (index < words.length) { while (index < words.length) {
const currentWordWidth = getLineWidth(words[index], font); const currentWordWidth = getLineWidth(words[index], font);
// This will only happen when single word takes entire width
if (currentWordWidth === maxWidth) {
push(words[index]);
index++;
}
// Start breaking longer words exceeding max width // Start breaking longer words exceeding max width
else if (currentWordWidth > maxWidth) { if (currentWordWidth >= maxWidth) {
// push current line since the current word exceeds the max width // push current line since the current word exceeds the max width
// so will be appended in next line // so will be appended in next line
push(currentLine); push(currentLine);
currentLine = "";
resetParams(); currentLineWidthTillNow = 0;
while (words[index].length > 0) { while (words[index].length > 0) {
const currentChar = String.fromCodePoint( const currentChar = String.fromCodePoint(
words[index].codePointAt(0)!, words[index].codePointAt(0)!,
@@ -501,6 +388,10 @@ export const wrapText = (text: string, font: FontString, maxWidth: number) => {
words[index] = words[index].slice(currentChar.length); words[index] = words[index].slice(currentChar.length);
if (currentLineWidthTillNow >= maxWidth) { if (currentLineWidthTillNow >= maxWidth) {
// only remove last trailing space which we have added when joining words
if (currentLine.slice(-1) === " ") {
currentLine = currentLine.slice(0, -1);
}
push(currentLine); push(currentLine);
currentLine = currentChar; currentLine = currentChar;
currentLineWidthTillNow = width; currentLineWidthTillNow = width;
@@ -511,15 +402,16 @@ export const wrapText = (text: string, font: FontString, maxWidth: number) => {
// push current line if appending space exceeds max width // push current line if appending space exceeds max width
if (currentLineWidthTillNow + spaceWidth >= maxWidth) { if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
push(currentLine); push(currentLine);
resetParams(); currentLine = "";
currentLineWidthTillNow = 0;
} else {
// space needs to be appended before next word // space needs to be appended before next word
// as currentLine contains chars which couldn't be appended // as currentLine contains chars which couldn't be appended
// to previous line unless the line ends with hyphen to sync // to previous line
// with css word-wrap
} else if (!currentLine.endsWith("-")) {
currentLine += " "; currentLine += " ";
currentLineWidthTillNow += spaceWidth; currentLineWidthTillNow += spaceWidth;
} }
index++; index++;
} else { } else {
// Start appending words in a line till max width reached // Start appending words in a line till max width reached
@@ -527,39 +419,36 @@ export const wrapText = (text: string, font: FontString, maxWidth: number) => {
const word = words[index]; const word = words[index];
currentLineWidthTillNow = getLineWidth(currentLine + word, font); currentLineWidthTillNow = getLineWidth(currentLine + word, font);
if (currentLineWidthTillNow > maxWidth) { if (currentLineWidthTillNow >= maxWidth) {
push(currentLine); push(currentLine);
resetParams(); currentLineWidthTillNow = 0;
currentLine = "";
break; break;
} }
index++; index++;
currentLine += `${word} `;
// if word ends with "-" then we don't need to add space
// to sync with css word-wrap
const shouldAppendSpace = !word.endsWith("-");
currentLine += word;
if (shouldAppendSpace) {
currentLine += " ";
}
// Push the word if appending space exceeds max width // Push the word if appending space exceeds max width
if (currentLineWidthTillNow + spaceWidth >= maxWidth) { if (currentLineWidthTillNow + spaceWidth >= maxWidth) {
if (shouldAppendSpace) { const word = currentLine.slice(0, -1);
lines.push(currentLine.slice(0, -1)); push(word);
} else { currentLine = "";
lines.push(currentLine); currentLineWidthTillNow = 0;
}
resetParams();
break; break;
} }
} }
if (currentLineWidthTillNow === maxWidth) {
currentLine = "";
currentLineWidthTillNow = 0;
}
} }
} }
if (currentLine.slice(-1) === " ") { if (currentLine) {
// only remove last trailing space which we have added when joining words // only remove last trailing space which we have added when joining words
currentLine = currentLine.slice(0, -1); if (currentLine.slice(-1) === " ") {
currentLine = currentLine.slice(0, -1);
}
push(currentLine); push(currentLine);
} }
}); });
@@ -590,24 +479,22 @@ export const charWidth = (() => {
getCache, getCache,
}; };
})(); })();
export const getApproxMinLineWidth = (font: FontString) => {
const DUMMY_TEXT = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();
// FIXME rename to getApproxMinContainerWidth
export const getApproxMinLineWidth = (
font: FontString,
lineHeight: ExcalidrawTextElement["lineHeight"],
) => {
const maxCharWidth = getMaxCharWidth(font); const maxCharWidth = getMaxCharWidth(font);
if (maxCharWidth === 0) { if (maxCharWidth === 0) {
return ( return (
measureText(DUMMY_TEXT.split("").join("\n"), font, lineHeight).width + measureText(DUMMY_TEXT.split("").join("\n"), font).width +
BOUND_TEXT_PADDING * 2 BOUND_TEXT_PADDING * 2
); );
} }
return maxCharWidth + BOUND_TEXT_PADDING * 2; return maxCharWidth + BOUND_TEXT_PADDING * 2;
}; };
export const getApproxMinLineHeight = (font: FontString) => {
return getApproxLineHeight(font) + BOUND_TEXT_PADDING * 2;
};
export const getMinCharWidth = (font: FontString) => { export const getMinCharWidth = (font: FontString) => {
const cache = charWidth.getCache(font); const cache = charWidth.getCache(font);
if (!cache) { if (!cache) {
@@ -734,26 +621,6 @@ export const getContainerCenter = (
return { x: midSegmentMidpoint[0], y: midSegmentMidpoint[1] }; return { x: midSegmentMidpoint[0], y: midSegmentMidpoint[1] };
}; };
export const getContainerCoords = (container: NonDeletedExcalidrawElement) => {
let offsetX = BOUND_TEXT_PADDING;
let offsetY = BOUND_TEXT_PADDING;
if (container.type === "ellipse") {
// The derivation of coordinates is explained in https://github.com/excalidraw/excalidraw/pull/6172
offsetX += (container.width / 2) * (1 - Math.sqrt(2) / 2);
offsetY += (container.height / 2) * (1 - Math.sqrt(2) / 2);
}
// The derivation of coordinates is explained in https://github.com/excalidraw/excalidraw/pull/6265
if (container.type === "diamond") {
offsetX += container.width / 4;
offsetY += container.height / 4;
}
return {
x: container.x + offsetX,
y: container.y + offsetY,
};
};
export const getTextElementAngle = (textElement: ExcalidrawTextElement) => { export const getTextElementAngle = (textElement: ExcalidrawTextElement) => {
const container = getContainerElement(textElement); const container = getContainerElement(textElement);
if (!container || isArrowElement(container)) { if (!container || isArrowElement(container)) {
@@ -766,13 +633,12 @@ export const getBoundTextElementOffset = (
boundTextElement: ExcalidrawTextElement | null, boundTextElement: ExcalidrawTextElement | null,
) => { ) => {
const container = getContainerElement(boundTextElement); const container = getContainerElement(boundTextElement);
if (!container || !boundTextElement) { if (!container) {
return 0; return 0;
} }
if (isArrowElement(container)) { if (isArrowElement(container)) {
return BOUND_TEXT_PADDING * 8; return BOUND_TEXT_PADDING * 8;
} }
return BOUND_TEXT_PADDING; return BOUND_TEXT_PADDING;
}; };
@@ -790,26 +656,6 @@ export const getBoundTextElementPosition = (
export const shouldAllowVerticalAlign = ( export const shouldAllowVerticalAlign = (
selectedElements: NonDeletedExcalidrawElement[], selectedElements: NonDeletedExcalidrawElement[],
) => {
return selectedElements.some((element) => {
const hasBoundContainer = isBoundToContainer(element);
if (hasBoundContainer) {
const container = getContainerElement(element);
if (
isTextElement(element) &&
isArrowElement(container) &&
container.points.length > 2
) {
return false;
}
return true;
}
return false;
});
};
export const suppportsHorizontalAlign = (
selectedElements: NonDeletedExcalidrawElement[],
) => { ) => {
return selectedElements.some((element) => { return selectedElements.some((element) => {
const hasBoundContainer = isBoundToContainer(element); const hasBoundContainer = isBoundToContainer(element);
@@ -820,8 +666,14 @@ export const suppportsHorizontalAlign = (
} }
return true; return true;
} }
const boundTextElement = getBoundTextElement(element);
return isTextElement(element); if (boundTextElement) {
if (isArrowElement(element)) {
return false;
}
return true;
}
return false;
}); });
}; };
@@ -862,118 +714,12 @@ export const getTextBindableContainerAtPosition = (
return isTextBindableContainer(hitElement, false) ? hitElement : null; return isTextBindableContainer(hitElement, false) ? hitElement : null;
}; };
const VALID_CONTAINER_TYPES = new Set([ export const isValidTextContainer = (element: ExcalidrawElement) => {
"rectangle", return (
"ellipse", element.type === "rectangle" ||
"diamond", element.type === "ellipse" ||
"image", element.type === "diamond" ||
"arrow", isImageElement(element) ||
]); isArrowElement(element)
export const isValidTextContainer = (element: ExcalidrawElement) =>
VALID_CONTAINER_TYPES.has(element.type);
export const computeContainerDimensionForBoundText = (
dimension: number,
containerType: ExtractSetType<typeof VALID_CONTAINER_TYPES>,
) => {
dimension = Math.ceil(dimension);
const padding = BOUND_TEXT_PADDING * 2;
if (containerType === "ellipse") {
return Math.round(((dimension + padding) / Math.sqrt(2)) * 2);
}
if (containerType === "arrow") {
return dimension + padding * 8;
}
if (containerType === "diamond") {
return 2 * (dimension + padding);
}
return dimension + padding;
};
export const getBoundTextMaxWidth = (container: ExcalidrawElement) => {
const width = getContainerDims(container).width;
if (isArrowElement(container)) {
return width - BOUND_TEXT_PADDING * 8 * 2;
}
if (container.type === "ellipse") {
// The width of the largest rectangle inscribed inside an ellipse is
// Math.round((ellipse.width / 2) * Math.sqrt(2)) which is derived from
// equation of an ellipse -https://github.com/excalidraw/excalidraw/pull/6172
return Math.round((width / 2) * Math.sqrt(2)) - BOUND_TEXT_PADDING * 2;
}
if (container.type === "diamond") {
// The width of the largest rectangle inscribed inside a rhombus is
// Math.round(width / 2) - https://github.com/excalidraw/excalidraw/pull/6265
return Math.round(width / 2) - BOUND_TEXT_PADDING * 2;
}
return width - BOUND_TEXT_PADDING * 2;
};
export const getBoundTextMaxHeight = (
container: ExcalidrawElement,
boundTextElement: ExcalidrawTextElementWithContainer,
) => {
const height = getContainerDims(container).height;
if (isArrowElement(container)) {
const containerHeight = height - BOUND_TEXT_PADDING * 8 * 2;
if (containerHeight <= 0) {
return boundTextElement.height;
}
return height;
}
if (container.type === "ellipse") {
// The height of the largest rectangle inscribed inside an ellipse is
// Math.round((ellipse.height / 2) * Math.sqrt(2)) which is derived from
// equation of an ellipse - https://github.com/excalidraw/excalidraw/pull/6172
return Math.round((height / 2) * Math.sqrt(2)) - BOUND_TEXT_PADDING * 2;
}
if (container.type === "diamond") {
// The height of the largest rectangle inscribed inside a rhombus is
// Math.round(height / 2) - https://github.com/excalidraw/excalidraw/pull/6265
return Math.round(height / 2) - BOUND_TEXT_PADDING * 2;
}
return height - BOUND_TEXT_PADDING * 2;
};
export const isMeasureTextSupported = () => {
const width = getTextWidth(
DUMMY_TEXT,
getFontString({
fontSize: DEFAULT_FONT_SIZE,
fontFamily: DEFAULT_FONT_FAMILY,
}),
); );
return width > 0;
};
/**
* Unitless line height
*
* In previous versions we used `normal` line height, which browsers interpret
* differently, and based on font-family and font-size.
*
* To make line heights consistent across browsers we hardcode the values for
* each of our fonts based on most common average line-heights.
* See https://github.com/excalidraw/excalidraw/pull/6360#issuecomment-1477635971
* where the values come from.
*/
const DEFAULT_LINE_HEIGHT = {
// ~1.25 is the average for Virgil in WebKit and Blink.
// Gecko (FF) uses ~1.28.
[FONT_FAMILY.Virgil]: 1.25 as ExcalidrawTextElement["lineHeight"],
// ~1.15 is the average for Virgil in WebKit and Blink.
// Gecko if all over the place.
[FONT_FAMILY.Helvetica]: 1.15 as ExcalidrawTextElement["lineHeight"],
// ~1.2 is the average for Virgil in WebKit and Blink, and kinda Gecko too
[FONT_FAMILY.Cascadia]: 1.2 as ExcalidrawTextElement["lineHeight"],
};
export const getDefaultLineHeight = (fontFamily: FontFamilyValues) => {
if (fontFamily in DEFAULT_LINE_HEIGHT) {
return DEFAULT_LINE_HEIGHT[fontFamily];
}
return DEFAULT_LINE_HEIGHT[DEFAULT_FONT_FAMILY];
}; };
+141 -337
View File
@@ -3,23 +3,19 @@ import ExcalidrawApp from "../excalidraw-app";
import { GlobalTestState, render, screen } from "../tests/test-utils"; import { GlobalTestState, render, screen } from "../tests/test-utils";
import { Keyboard, Pointer, UI } from "../tests/helpers/ui"; import { Keyboard, Pointer, UI } from "../tests/helpers/ui";
import { CODES, KEYS } from "../keys"; import { CODES, KEYS } from "../keys";
import { import { fireEvent } from "../tests/test-utils";
fireEvent,
mockBoundingClientRect,
restoreOriginalGetBoundingClientRect,
} from "../tests/test-utils";
import { queryByText } from "@testing-library/react"; import { queryByText } from "@testing-library/react";
import { FONT_FAMILY, TEXT_ALIGN, VERTICAL_ALIGN } from "../constants"; import { BOUND_TEXT_PADDING, FONT_FAMILY } from "../constants";
import { import {
ExcalidrawTextElement, ExcalidrawTextElement,
ExcalidrawTextElementWithContainer, ExcalidrawTextElementWithContainer,
} from "./types"; } from "./types";
import * as textElementUtils from "./textElement";
import { API } from "../tests/helpers/api"; import { API } from "../tests/helpers/api";
import { mutateElement } from "./mutateElement"; import { mutateElement } from "./mutateElement";
import { resize } from "../tests/utils"; import { resize } from "../tests/utils";
import { getOriginalContainerHeightFromCache } from "./textWysiwyg"; import { getOriginalContainerHeightFromCache } from "./textWysiwyg";
// Unmount ReactDOM from root // Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!); ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
@@ -226,19 +222,11 @@ describe("textWysiwyg", () => {
describe("Test container-unbound text", () => { describe("Test container-unbound text", () => {
const { h } = window; const { h } = window;
const dimensions = { height: 400, width: 800 };
let textarea: HTMLTextAreaElement; let textarea: HTMLTextAreaElement;
let textElement: ExcalidrawTextElement; let textElement: ExcalidrawTextElement;
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => { beforeEach(async () => {
await render(<ExcalidrawApp />); await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
textElement = UI.createElement("text"); textElement = UI.createElement("text");
@@ -248,10 +236,6 @@ describe("textWysiwyg", () => {
)!; )!;
}); });
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should add a tab at the start of the first line", () => { it("should add a tab at the start of the first line", () => {
const event = new KeyboardEvent("keydown", { key: KEYS.TAB }); const event = new KeyboardEvent("keydown", { key: KEYS.TAB });
textarea.value = "Line#1\nLine#2"; textarea.value = "Line#1\nLine#2";
@@ -450,33 +434,23 @@ describe("textWysiwyg", () => {
); );
expect(h.state.zoom.value).toBe(1); expect(h.state.zoom.value).toBe(1);
}); });
it("text should never go beyond max width", async () => {
UI.clickTool("text");
mouse.clickAt(750, 300);
textarea = document.querySelector(
".excalidraw-textEditorContainer > textarea",
)!;
fireEvent.change(textarea, {
target: {
value:
"Excalidraw is an opensource virtual collaborative whiteboard for sketching hand-drawn like diagrams!",
},
});
textarea.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
textarea.blur();
expect(textarea.style.width).toBe("792px");
expect(h.elements[0].width).toBe(1000);
});
}); });
describe("Test container-bound text", () => { describe("Test container-bound text", () => {
let rectangle: any; let rectangle: any;
const { h } = window; const { h } = window;
const DUMMY_HEIGHT = 240;
const DUMMY_WIDTH = 160;
const APPROX_LINE_HEIGHT = 25;
const INITIAL_WIDTH = 10;
beforeAll(() => {
jest
.spyOn(textElementUtils, "getApproxLineHeight")
.mockReturnValue(APPROX_LINE_HEIGHT);
});
beforeEach(async () => { beforeEach(async () => {
await render(<ExcalidrawApp />); await render(<ExcalidrawApp />);
h.elements = []; h.elements = [];
@@ -526,74 +500,6 @@ describe("textWysiwyg", () => {
]); ]);
}); });
it("should set the text element angle to same as container angle when binding to rotated container", async () => {
const rectangle = API.createElement({
type: "rectangle",
width: 90,
height: 75,
angle: 45,
});
h.elements = [rectangle];
mouse.doubleClickAt(rectangle.x + 10, rectangle.y + 10);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(text.type).toBe("text");
expect(text.containerId).toBe(rectangle.id);
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
expect(text.angle).toBe(rectangle.angle);
mouse.down();
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, { target: { value: "Hello World!" } });
await new Promise((r) => setTimeout(r, 0));
editor.blur();
expect(rectangle.boundElements).toStrictEqual([
{ id: text.id, type: "text" },
]);
});
it("should compute the container height correctly and not throw error when height is updated while editing the text", async () => {
const diamond = API.createElement({
type: "diamond",
x: 10,
y: 20,
width: 90,
height: 75,
});
h.elements = [diamond];
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(diamond.id);
API.setSelectedElements([diamond]);
Keyboard.keyPress(KEYS.ENTER);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
const value = new Array(1000).fill("1").join("\n");
// Pasting large text to simulate height increase
expect(() =>
fireEvent.input(editor, { target: { value } }),
).not.toThrow();
expect(diamond.height).toBe(50020);
// Clearing text to simulate height decrease
expect(() =>
fireEvent.input(editor, { target: { value: "" } }),
).not.toThrow();
expect(diamond.height).toBe(70);
});
it("should bind text to container when double clicked on center of transparent container", async () => { it("should bind text to container when double clicked on center of transparent container", async () => {
const rectangle = API.createElement({ const rectangle = API.createElement({
type: "rectangle", type: "rectangle",
@@ -737,11 +643,11 @@ describe("textWysiwyg", () => {
["freedraw", "line"].forEach((type: any) => { ["freedraw", "line"].forEach((type: any) => {
it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => { it(`shouldn't create text element when pressing 'Enter' key on ${type} `, async () => {
h.elements = []; h.elements = [];
const element = UI.createElement(type, { const elemnet = UI.createElement(type, {
width: 100, width: 100,
height: 50, height: 50,
}); });
API.setSelectedElements([element]); API.setSelectedElements([elemnet]);
Keyboard.keyPress(KEYS.ENTER); Keyboard.keyPress(KEYS.ENTER);
expect(h.elements.length).toBe(1); expect(h.elements.length).toBe(1);
}); });
@@ -770,52 +676,6 @@ describe("textWysiwyg", () => {
expect(rectangle.boundElements).toBe(null); expect(rectangle.boundElements).toBe(null);
}); });
it("should bind text to container when triggered via context menu", async () => {
expect(h.elements.length).toBe(1);
expect(h.elements[0].id).toBe(rectangle.id);
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
expect(h.elements.length).toBe(2);
expect(h.elements[1].type).toBe("text");
API.setSelectedElements([h.elements[0], h.elements[1]]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Bind text to the container")!,
);
const text = h.elements[1] as ExcalidrawTextElementWithContainer;
expect(rectangle.boundElements).toStrictEqual([
{ id: h.elements[1].id, type: "text" },
]);
expect(text.containerId).toBe(rectangle.id);
expect(text.verticalAlign).toBe(VERTICAL_ALIGN.MIDDLE);
expect(text.textAlign).toBe(TEXT_ALIGN.CENTER);
expect(text.x).toBe(
h.elements[0].x + h.elements[0].width / 2 - text.width / 2,
);
expect(text.y).toBe(
h.elements[0].y + h.elements[0].height / 2 - text.height / 2,
);
});
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => { it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1); expect(h.elements.length).toBe(1);
@@ -872,6 +732,39 @@ describe("textWysiwyg", () => {
}); });
it("should wrap text and vertcially center align once text submitted", async () => { it("should wrap text and vertcially center align once text submitted", async () => {
jest
.spyOn(textElementUtils, "measureText")
.mockImplementation((text, font, maxWidth) => {
let width = INITIAL_WIDTH;
let height = APPROX_LINE_HEIGHT;
let baseline = 10;
if (!text) {
return {
width,
height,
baseline,
};
}
baseline = 30;
width = DUMMY_WIDTH;
if (text === "Hello \nWorld!") {
height = APPROX_LINE_HEIGHT * 2;
}
if (maxWidth) {
width = maxWidth;
// To capture cases where maxWidth passed is initial width
// due to which the text is not wrapped correctly
if (maxWidth === INITIAL_WIDTH) {
height = DUMMY_HEIGHT;
}
}
return {
width,
height,
baseline,
};
});
expect(h.elements.length).toBe(1); expect(h.elements.length).toBe(1);
Keyboard.keyDown(KEYS.ENTER); Keyboard.keyDown(KEYS.ENTER);
@@ -880,6 +773,11 @@ describe("textWysiwyg", () => {
".excalidraw-textEditorContainer > textarea", ".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement; ) as HTMLTextAreaElement;
// mock scroll height
jest
.spyOn(editor, "scrollHeight", "get")
.mockImplementation(() => APPROX_LINE_HEIGHT * 2);
fireEvent.change(editor, { fireEvent.change(editor, {
target: { target: {
value: "Hello World!", value: "Hello World!",
@@ -894,11 +792,11 @@ describe("textWysiwyg", () => {
expect(text.text).toBe("Hello \nWorld!"); expect(text.text).toBe("Hello \nWorld!");
expect(text.originalText).toBe("Hello World!"); expect(text.originalText).toBe("Hello World!");
expect(text.y).toBe( expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2, rectangle.y + rectangle.height / 2 - (APPROX_LINE_HEIGHT * 2) / 2,
); );
expect(text.x).toBe(25); expect(text.x).toBe(rectangle.x + BOUND_TEXT_PADDING);
expect(text.height).toBe(50); expect(text.height).toBe(APPROX_LINE_HEIGHT * 2);
expect(text.width).toBe(60); expect(text.width).toBe(rectangle.width - BOUND_TEXT_PADDING * 2);
// Edit and text by removing second line and it should // Edit and text by removing second line and it should
// still vertically align correctly // still vertically align correctly
@@ -915,6 +813,11 @@ describe("textWysiwyg", () => {
}, },
}); });
// mock scroll height
jest
.spyOn(editor, "scrollHeight", "get")
.mockImplementation(() => APPROX_LINE_HEIGHT);
editor.style.height = "25px";
editor.dispatchEvent(new Event("input")); editor.dispatchEvent(new Event("input"));
await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0));
@@ -924,12 +827,12 @@ describe("textWysiwyg", () => {
expect(text.text).toBe("Hello"); expect(text.text).toBe("Hello");
expect(text.originalText).toBe("Hello"); expect(text.originalText).toBe("Hello");
expect(text.height).toBe(25);
expect(text.width).toBe(50);
expect(text.y).toBe( expect(text.y).toBe(
rectangle.y + h.elements[0].height / 2 - text.height / 2, rectangle.y + rectangle.height / 2 - APPROX_LINE_HEIGHT / 2,
); );
expect(text.x).toBe(30); expect(text.x).toBe(rectangle.x + BOUND_TEXT_PADDING);
expect(text.height).toBe(APPROX_LINE_HEIGHT);
expect(text.width).toBe(rectangle.width - BOUND_TEXT_PADDING * 2);
}); });
it("should unbind bound text when unbind action from context menu is triggered", async () => { it("should unbind bound text when unbind action from context menu is triggered", async () => {
@@ -1016,8 +919,8 @@ describe("textWysiwyg", () => {
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]); resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
85, 109.5,
4.5, 17,
] ]
`); `);
@@ -1031,8 +934,6 @@ describe("textWysiwyg", () => {
editor.select(); editor.select();
fireEvent.click(screen.getByTitle("Left")); fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
fireEvent.click(screen.getByTitle("Align bottom")); fireEvent.click(screen.getByTitle("Align bottom"));
await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0));
@@ -1043,7 +944,7 @@ describe("textWysiwyg", () => {
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
15, 15,
65, 90,
] ]
`); `);
@@ -1066,7 +967,7 @@ describe("textWysiwyg", () => {
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]); resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
375, 424,
-539, -539,
] ]
`); `);
@@ -1181,9 +1082,9 @@ describe("textWysiwyg", () => {
mouse.moveTo(rectangle.x + 100, rectangle.y + 50); mouse.moveTo(rectangle.x + 100, rectangle.y + 50);
mouse.up(rectangle.x + 100, rectangle.y + 50); mouse.up(rectangle.x + 100, rectangle.y + 50);
expect(rectangle.x).toBe(80); expect(rectangle.x).toBe(80);
expect(rectangle.y).toBe(-40); expect(rectangle.y).toBe(85);
expect(text.x).toBe(85); expect(text.x).toBe(89.5);
expect(text.y).toBe(-35); expect(text.y).toBe(90);
Keyboard.withModifierKeys({ ctrl: true }, () => { Keyboard.withModifierKeys({ ctrl: true }, () => {
Keyboard.keyPress(KEYS.Z); Keyboard.keyPress(KEYS.Z);
@@ -1213,6 +1114,29 @@ describe("textWysiwyg", () => {
}); });
it("should restore original container height and clear cache once text is unbind", async () => { it("should restore original container height and clear cache once text is unbind", async () => {
jest
.spyOn(textElementUtils, "measureText")
.mockImplementation((text, font, maxWidth) => {
let width = INITIAL_WIDTH;
let height = APPROX_LINE_HEIGHT;
let baseline = 10;
if (!text) {
return {
width,
height,
baseline,
};
}
baseline = 30;
width = DUMMY_WIDTH;
height = APPROX_LINE_HEIGHT * 5;
return {
width,
height,
baseline,
};
});
const originalRectHeight = rectangle.height; const originalRectHeight = rectangle.height;
expect(rectangle.height).toBe(originalRectHeight); expect(rectangle.height).toBe(originalRectHeight);
@@ -1226,7 +1150,7 @@ describe("textWysiwyg", () => {
target: { value: "Online whiteboard collaboration made easy" }, target: { value: "Online whiteboard collaboration made easy" },
}); });
editor.blur(); editor.blur();
expect(rectangle.height).toBe(185); expect(rectangle.height).toBe(135);
mouse.select(rectangle); mouse.select(rectangle);
fireEvent.contextMenu(GlobalTestState.canvas, { fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2, button: 2,
@@ -1252,7 +1176,7 @@ describe("textWysiwyg", () => {
editor.blur(); editor.blur();
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]); resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect(rectangle.height).toBe(156); expect(rectangle.height).toBe(215);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null); expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(null);
mouse.select(rectangle); mouse.select(rectangle);
@@ -1264,12 +1188,13 @@ describe("textWysiwyg", () => {
await new Promise((r) => setTimeout(r, 0)); await new Promise((r) => setTimeout(r, 0));
editor.blur(); editor.blur();
expect(rectangle.height).toBe(156); expect(rectangle.height).toBe(215);
// cache updated again // cache updated again
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(156); expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(215);
}); });
it("should reset the container height cache when font properties updated", async () => { //@todo fix this test later once measureText is mocked correctly
it.skip("should reset the container height cache when font properties updated", async () => {
Keyboard.keyPress(KEYS.ENTER); Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75); expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
@@ -1295,42 +1220,7 @@ describe("textWysiwyg", () => {
expect( expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontSize, (h.elements[1] as ExcalidrawTextElementWithContainer).fontSize,
).toEqual(36); ).toEqual(36);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(97);
});
it("should update line height when font family updated", async () => {
Keyboard.keyPress(KEYS.ENTER);
expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75); expect(getOriginalContainerHeightFromCache(rectangle.id)).toBe(75);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
await new Promise((r) => setTimeout(r, 0));
fireEvent.change(editor, { target: { value: "Hello World!" } });
editor.blur();
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).lineHeight,
).toEqual(1.25);
mouse.select(rectangle);
Keyboard.keyPress(KEYS.ENTER);
fireEvent.click(screen.getByTitle(/code/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Cascadia);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).lineHeight,
).toEqual(1.2);
fireEvent.click(screen.getByTitle(/normal/i));
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).fontFamily,
).toEqual(FONT_FAMILY.Helvetica);
expect(
(h.elements[1] as ExcalidrawTextElementWithContainer).lineHeight,
).toEqual(1.15);
}); });
describe("should align correctly", () => { describe("should align correctly", () => {
@@ -1358,7 +1248,7 @@ describe("textWysiwyg", () => {
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
15, 15,
25, 20,
] ]
`); `);
}); });
@@ -1368,8 +1258,8 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Align top")); fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
30, 94.5,
25, 20,
] ]
`); `);
}); });
@@ -1379,22 +1269,22 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Align top")); fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
45, 174,
25, 20,
] ]
`); `);
}); });
it("when center left", async () => { it("when center left", async () => {
fireEvent.click(screen.getByTitle("Center vertically")); fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left")); fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
15, 15,
45, 25,
] ]
`); `);
}); });
it("when center center", async () => { it("when center center", async () => {
@@ -1402,11 +1292,11 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center vertically")); fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
30, -25,
45, 25,
] ]
`); `);
}); });
it("when center right", async () => { it("when center right", async () => {
@@ -1414,11 +1304,11 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center vertically")); fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
45, 174,
45, 25,
] ]
`); `);
}); });
it("when bottom left", async () => { it("when bottom left", async () => {
@@ -1426,120 +1316,34 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Align bottom")); fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
15, 15,
65, 25,
] ]
`); `);
}); });
it("when bottom center", async () => { it("when bottom center", async () => {
fireEvent.click(screen.getByTitle("Center")); fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom")); fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
30, 94.5,
65, 25,
] ]
`); `);
}); });
it("when bottom right", async () => { it("when bottom right", async () => {
fireEvent.click(screen.getByTitle("Right")); fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom")); fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(` expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [ Array [
45, 174,
65, 25,
] ]
`); `);
}); });
}); });
it("should wrap text in a container when wrap text in container triggered from context menu", async () => {
UI.clickTool("text");
mouse.clickAt(20, 30);
const editor = document.querySelector(
".excalidraw-textEditorContainer > textarea",
) as HTMLTextAreaElement;
fireEvent.change(editor, {
target: {
value: "Excalidraw is an opensource virtual collaborative whiteboard",
},
});
editor.dispatchEvent(new Event("input"));
await new Promise((cb) => setTimeout(cb, 0));
editor.select();
fireEvent.click(screen.getByTitle("Left"));
await new Promise((r) => setTimeout(r, 0));
editor.blur();
const textElement = h.elements[1] as ExcalidrawTextElement;
expect(textElement.width).toBe(600);
expect(textElement.height).toBe(25);
expect(textElement.textAlign).toBe(TEXT_ALIGN.LEFT);
expect((textElement as ExcalidrawTextElement).text).toBe(
"Excalidraw is an opensource virtual collaborative whiteboard",
);
API.setSelectedElements([textElement]);
fireEvent.contextMenu(GlobalTestState.canvas, {
button: 2,
clientX: 20,
clientY: 30,
});
const contextMenu = document.querySelector(".context-menu");
fireEvent.click(
queryByText(contextMenu as HTMLElement, "Wrap text in a container")!,
);
expect(h.elements.length).toBe(3);
expect(h.elements[1]).toEqual(
expect.objectContaining({
angle: 0,
backgroundColor: "transparent",
boundElements: [
{
id: h.elements[2].id,
type: "text",
},
],
fillStyle: "hachure",
groupIds: [],
height: 35,
isDeleted: false,
link: null,
locked: false,
opacity: 100,
roughness: 1,
roundness: {
type: 3,
},
strokeColor: "#000000",
strokeStyle: "solid",
strokeWidth: 1,
type: "rectangle",
updated: 1,
version: 1,
width: 610,
x: 15,
y: 25,
}),
);
expect(h.elements[2] as ExcalidrawTextElement).toEqual(
expect.objectContaining({
text: "Excalidraw is an opensource virtual collaborative whiteboard",
verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
boundElements: null,
}),
);
});
}); });
}); });
+82 -61
View File
@@ -11,7 +11,7 @@ import {
isBoundToContainer, isBoundToContainer,
isTextElement, isTextElement,
} from "./typeChecks"; } from "./typeChecks";
import { CLASSES, isSafari, VERTICAL_ALIGN } from "../constants"; import { CLASSES, VERTICAL_ALIGN } from "../constants";
import { import {
ExcalidrawElement, ExcalidrawElement,
ExcalidrawLinearElement, ExcalidrawLinearElement,
@@ -22,20 +22,15 @@ import {
import { AppState } from "../types"; import { AppState } from "../types";
import { mutateElement } from "./mutateElement"; import { mutateElement } from "./mutateElement";
import { import {
getApproxLineHeight,
getBoundTextElementId, getBoundTextElementId,
getContainerCoords, getBoundTextElementOffset,
getContainerDims, getContainerDims,
getContainerElement, getContainerElement,
getTextElementAngle, getTextElementAngle,
getTextWidth, getTextWidth,
measureText,
normalizeText, normalizeText,
redrawTextBoundingBox,
wrapText, wrapText,
getBoundTextMaxHeight,
getBoundTextMaxWidth,
computeContainerDimensionForBoundText,
detectLineHeight,
} from "./textElement"; } from "./textElement";
import { import {
actionDecreaseFontSize, actionDecreaseFontSize,
@@ -43,6 +38,7 @@ import {
} from "../actions/actionProperties"; } from "../actions/actionProperties";
import { actionZoomIn, actionZoomOut } from "../actions/actionCanvas"; import { actionZoomIn, actionZoomOut } from "../actions/actionCanvas";
import App from "../components/App"; import App from "../components/App";
import { getMaxContainerHeight, getMaxContainerWidth } from "./newElement";
import { LinearElementEditor } from "./linearElementEditor"; import { LinearElementEditor } from "./linearElementEditor";
import { parseClipboard } from "../clipboard"; import { parseClipboard } from "../clipboard";
@@ -151,7 +147,9 @@ export const textWysiwyg = ({
return; return;
} }
const { textAlign, verticalAlign } = updatedTextElement; const { textAlign, verticalAlign } = updatedTextElement;
const approxLineHeight = getApproxLineHeight(
getFontString(updatedTextElement),
);
if (updatedTextElement && isTextElement(updatedTextElement)) { if (updatedTextElement && isTextElement(updatedTextElement)) {
let coordX = updatedTextElement.x; let coordX = updatedTextElement.x;
let coordY = updatedTextElement.y; let coordY = updatedTextElement.y;
@@ -159,7 +157,7 @@ export const textWysiwyg = ({
let maxWidth = updatedTextElement.width; let maxWidth = updatedTextElement.width;
let maxHeight = updatedTextElement.height; let maxHeight = updatedTextElement.height;
let textElementWidth = updatedTextElement.width; const width = updatedTextElement.width;
// Set to element height by default since that's // Set to element height by default since that's
// what is going to be used for unbounded text // what is going to be used for unbounded text
let textElementHeight = updatedTextElement.height; let textElementHeight = updatedTextElement.height;
@@ -205,20 +203,16 @@ export const textWysiwyg = ({
} }
} }
maxWidth = getBoundTextMaxWidth(container); maxWidth = getMaxContainerWidth(container);
maxHeight = getBoundTextMaxHeight( maxHeight = getMaxContainerHeight(container);
container,
updatedTextElement as ExcalidrawTextElementWithContainer,
);
// autogrow container height if text exceeds // autogrow container height if text exceeds
if (!isArrowElement(container) && textElementHeight > maxHeight) { if (!isArrowElement(container) && textElementHeight > maxHeight) {
const targetContainerHeight = computeContainerDimensionForBoundText( const diff = Math.min(
textElementHeight, textElementHeight - maxHeight,
container.type, approxLineHeight,
); );
mutateElement(container, { height: containerDims.height + diff });
mutateElement(container, { height: targetContainerHeight });
return; return;
} else if ( } else if (
// autoshrink container height until original container height // autoshrink container height until original container height
@@ -227,23 +221,28 @@ export const textWysiwyg = ({
containerDims.height > originalContainerData.height && containerDims.height > originalContainerData.height &&
textElementHeight < maxHeight textElementHeight < maxHeight
) { ) {
const targetContainerHeight = computeContainerDimensionForBoundText( const diff = Math.min(
textElementHeight, maxHeight - textElementHeight,
container.type, approxLineHeight,
); );
mutateElement(container, { height: targetContainerHeight }); mutateElement(container, { height: containerDims.height - diff });
} }
// update y coord as you type, not needed for arrow as we calculate // Start pushing text upward until a diff of 30px (padding)
// position from the container element for editor and canvas when rendering labelled arrows // is reached
else if (!isArrowElement(container)) { else {
const containerCoords = getContainerCoords(container);
// vertically center align the text // vertically center align the text
if (verticalAlign === VERTICAL_ALIGN.MIDDLE) { if (verticalAlign === VERTICAL_ALIGN.MIDDLE) {
coordY = containerCoords.y + maxHeight / 2 - textElementHeight / 2; if (!isArrowElement(container)) {
coordY =
container.y + containerDims.height / 2 - textElementHeight / 2;
}
} }
if (verticalAlign === VERTICAL_ALIGN.BOTTOM) { if (verticalAlign === VERTICAL_ALIGN.BOTTOM) {
coordY = containerCoords.y + (maxHeight - textElementHeight); coordY =
container.y +
containerDims.height -
textElementHeight -
getBoundTextElementOffset(updatedTextElement);
} }
} }
} }
@@ -266,21 +265,12 @@ export const textWysiwyg = ({
editable.selectionEnd = editable.value.length - diff; editable.selectionEnd = editable.value.length - diff;
} }
const lines = updatedTextElement.originalText.split("\n");
const lineHeight = updatedTextElement.containerId
? approxLineHeight
: updatedTextElement.height / lines.length;
if (!container) { if (!container) {
maxWidth = (appState.width - 8 - viewportX) / appState.zoom.value; maxWidth = (appState.width - 8 - viewportX) / appState.zoom.value;
textElementWidth = Math.min(textElementWidth, maxWidth);
} else {
textElementWidth += 0.5;
}
let lineHeight = updatedTextElement.lineHeight;
// In Safari the font size gets rounded off when rendering hence calculating the line height by rounding off font size
if (isSafari) {
lineHeight = detectLineHeight({
...updatedTextElement,
fontSize: Math.round(updatedTextElement.fontSize),
});
} }
// Make sure text editor height doesn't go beyond viewport // Make sure text editor height doesn't go beyond viewport
@@ -289,13 +279,13 @@ export const textWysiwyg = ({
Object.assign(editable.style, { Object.assign(editable.style, {
font: getFontString(updatedTextElement), font: getFontString(updatedTextElement),
// must be defined *after* font ¯\_(ツ)_/¯ // must be defined *after* font ¯\_(ツ)_/¯
lineHeight, lineHeight: `${lineHeight}px`,
width: `${textElementWidth}px`, width: `${Math.min(width, maxWidth)}px`,
height: `${textElementHeight}px`, height: `${textElementHeight}px`,
left: `${viewportX}px`, left: `${viewportX}px`,
top: `${viewportY}px`, top: `${viewportY}px`,
transform: getTransform( transform: getTransform(
textElementWidth, width,
textElementHeight, textElementHeight,
getTextElementAngle(updatedTextElement), getTextElementAngle(updatedTextElement),
appState, appState,
@@ -309,7 +299,6 @@ export const textWysiwyg = ({
filter: "var(--theme-filter)", filter: "var(--theme-filter)",
maxHeight: `${editorMaxHeight}px`, maxHeight: `${editorMaxHeight}px`,
}); });
editable.scrollTop = 0;
// For some reason updating font attribute doesn't set font family // For some reason updating font attribute doesn't set font family
// hence updating font family explicitly for test environment // hence updating font family explicitly for test environment
if (isTestEnv()) { if (isTestEnv()) {
@@ -377,7 +366,7 @@ export const textWysiwyg = ({
const wrappedText = wrapText( const wrappedText = wrapText(
`${editable.value}${data}`, `${editable.value}${data}`,
font, font,
getBoundTextMaxWidth(container), getMaxContainerWidth(container),
); );
const width = getTextWidth(wrappedText, font); const width = getTextWidth(wrappedText, font);
editable.style.width = `${width}px`; editable.style.width = `${width}px`;
@@ -389,20 +378,55 @@ export const textWysiwyg = ({
id, id,
) as ExcalidrawTextElement; ) as ExcalidrawTextElement;
const font = getFontString(updatedTextElement); const font = getFontString(updatedTextElement);
if (isBoundToContainer(element)) { // using scrollHeight here since we need to calculate
// number of lines so cannot use editable.style.height
// as that gets updated below
// Rounding here so that the lines calculated is more accurate in all browsers.
// The scrollHeight and approxLineHeight differs in diff browsers
// eg it gives 1.05 in firefox for handewritten small font due to which
// height gets updated as lines > 1 and leads to jumping text for first line in bound container
// hence rounding here to avoid that
const lines = Math.round(
editable.scrollHeight / getApproxLineHeight(font),
);
// auto increase height only when lines > 1 so its
// measured correctly and vertically aligns for
// first line as well as setting height to "auto"
// doubles the height as soon as user starts typing
if (isBoundToContainer(element) && lines > 1) {
const container = getContainerElement(element); const container = getContainerElement(element);
let height = "auto";
editable.style.height = "0px";
let heightSet = false;
if (lines === 2) {
const actualLineCount = wrapText(
editable.value,
font,
getMaxContainerWidth(container!),
).split("\n").length;
// This is browser behaviour when setting height to "auto"
// It sets the height needed for 2 lines even if actual
// line count is 1 as mentioned above as well
// hence reducing the height by half if actual line count is 1
// so single line aligns vertically when deleting
if (actualLineCount === 1) {
height = `${editable.scrollHeight / 2}px`;
editable.style.height = height;
heightSet = true;
}
}
const wrappedText = wrapText( const wrappedText = wrapText(
normalizeText(editable.value), normalizeText(editable.value),
font, font,
getBoundTextMaxWidth(container!), getMaxContainerWidth(container!),
);
const { width, height } = measureText(
wrappedText,
font,
updatedTextElement.lineHeight,
); );
const width = getTextWidth(wrappedText, font);
editable.style.width = `${width}px`; editable.style.width = `${width}px`;
editable.style.height = `${height}px`;
if (!heightSet) {
editable.style.height = `${editable.scrollHeight}px`;
}
} }
onChange(normalizeText(editable.value)); onChange(normalizeText(editable.value));
}; };
@@ -439,9 +463,7 @@ export const textWysiwyg = ({
event.code === CODES.BRACKET_RIGHT)) event.code === CODES.BRACKET_RIGHT))
) { ) {
event.preventDefault(); event.preventDefault();
if (event.isComposing) { if (event.shiftKey || event.code === CODES.BRACKET_LEFT) {
return;
} else if (event.shiftKey || event.code === CODES.BRACKET_LEFT) {
outdent(); outdent();
} else { } else {
indent(); indent();
@@ -590,7 +612,6 @@ export const textWysiwyg = ({
), ),
}); });
} }
redrawTextBoundingBox(updateElement, container);
} }
onSubmit({ onSubmit({
-66
View File
@@ -1,66 +0,0 @@
import { API } from "../tests/helpers/api";
import { hasBoundTextElement } from "./typeChecks";
describe("Test TypeChecks", () => {
describe("Test hasBoundTextElement", () => {
it("should return true for text bindable containers with bound text", () => {
expect(
hasBoundTextElement(
API.createElement({
type: "rectangle",
boundElements: [{ type: "text", id: "text-id" }],
}),
),
).toBeTruthy();
expect(
hasBoundTextElement(
API.createElement({
type: "ellipse",
boundElements: [{ type: "text", id: "text-id" }],
}),
),
).toBeTruthy();
expect(
hasBoundTextElement(
API.createElement({
type: "arrow",
boundElements: [{ type: "text", id: "text-id" }],
}),
),
).toBeTruthy();
expect(
hasBoundTextElement(
API.createElement({
type: "image",
boundElements: [{ type: "text", id: "text-id" }],
}),
),
).toBeTruthy();
});
it("should return false for text bindable containers without bound text", () => {
expect(
hasBoundTextElement(
API.createElement({
type: "freedraw",
boundElements: [{ type: "arrow", id: "arrow-id" }],
}),
),
).toBeFalsy();
});
it("should return false for non text bindable containers", () => {
expect(
hasBoundTextElement(
API.createElement({
type: "freedraw",
boundElements: [{ type: "text", id: "text-id" }],
}),
),
).toBeFalsy();
});
});
});
+1 -2
View File
@@ -1,6 +1,5 @@
import { ROUNDNESS } from "../constants"; import { ROUNDNESS } from "../constants";
import { AppState } from "../types"; import { AppState } from "../types";
import { MarkNonNullable } from "../utility-types";
import { import {
ExcalidrawElement, ExcalidrawElement,
ExcalidrawTextElement, ExcalidrawTextElement,
@@ -140,7 +139,7 @@ export const hasBoundTextElement = (
element: ExcalidrawElement | null, element: ExcalidrawElement | null,
): element is MarkNonNullable<ExcalidrawBindableElement, "boundElements"> => { ): element is MarkNonNullable<ExcalidrawBindableElement, "boundElements"> => {
return ( return (
isTextBindableContainer(element) && isBindableElement(element) &&
!!element.boundElements?.some(({ type }) => type === "text") !!element.boundElements?.some(({ type }) => type === "text")
); );
}; };
+1 -7
View File
@@ -6,10 +6,9 @@ import {
THEME, THEME,
VERTICAL_ALIGN, VERTICAL_ALIGN,
} from "../constants"; } from "../constants";
import { MarkNonNullable, ValueOf } from "../utility-types";
export type ChartType = "bar" | "line"; export type ChartType = "bar" | "line";
export type FillStyle = "hachure" | "cross-hatch" | "solid" | "zigzag"; export type FillStyle = "hachure" | "cross-hatch" | "solid";
export type FontFamilyKeys = keyof typeof FONT_FAMILY; export type FontFamilyKeys = keyof typeof FONT_FAMILY;
export type FontFamilyValues = typeof FONT_FAMILY[FontFamilyKeys]; export type FontFamilyValues = typeof FONT_FAMILY[FontFamilyKeys];
export type Theme = typeof THEME[keyof typeof THEME]; export type Theme = typeof THEME[keyof typeof THEME];
@@ -136,11 +135,6 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
verticalAlign: VerticalAlign; verticalAlign: VerticalAlign;
containerId: ExcalidrawGenericElement["id"] | null; containerId: ExcalidrawGenericElement["id"] | null;
originalText: string; originalText: string;
/**
* Unitless line height (aligned to W3C). To get line height in px, multiply
* with font size (using `getLineHeightInPx` helper).
*/
lineHeight: number & { _brand: "unitlessLineHeight" };
}>; }>;
export type ExcalidrawBindableElement = export type ExcalidrawBindableElement =
-3
View File
@@ -1,3 +0,0 @@
import { unstable_createStore } from "jotai";
export const appJotaiStore = unstable_createStore();
+10 -9
View File
@@ -70,7 +70,7 @@ import { decryptData } from "../../data/encryption";
import { resetBrowserStateVersions } from "../data/tabSync"; import { resetBrowserStateVersions } from "../data/tabSync";
import { LocalData } from "../data/LocalData"; import { LocalData } from "../data/LocalData";
import { atom, useAtom } from "jotai"; import { atom, useAtom } from "jotai";
import { appJotaiStore } from "../app-jotai"; import { jotaiStore } from "../../jotai";
export const collabAPIAtom = atom<CollabAPI | null>(null); export const collabAPIAtom = atom<CollabAPI | null>(null);
export const collabDialogShownAtom = atom(false); export const collabDialogShownAtom = atom(false);
@@ -167,7 +167,7 @@ class Collab extends PureComponent<Props, CollabState> {
setUsername: this.setUsername, setUsername: this.setUsername,
}; };
appJotaiStore.set(collabAPIAtom, collabAPI); jotaiStore.set(collabAPIAtom, collabAPI);
this.onOfflineStatusToggle(); this.onOfflineStatusToggle();
if ( if (
@@ -185,7 +185,7 @@ class Collab extends PureComponent<Props, CollabState> {
} }
onOfflineStatusToggle = () => { onOfflineStatusToggle = () => {
appJotaiStore.set(isOfflineAtom, !window.navigator.onLine); jotaiStore.set(isOfflineAtom, !window.navigator.onLine);
}; };
componentWillUnmount() { componentWillUnmount() {
@@ -208,10 +208,10 @@ class Collab extends PureComponent<Props, CollabState> {
} }
} }
isCollaborating = () => appJotaiStore.get(isCollaboratingAtom)!; isCollaborating = () => jotaiStore.get(isCollaboratingAtom)!;
private setIsCollaborating = (isCollaborating: boolean) => { private setIsCollaborating = (isCollaborating: boolean) => {
appJotaiStore.set(isCollaboratingAtom, isCollaborating); jotaiStore.set(isCollaboratingAtom, isCollaborating);
}; };
private onUnload = () => { private onUnload = () => {
@@ -804,7 +804,7 @@ class Collab extends PureComponent<Props, CollabState> {
); );
handleClose = () => { handleClose = () => {
appJotaiStore.set(collabDialogShownAtom, false); jotaiStore.set(collabDialogShownAtom, false);
}; };
setUsername = (username: string) => { setUsername = (username: string) => {
@@ -838,9 +838,10 @@ class Collab extends PureComponent<Props, CollabState> {
/> />
)} )}
{errorMessage && ( {errorMessage && (
<ErrorDialog onClose={() => this.setState({ errorMessage: "" })}> <ErrorDialog
{errorMessage} message={errorMessage}
</ErrorDialog> onClose={() => this.setState({ errorMessage: "" })}
/>
)} )}
</> </>
); );
+1 -2
View File
@@ -10,13 +10,13 @@ import {
shareWindows, shareWindows,
} from "../../components/icons"; } from "../../components/icons";
import { ToolButton } from "../../components/ToolButton"; import { ToolButton } from "../../components/ToolButton";
import { t } from "../../i18n";
import "./RoomDialog.scss"; import "./RoomDialog.scss";
import Stack from "../../components/Stack"; import Stack from "../../components/Stack";
import { AppState } from "../../types"; import { AppState } from "../../types";
import { trackEvent } from "../../analytics"; import { trackEvent } from "../../analytics";
import { getFrame } from "../../utils"; import { getFrame } from "../../utils";
import DialogActionButton from "../../components/DialogActionButton"; import DialogActionButton from "../../components/DialogActionButton";
import { useI18n } from "../../i18n";
const getShareIcon = () => { const getShareIcon = () => {
const navigator = window.navigator as any; const navigator = window.navigator as any;
@@ -51,7 +51,6 @@ const RoomDialog = ({
setErrorMessage: (message: string) => void; setErrorMessage: (message: string) => void;
theme: AppState["theme"]; theme: AppState["theme"];
}) => { }) => {
const { t } = useI18n();
const roomLinkInput = useRef<HTMLInputElement>(null); const roomLinkInput = useRef<HTMLInputElement>(null);
const copyRoomLink = async () => { const copyRoomLink = async () => {
+1 -1
View File
@@ -65,7 +65,7 @@ export const reconcileElements = (
// Mark duplicate for removal as it'll be replaced with the remote element // Mark duplicate for removal as it'll be replaced with the remote element
if (local) { if (local) {
// Unless the remote and local elements are the same element in which case // Unless the ramote and local elements are the same element in which case
// we need to keep it as we'd otherwise discard it from the resulting // we need to keep it as we'd otherwise discard it from the resulting
// array. // array.
if (local[0] === remoteElement) { if (local[0] === remoteElement) {
@@ -1,13 +1,12 @@
import React from "react"; import React from "react";
import { PlusPromoIcon } from "../../components/icons"; import { PlusPromoIcon } from "../../components/icons";
import { useI18n } from "../../i18n"; import { t } from "../../i18n";
import { WelcomeScreen } from "../../packages/excalidraw/index"; import { WelcomeScreen } from "../../packages/excalidraw/index";
import { isExcalidrawPlusSignedUser } from "../app_constants"; import { isExcalidrawPlusSignedUser } from "../app_constants";
export const AppWelcomeScreen: React.FC<{ export const AppWelcomeScreen: React.FC<{
setCollabDialogShown: (toggle: boolean) => any; setCollabDialogShown: (toggle: boolean) => any;
}> = React.memo((props) => { }> = React.memo((props) => {
const { t } = useI18n();
let headingContent; let headingContent;
if (isExcalidrawPlusSignedUser) { if (isExcalidrawPlusSignedUser) {
+14 -18
View File
@@ -1,21 +1,17 @@
import { shield } from "../../components/icons"; import { shield } from "../../components/icons";
import { Tooltip } from "../../components/Tooltip"; import { Tooltip } from "../../components/Tooltip";
import { useI18n } from "../../i18n"; import { t } from "../../i18n";
export const EncryptedIcon = () => { export const EncryptedIcon = () => (
const { t } = useI18n(); <a
className="encrypted-icon tooltip"
return ( href="https://blog.excalidraw.com/end-to-end-encryption/"
<a target="_blank"
className="encrypted-icon tooltip" rel="noopener noreferrer"
href="https://blog.excalidraw.com/end-to-end-encryption/" aria-label={t("encrypted.link")}
target="_blank" >
rel="noopener noreferrer" <Tooltip label={t("encrypted.tooltip")} long={true}>
aria-label={t("encrypted.link")} {shield}
> </Tooltip>
<Tooltip label={t("encrypted.tooltip")} long={true}> </a>
{shield} );
</Tooltip>
</a>
);
};
@@ -6,7 +6,7 @@ import { loadFirebaseStorage, saveFilesToFirebase } from "../data/firebase";
import { FileId, NonDeletedExcalidrawElement } from "../../element/types"; import { FileId, NonDeletedExcalidrawElement } from "../../element/types";
import { AppState, BinaryFileData, BinaryFiles } from "../../types"; import { AppState, BinaryFileData, BinaryFiles } from "../../types";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { useI18n } from "../../i18n"; import { t } from "../../i18n";
import { excalidrawPlusIcon } from "./icons"; import { excalidrawPlusIcon } from "./icons";
import { encryptData, generateEncryptionKey } from "../../data/encryption"; import { encryptData, generateEncryptionKey } from "../../data/encryption";
import { isInitializedImageElement } from "../../element/typeChecks"; import { isInitializedImageElement } from "../../element/typeChecks";
@@ -79,7 +79,6 @@ export const ExportToExcalidrawPlus: React.FC<{
files: BinaryFiles; files: BinaryFiles;
onError: (error: Error) => void; onError: (error: Error) => void;
}> = ({ elements, appState, files, onError }) => { }> = ({ elements, appState, files, onError }) => {
const { t } = useI18n();
return ( return (
<Card color="primary"> <Card color="primary">
<div className="Card-icon">{excalidrawPlusIcon}</div> <div className="Card-icon">{excalidrawPlusIcon}</div>
@@ -1,23 +1,22 @@
import { useSetAtom } from "jotai"; import { useAtom } from "jotai";
import React from "react"; import React from "react";
import { appLangCodeAtom } from ".."; import { langCodeAtom } from "..";
import { defaultLang, useI18n } from "../../i18n"; import * as i18n from "../../i18n";
import { languages } from "../../i18n"; import { languages } from "../../i18n";
export const LanguageList = ({ style }: { style?: React.CSSProperties }) => { export const LanguageList = ({ style }: { style?: React.CSSProperties }) => {
const { t, langCode } = useI18n(); const [langCode, setLangCode] = useAtom(langCodeAtom);
const setLangCode = useSetAtom(appLangCodeAtom);
return ( return (
<select <select
className="dropdown-select dropdown-select__language" className="dropdown-select dropdown-select__language"
onChange={({ target }) => setLangCode(target.value)} onChange={({ target }) => setLangCode(target.value)}
value={langCode} value={langCode}
aria-label={t("buttons.selectLanguage")} aria-label={i18n.t("buttons.selectLanguage")}
style={style} style={style}
> >
<option key={defaultLang.code} value={defaultLang.code}> <option key={i18n.defaultLang.code} value={i18n.defaultLang.code}>
{defaultLang.label} {i18n.defaultLang.label}
</option> </option>
{languages.map((lang) => ( {languages.map((lang) => (
<option key={lang.code} value={lang.code}> <option key={lang.code} value={lang.code}>
-1
View File
@@ -14,7 +14,6 @@ import { encryptData, decryptData } from "../../data/encryption";
import { MIME_TYPES } from "../../constants"; import { MIME_TYPES } from "../../constants";
import { reconcileElements } from "../collab/reconciliation"; import { reconcileElements } from "../collab/reconciliation";
import { getSyncableElements, SyncableExcalidrawElement } from "."; import { getSyncableElements, SyncableExcalidrawElement } from ".";
import { ResolutionType } from "../../utility-types";
// private // private
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
+1 -1
View File
@@ -263,7 +263,7 @@ export const loadScene = async (
await importFromBackend(id, privateKey), await importFromBackend(id, privateKey),
localDataState?.appState, localDataState?.appState,
localDataState?.elements, localDataState?.elements,
{ repairBindings: true, refreshDimensions: false }, { repairBindings: true },
); );
} else { } else {
data = restore(localDataState || null, null, null, { data = restore(localDataState || null, null, null, {
+12 -13
View File
@@ -75,17 +75,15 @@ import { loadFilesFromFirebase } from "./data/firebase";
import { LocalData } from "./data/LocalData"; import { LocalData } from "./data/LocalData";
import { isBrowserStorageStateNewer } from "./data/tabSync"; import { isBrowserStorageStateNewer } from "./data/tabSync";
import clsx from "clsx"; import clsx from "clsx";
import { atom, Provider, useAtom, useAtomValue } from "jotai";
import { jotaiStore, useAtomWithInitialValue } from "../jotai";
import { reconcileElements } from "./collab/reconciliation"; import { reconcileElements } from "./collab/reconciliation";
import { parseLibraryTokensFromUrl, useHandleLibrary } from "../data/library"; import { parseLibraryTokensFromUrl, useHandleLibrary } from "../data/library";
import { AppMainMenu } from "./components/AppMainMenu"; import { AppMainMenu } from "./components/AppMainMenu";
import { AppWelcomeScreen } from "./components/AppWelcomeScreen"; import { AppWelcomeScreen } from "./components/AppWelcomeScreen";
import { AppFooter } from "./components/AppFooter"; import { AppFooter } from "./components/AppFooter";
import { atom, Provider, useAtom, useAtomValue } from "jotai";
import { useAtomWithInitialValue } from "../jotai";
import { appJotaiStore } from "./app-jotai";
import "./index.scss"; import "./index.scss";
import { ResolutionType } from "../utility-types";
polyfill(); polyfill();
@@ -228,15 +226,15 @@ const initializeScene = async (opts: {
return { scene: null, isExternalScene: false }; return { scene: null, isExternalScene: false };
}; };
const detectedLangCode = languageDetector.detect() || defaultLang.code; const currentLangCode = languageDetector.detect() || defaultLang.code;
export const appLangCodeAtom = atom(
Array.isArray(detectedLangCode) ? detectedLangCode[0] : detectedLangCode, export const langCodeAtom = atom(
Array.isArray(currentLangCode) ? currentLangCode[0] : currentLangCode,
); );
const ExcalidrawWrapper = () => { const ExcalidrawWrapper = () => {
const [errorMessage, setErrorMessage] = useState(""); const [errorMessage, setErrorMessage] = useState("");
const [langCode, setLangCode] = useAtom(appLangCodeAtom); const [langCode, setLangCode] = useAtom(langCodeAtom);
// initial state // initial state
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -673,9 +671,10 @@ const ExcalidrawWrapper = () => {
</Excalidraw> </Excalidraw>
{excalidrawAPI && <Collab excalidrawAPI={excalidrawAPI} />} {excalidrawAPI && <Collab excalidrawAPI={excalidrawAPI} />}
{errorMessage && ( {errorMessage && (
<ErrorDialog onClose={() => setErrorMessage("")}> <ErrorDialog
{errorMessage} message={errorMessage}
</ErrorDialog> onClose={() => setErrorMessage("")}
/>
)} )}
</div> </div>
); );
@@ -684,7 +683,7 @@ const ExcalidrawWrapper = () => {
const ExcalidrawApp = () => { const ExcalidrawApp = () => {
return ( return (
<TopErrorBoundary> <TopErrorBoundary>
<Provider unstable_createStore={() => appJotaiStore}> <Provider unstable_createStore={() => jotaiStore}>
<ExcalidrawWrapper /> <ExcalidrawWrapper />
</Provider> </Provider>
</TopErrorBoundary> </TopErrorBoundary>
+47 -2
View File
@@ -18,8 +18,6 @@ interface Window {
EXCALIDRAW_EXPORT_SOURCE: string; EXCALIDRAW_EXPORT_SOURCE: string;
EXCALIDRAW_THROTTLE_RENDER: boolean | undefined; EXCALIDRAW_THROTTLE_RENDER: boolean | undefined;
gtag: Function; gtag: Function;
_paq: any[];
_mtm: any[];
} }
interface CanvasRenderingContext2D { interface CanvasRenderingContext2D {
@@ -52,6 +50,36 @@ interface Clipboard extends EventTarget {
write(data: any[]): Promise<void>; write(data: any[]): Promise<void>;
} }
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
type ValueOf<T> = T[keyof T];
type Merge<M, N> = Omit<M, keyof N> & N;
/** utility type to assert that the second type is a subtype of the first type.
* Returns the subtype. */
type SubtypeOf<Supertype, Subtype extends Supertype> = Subtype;
type ResolutionType<T extends (...args: any) => any> = T extends (
...args: any
) => Promise<infer R>
? R
: any;
// https://github.com/krzkaczor/ts-essentials
type MarkOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
type MarkRequired<T, RK extends keyof T> = Exclude<T, RK> &
Required<Pick<T, RK>>;
type MarkNonNullable<T, K extends keyof T> = {
[P in K]-?: P extends K ? NonNullable<T[P]> : T[P];
} & { [P in keyof T]: T[P] };
type NonOptional<T> = Exclude<T, undefined>;
// PNG encoding/decoding // PNG encoding/decoding
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
type TEXtChunk = { name: "tEXt"; data: Uint8Array }; type TEXtChunk = { name: "tEXt"; data: Uint8Array };
@@ -73,6 +101,23 @@ declare module "png-chunks-extract" {
} }
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// type getter for interface's callable type
// src: https://stackoverflow.com/a/58658851/927631
// -----------------------------------------------------------------------------
type SignatureType<T> = T extends (...args: infer R) => any ? R : never;
type CallableType<T extends (...args: any[]) => any> = (
...args: SignatureType<T>
) => ReturnType<T>;
// --------------------------------------------------------------------------—
// Type for React.forwardRef --- supply only the first generic argument T
type ForwardRef<T, P = any> = Parameters<
CallableType<React.ForwardRefRenderFunction<T, P>>
>[1];
// --------------------------------------------------------------------------—
interface Blob { interface Blob {
handle?: import("browser-fs-acces").FileSystemHandle; handle?: import("browser-fs-acces").FileSystemHandle;
name?: string; name?: string;
-1
View File
@@ -2,7 +2,6 @@ import { AppState } from "./types";
import { ExcalidrawElement } from "./element/types"; import { ExcalidrawElement } from "./element/types";
import { isLinearElement } from "./element/typeChecks"; import { isLinearElement } from "./element/typeChecks";
import { deepCopyElement } from "./element/newElement"; import { deepCopyElement } from "./element/newElement";
import { Mutable } from "./utility-types";
export interface HistoryEntry { export interface HistoryEntry {
appState: ReturnType<typeof clearAppStatePropertiesForHistory>; appState: ReturnType<typeof clearAppStatePropertiesForHistory>;
-16
View File
@@ -1,8 +1,6 @@
import fallbackLangData from "./locales/en.json"; import fallbackLangData from "./locales/en.json";
import percentages from "./locales/percentages.json"; import percentages from "./locales/percentages.json";
import { ENV } from "./constants"; import { ENV } from "./constants";
import { jotaiScope, jotaiStore } from "./jotai";
import { atom, useAtomValue } from "jotai";
const COMPLETION_THRESHOLD = 85; const COMPLETION_THRESHOLD = 85;
@@ -101,8 +99,6 @@ export const setLanguage = async (lang: Language) => {
currentLangData = fallbackLangData; currentLangData = fallbackLangData;
} }
} }
jotaiStore.set(editorLangCodeAtom, lang.code);
}; };
export const getLanguage = () => currentLang; export const getLanguage = () => currentLang;
@@ -147,15 +143,3 @@ export const t = (
} }
return translation; return translation;
}; };
/** @private atom used solely to rerender components using `useI18n` hook */
const editorLangCodeAtom = atom(defaultLang.code);
// Should be used in components that fall under these cases:
// - component is rendered as an <Excalidraw> child
// - component is rendered internally by <Excalidraw>, but the component
// is memoized w/o being updated on `langCode`, `AppState`, or `UIAppState`
export const useI18n = () => {
const langCode = useAtomValue(editorLangCodeAtom, jotaiScope);
return { t, langCode };
};
+2 -2
View File
@@ -1,4 +1,4 @@
import { PrimitiveAtom, unstable_createStore, useAtom } from "jotai"; import { unstable_createStore, useAtom, WritableAtom } from "jotai";
import { useLayoutEffect } from "react"; import { useLayoutEffect } from "react";
export const jotaiScope = Symbol(); export const jotaiScope = Symbol();
@@ -6,7 +6,7 @@ export const jotaiStore = unstable_createStore();
export const useAtomWithInitialValue = < export const useAtomWithInitialValue = <
T extends unknown, T extends unknown,
A extends PrimitiveAtom<T>, A extends WritableAtom<T, T>,
>( >(
atom: A, atom: A,
initialValue: T | (() => T), initialValue: T | (() => T),
+3 -21
View File
@@ -110,7 +110,6 @@
"increaseFontSize": "ØĒŲƒØ¨ŲŠØą Ø­ØŦŲ… Ø§Ų„ØŽØˇ", "increaseFontSize": "ØĒŲƒØ¨ŲŠØą Ø­ØŦŲ… Ø§Ų„ØŽØˇ",
"unbindText": "؁؃ ØąØ¨Øˇ Ø§Ų„Ų†Øĩ", "unbindText": "؁؃ ØąØ¨Øˇ Ø§Ų„Ų†Øĩ",
"bindText": "ØąØ¨Øˇ Ø§Ų„Ų†Øĩ Ø¨Ø§Ų„Ø­Ø§ŲˆŲŠØŠ", "bindText": "ØąØ¨Øˇ Ø§Ų„Ų†Øĩ Ø¨Ø§Ų„Ø­Ø§ŲˆŲŠØŠ",
"createContainerFromText": "",
"link": { "link": {
"edit": "ØĒØšØ¯ŲŠŲ„ Ø§Ų„ØąØ§Ø¨Øˇ", "edit": "ØĒØšØ¯ŲŠŲ„ Ø§Ų„ØąØ§Ø¨Øˇ",
"create": "ØĨŲ†Ø´Ø§ØĄ ØąØ§Ø¨Øˇ", "create": "ØĨŲ†Ø´Ø§ØĄ ØąØ§Ø¨Øˇ",
@@ -193,8 +192,7 @@
"invalidSceneUrl": "ØĒØšØ°Øą Ø§ØŗØĒŲŠØąØ§Ø¯ Ø§Ų„Ų…Ø´Ų‡Ø¯ Ų…Ų† ØšŲ†ŲˆØ§Ų† URL Ø§Ų„Ų…ØĒŲˆŲØą. ØĨŲ…Ø§ ØŖŲ†Ų‡Ø§ Ų…Ø´ŲˆŲ‡ØŠØŒ ØŖŲˆ Ų„Ø§ ØĒØ­ØĒ؈؊ ØšŲ„Ų‰ Ø¨ŲŠØ§Ų†Ø§ØĒ Excalidraw JSON ØĩØ§Ų„Ø­ØŠ.", "invalidSceneUrl": "ØĒØšØ°Øą Ø§ØŗØĒŲŠØąØ§Ø¯ Ø§Ų„Ų…Ø´Ų‡Ø¯ Ų…Ų† ØšŲ†ŲˆØ§Ų† URL Ø§Ų„Ų…ØĒŲˆŲØą. ØĨŲ…Ø§ ØŖŲ†Ų‡Ø§ Ų…Ø´ŲˆŲ‡ØŠØŒ ØŖŲˆ Ų„Ø§ ØĒØ­ØĒ؈؊ ØšŲ„Ų‰ Ø¨ŲŠØ§Ų†Ø§ØĒ Excalidraw JSON ØĩØ§Ų„Ø­ØŠ.",
"resetLibrary": "Ų‡Ø°Ø§ ØŗŲˆŲ ŲŠŲ…ØŗØ­ Ų…ŲƒØĒبØĒ؃. Ų‡Ų„ ØŖŲ†ØĒ Ų…ØĒØŖŲƒØ¯ØŸ", "resetLibrary": "Ų‡Ø°Ø§ ØŗŲˆŲ ŲŠŲ…ØŗØ­ Ų…ŲƒØĒبØĒ؃. Ų‡Ų„ ØŖŲ†ØĒ Ų…ØĒØŖŲƒØ¯ØŸ",
"removeItemsFromsLibrary": "Ø­Ø°Ų {{count}} ØšŲ†ØĩØą (ØšŲ†Ø§ØĩØą) Ų…Ų† Ø§Ų„Ų…ŲƒØĒب؊؟", "removeItemsFromsLibrary": "Ø­Ø°Ų {{count}} ØšŲ†ØĩØą (ØšŲ†Ø§ØĩØą) Ų…Ų† Ø§Ų„Ų…ŲƒØĒب؊؟",
"invalidEncryptionKey": "؅؁ØĒاح Ø§Ų„ØĒØ´ŲŲŠØą ؊ØŦب ØŖŲ† ŲŠŲƒŲˆŲ† Ų…Ų† 22 Ø­ØąŲØ§Ų‹. Ø§Ų„ØĒØšØ§ŲˆŲ† Ø§Ų„Ų…Ø¨Ø§Ø´Øą Ų…ØšØˇŲ„.", "invalidEncryptionKey": "؅؁ØĒاح Ø§Ų„ØĒØ´ŲŲŠØą ؊ØŦب ØŖŲ† ŲŠŲƒŲˆŲ† Ų…Ų† 22 Ø­ØąŲØ§Ų‹. Ø§Ų„ØĒØšØ§ŲˆŲ† Ø§Ų„Ų…Ø¨Ø§Ø´Øą Ų…ØšØˇŲ„."
"collabOfflineWarning": ""
}, },
"errors": { "errors": {
"unsupportedFileType": "Ų†ŲˆØš Ø§Ų„Ų…Ų„Ų ØēŲŠØą Ų…Ø¯ØšŲˆŲ….", "unsupportedFileType": "Ų†ŲˆØš Ø§Ų„Ų…Ų„Ų ØēŲŠØą Ų…Ø¯ØšŲˆŲ….",
@@ -205,22 +203,7 @@
"cannotResolveCollabServer": "ØĒØšØ°Øą Ø§Ų„Ø§ØĒØĩØ§Ų„ Ø¨ØŽØ§Ø¯Ų… Ø§Ų„ØĒØšØ§ŲˆŲ†. Ø§Ų„ØąØŦØ§ØĄ ØĨؚاد؊ ØĒØ­Ų…ŲŠŲ„ Ø§Ų„ØĩŲØ­ØŠ ŲˆØ§Ų„Ų…Ø­Ø§ŲˆŲ„ØŠ Ų…ØąØŠ ØŖØŽØąŲ‰.", "cannotResolveCollabServer": "ØĒØšØ°Øą Ø§Ų„Ø§ØĒØĩØ§Ų„ Ø¨ØŽØ§Ø¯Ų… Ø§Ų„ØĒØšØ§ŲˆŲ†. Ø§Ų„ØąØŦØ§ØĄ ØĨؚاد؊ ØĒØ­Ų…ŲŠŲ„ Ø§Ų„ØĩŲØ­ØŠ ŲˆØ§Ų„Ų…Ø­Ø§ŲˆŲ„ØŠ Ų…ØąØŠ ØŖØŽØąŲ‰.",
"importLibraryError": "ØĒØšØ°Øą ØĒØ­Ų…ŲŠŲ„ Ø§Ų„Ų…ŲƒØĒب؊", "importLibraryError": "ØĒØšØ°Øą ØĒØ­Ų…ŲŠŲ„ Ø§Ų„Ų…ŲƒØĒب؊",
"collabSaveFailed": "ØĒØšØ°Øą Ø§Ų„Ø­ŲØ¸ ؁؊ Ų‚Ø§ØšØ¯ØŠ Ø§Ų„Ø¨ŲŠØ§Ų†Ø§ØĒ. ØĨذا Ø§ØŗØĒŲ…ØąØĒ Ø§Ų„Ų…Ø´Ø§ŲƒŲ„ØŒ ؊؁ØļŲ„ ØŖŲ† ØĒØ­ŲØ¸ Ų…Ų„ŲŲƒ Ų…Ø­Ų„ŲŠØ§ ؃؊ Ų„Ø§ ØĒŲŲ‚Ø¯ ØšŲ…Ų„Ųƒ.", "collabSaveFailed": "ØĒØšØ°Øą Ø§Ų„Ø­ŲØ¸ ؁؊ Ų‚Ø§ØšØ¯ØŠ Ø§Ų„Ø¨ŲŠØ§Ų†Ø§ØĒ. ØĨذا Ø§ØŗØĒŲ…ØąØĒ Ø§Ų„Ų…Ø´Ø§ŲƒŲ„ØŒ ؊؁ØļŲ„ ØŖŲ† ØĒØ­ŲØ¸ Ų…Ų„ŲŲƒ Ų…Ø­Ų„ŲŠØ§ ؃؊ Ų„Ø§ ØĒŲŲ‚Ø¯ ØšŲ…Ų„Ųƒ.",
"collabSaveFailed_sizeExceeded": "ØĒØšØ°Øą Ø§Ų„Ø­ŲØ¸ ؁؊ Ų‚Ø§ØšØ¯ØŠ Ø§Ų„Ø¨ŲŠØ§Ų†Ø§ØĒ، ŲŠØ¨Ø¯Ųˆ ØŖŲ† Ø§Ų„Ų‚Ų…Ø§Ø´ ŲƒØ¨ŲŠØą Ų„Ų„ØēØ§ŲŠØŠØŒ ؊؁ØļŲ‘Ų„ Ø­ŲØ¸ Ø§Ų„Ų…Ų„Ų Ų…Ø­Ų„ŲŠØ§ ؃؊ Ų„Ø§ ØĒŲŲ‚Ø¯ ØšŲ…Ų„Ųƒ.", "collabSaveFailed_sizeExceeded": "ØĒØšØ°Øą Ø§Ų„Ø­ŲØ¸ ؁؊ Ų‚Ø§ØšØ¯ØŠ Ø§Ų„Ø¨ŲŠØ§Ų†Ø§ØĒ، ŲŠØ¨Ø¯Ųˆ ØŖŲ† Ø§Ų„Ų‚Ų…Ø§Ø´ ŲƒØ¨ŲŠØą Ų„Ų„ØēØ§ŲŠØŠØŒ ؊؁ØļŲ‘Ų„ Ø­ŲØ¸ Ø§Ų„Ų…Ų„Ų Ų…Ø­Ų„ŲŠØ§ ؃؊ Ų„Ø§ ØĒŲŲ‚Ø¯ ØšŲ…Ų„Ųƒ."
"brave_measure_text_error": {
"start": "",
"aggressive_block_fingerprint": "",
"setting_enabled": "",
"break": "",
"text_elements": "",
"in_your_drawings": "",
"strongly_recommend": "",
"steps": "",
"how": "",
"disable_setting": "",
"issue": "",
"write": "",
"discord": ""
}
}, },
"toolBar": { "toolBar": {
"selection": "ØĒØ­Ø¯ŲŠØ¯", "selection": "ØĒØ­Ø¯ŲŠØ¯",
@@ -319,8 +302,7 @@
"doubleClick": "Ø§Ų†Ų‚Øą Ų…ØąØĒŲŠŲ†", "doubleClick": "Ø§Ų†Ų‚Øą Ų…ØąØĒŲŠŲ†",
"drag": "Ø§ØŗØ­Ø¨", "drag": "Ø§ØŗØ­Ø¨",
"editor": "Ø§Ų„Ų…Ø­ØąØą", "editor": "Ø§Ų„Ų…Ø­ØąØą",
"editLineArrowPoints": "", "editSelectedShape": "ØĒØšØ¯ŲŠŲ„ Ø§Ų„Ø´ŲƒŲ„ Ø§Ų„Ų…Ø­Ø¯Ø¯ (Ø§Ų„Ų†Øĩ/Ø§Ų„ØŗŲ‡Ų…/Ø§Ų„ØŽØˇ)",
"editText": "",
"github": "ØšØĢØąØĒ ØšŲ„Ų‰ Ų…Ø´ŲƒŲ„ØŠØŸ ØĨØąØŗØ§Ų„", "github": "ØšØĢØąØĒ ØšŲ„Ų‰ Ų…Ø´ŲƒŲ„ØŠØŸ ØĨØąØŗØ§Ų„",
"howto": "اØĒبؚ Ø§Ų„ØĒØšŲ„ŲŠŲ…Ø§ØĒ", "howto": "اØĒبؚ Ø§Ų„ØĒØšŲ„ŲŠŲ…Ø§ØĒ",
"or": "ØŖŲˆ", "or": "ØŖŲˆ",
+3 -21
View File
@@ -110,7 +110,6 @@
"increaseFontSize": "", "increaseFontSize": "",
"unbindText": "", "unbindText": "",
"bindText": "", "bindText": "",
"createContainerFromText": "",
"link": { "link": {
"edit": "", "edit": "",
"create": "", "create": "",
@@ -193,8 +192,7 @@
"invalidSceneUrl": "", "invalidSceneUrl": "",
"resetLibrary": "", "resetLibrary": "",
"removeItemsFromsLibrary": "", "removeItemsFromsLibrary": "",
"invalidEncryptionKey": "", "invalidEncryptionKey": ""
"collabOfflineWarning": ""
}, },
"errors": { "errors": {
"unsupportedFileType": "ĐĸОСи Ņ„Đ°ĐšĐģОв Ņ„ĐžŅ€ĐŧĐ°Ņ‚ ĐŊĐĩ ҁĐĩ ĐŋĐžĐ´Đ´ŅŠŅ€Đļа.", "unsupportedFileType": "ĐĸОСи Ņ„Đ°ĐšĐģОв Ņ„ĐžŅ€ĐŧĐ°Ņ‚ ĐŊĐĩ ҁĐĩ ĐŋĐžĐ´Đ´ŅŠŅ€Đļа.",
@@ -205,22 +203,7 @@
"cannotResolveCollabServer": "", "cannotResolveCollabServer": "",
"importLibraryError": "", "importLibraryError": "",
"collabSaveFailed": "", "collabSaveFailed": "",
"collabSaveFailed_sizeExceeded": "", "collabSaveFailed_sizeExceeded": ""
"brave_measure_text_error": {
"start": "",
"aggressive_block_fingerprint": "",
"setting_enabled": "",
"break": "",
"text_elements": "",
"in_your_drawings": "",
"strongly_recommend": "",
"steps": "",
"how": "",
"disable_setting": "",
"issue": "",
"write": "",
"discord": ""
}
}, },
"toolBar": { "toolBar": {
"selection": "ĐĄĐĩĐģĐĩĐēŅ†Đ¸Ņ", "selection": "ĐĄĐĩĐģĐĩĐēŅ†Đ¸Ņ",
@@ -319,8 +302,7 @@
"doubleClick": "", "doubleClick": "",
"drag": "ĐŋĐģŅŠĐˇĐŊĐĩŅ‚Đĩ", "drag": "ĐŋĐģŅŠĐˇĐŊĐĩŅ‚Đĩ",
"editor": "Đ ĐĩдаĐēŅ‚ĐžŅ€", "editor": "Đ ĐĩдаĐēŅ‚ĐžŅ€",
"editLineArrowPoints": "", "editSelectedShape": "",
"editText": "",
"github": "НаĐŧĐĩŅ€Đ¸Ņ…Ņ‚Đĩ ĐŋŅ€ĐžĐąĐģĐĩĐŧ? ИСĐŋŅ€Đ°Ņ‚ĐĩŅ‚Đĩ", "github": "НаĐŧĐĩŅ€Đ¸Ņ…Ņ‚Đĩ ĐŋŅ€ĐžĐąĐģĐĩĐŧ? ИСĐŋŅ€Đ°Ņ‚ĐĩŅ‚Đĩ",
"howto": "ĐĄĐģĐĩĐ´Đ˛Đ°ĐšŅ‚Đĩ ĐŊĐ°ŅˆĐ¸Ņ‚Đĩ Ņ€ŅŠĐēĐžĐ˛ĐžĐ´ŅŅ‚Đ˛Đ°", "howto": "ĐĄĐģĐĩĐ´Đ˛Đ°ĐšŅ‚Đĩ ĐŊĐ°ŅˆĐ¸Ņ‚Đĩ Ņ€ŅŠĐēĐžĐ˛ĐžĐ´ŅŅ‚Đ˛Đ°",
"or": "иĐģи", "or": "иĐģи",
+3 -21
View File
@@ -110,7 +110,6 @@
"increaseFontSize": "āϞ⧇āĻ–āύ⧀āϰ āĻŽāĻžāĻ¤ā§āϰāĻž āĻŦāĻžā§œāĻžāύ", "increaseFontSize": "āϞ⧇āĻ–āύ⧀āϰ āĻŽāĻžāĻ¤ā§āϰāĻž āĻŦāĻžā§œāĻžāύ",
"unbindText": "", "unbindText": "",
"bindText": "", "bindText": "",
"createContainerFromText": "",
"link": { "link": {
"edit": "āϞāĻŋāĻ™ā§āĻ• āϏāĻ‚āĻļā§‹āϧāύ", "edit": "āϞāĻŋāĻ™ā§āĻ• āϏāĻ‚āĻļā§‹āϧāύ",
"create": "āϞāĻŋāĻ™ā§āĻ• āϤ⧈āϰ⧀", "create": "āϞāĻŋāĻ™ā§āĻ• āϤ⧈āϰ⧀",
@@ -193,8 +192,7 @@
"invalidSceneUrl": "āϏāϰāĻŦāϰāĻžāĻš āĻ•āϰāĻž āϞāĻŋāĻ™ā§āĻ• āĻĨ⧇āϕ⧇ āĻĻ⧃āĻļā§āϝ āϞ⧋āĻĄ āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋ⧎ āĻāϟāĻŋ āĻšāϝāĻŧ āĻŦāĻŋāĻ•ā§ƒāϤ, āĻ…āĻĨāĻŦāĻž āĻŦ⧈āϧ āĻāĻ•ā§āϏāĻ•ā§āϝāĻžāϞāĻŋāĻĄā§āϰ āĻœā§‡āϏāύ āϤāĻĨā§āϝ āύ⧇āχ⧎", "invalidSceneUrl": "āϏāϰāĻŦāϰāĻžāĻš āĻ•āϰāĻž āϞāĻŋāĻ™ā§āĻ• āĻĨ⧇āϕ⧇ āĻĻ⧃āĻļā§āϝ āϞ⧋āĻĄ āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋ⧎ āĻāϟāĻŋ āĻšāϝāĻŧ āĻŦāĻŋāĻ•ā§ƒāϤ, āĻ…āĻĨāĻŦāĻž āĻŦ⧈āϧ āĻāĻ•ā§āϏāĻ•ā§āϝāĻžāϞāĻŋāĻĄā§āϰ āĻœā§‡āϏāύ āϤāĻĨā§āϝ āύ⧇āχ⧎",
"resetLibrary": "āĻāϟāĻŋ āφāĻĒāύāĻžāϰ āϏāĻ‚āĻ—ā§āϰāĻš āĻĒāϰāĻŋāĻˇā§āĻ•āĻžāϰ āĻ•āϰāĻŦ⧇āĨ¤ āφāĻĒāύāĻŋ āĻ•āĻŋ āύāĻŋāĻļā§āϚāĻŋāϤ?", "resetLibrary": "āĻāϟāĻŋ āφāĻĒāύāĻžāϰ āϏāĻ‚āĻ—ā§āϰāĻš āĻĒāϰāĻŋāĻˇā§āĻ•āĻžāϰ āĻ•āϰāĻŦ⧇āĨ¤ āφāĻĒāύāĻŋ āĻ•āĻŋ āύāĻŋāĻļā§āϚāĻŋāϤ?",
"removeItemsFromsLibrary": "āϏāĻ‚āĻ—ā§āϰāĻš āĻĨ⧇āϕ⧇ {{count}} āĻŦāĻ¸ā§āϤ⧁ āĻŦāĻŋā§Ÿā§‹āĻ— āĻ•āϰāĻž āĻšāĻŦ⧇āĨ¤ āφāĻĒāύāĻŋ āĻ•āĻŋ āύāĻŋāĻļā§āϚāĻŋāϤ?", "removeItemsFromsLibrary": "āϏāĻ‚āĻ—ā§āϰāĻš āĻĨ⧇āϕ⧇ {{count}} āĻŦāĻ¸ā§āϤ⧁ āĻŦāĻŋā§Ÿā§‹āĻ— āĻ•āϰāĻž āĻšāĻŦ⧇āĨ¤ āφāĻĒāύāĻŋ āĻ•āĻŋ āύāĻŋāĻļā§āϚāĻŋāϤ?",
"invalidEncryptionKey": "āĻ…āĻŦ⧈āϧ āĻāύāĻ•ā§āϰ⧀āĻĒāĻļāύ āϕ⧀āĨ¤", "invalidEncryptionKey": "āĻ…āĻŦ⧈āϧ āĻāύāĻ•ā§āϰ⧀āĻĒāĻļāύ āϕ⧀āĨ¤"
"collabOfflineWarning": ""
}, },
"errors": { "errors": {
"unsupportedFileType": "āĻ…āϏāĻŽāĻ°ā§āĻĨāĻŋāϤ āĻĢāĻžāχāϞāĨ¤", "unsupportedFileType": "āĻ…āϏāĻŽāĻ°ā§āĻĨāĻŋāϤ āĻĢāĻžāχāϞāĨ¤",
@@ -205,22 +203,7 @@
"cannotResolveCollabServer": "āϕ⧋āĻ˛ā§āϝāĻžāĻŦ āϏāĻžāĻ°ā§āĻ­āĻžāϰ⧇āϰ āϏāĻžāĻĨ⧇ āϏāĻ‚āϝ⧋āĻ— āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋāĨ¤ āĻĒ⧃āĻˇā§āĻ āĻžāϟāĻŋ āĻĒ⧁āύāϰāĻžāϝāĻŧ āϞ⧋āĻĄ āĻ•āϰ⧇ āφāĻŦāĻžāϰ āĻšā§‡āĻˇā§āϟāĻž āĻ•āϰ⧁āύāĨ¤", "cannotResolveCollabServer": "āϕ⧋āĻ˛ā§āϝāĻžāĻŦ āϏāĻžāĻ°ā§āĻ­āĻžāϰ⧇āϰ āϏāĻžāĻĨ⧇ āϏāĻ‚āϝ⧋āĻ— āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋāĨ¤ āĻĒ⧃āĻˇā§āĻ āĻžāϟāĻŋ āĻĒ⧁āύāϰāĻžāϝāĻŧ āϞ⧋āĻĄ āĻ•āϰ⧇ āφāĻŦāĻžāϰ āĻšā§‡āĻˇā§āϟāĻž āĻ•āϰ⧁āύāĨ¤",
"importLibraryError": "āϏāĻ‚āĻ—ā§āϰāĻš āϞ⧋āĻĄ āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋ", "importLibraryError": "āϏāĻ‚āĻ—ā§āϰāĻš āϞ⧋āĻĄ āĻ•āϰāĻž āϝāĻžāϝāĻŧāύāĻŋ",
"collabSaveFailed": "", "collabSaveFailed": "",
"collabSaveFailed_sizeExceeded": "", "collabSaveFailed_sizeExceeded": ""
"brave_measure_text_error": {
"start": "",
"aggressive_block_fingerprint": "",
"setting_enabled": "",
"break": "",
"text_elements": "",
"in_your_drawings": "",
"strongly_recommend": "",
"steps": "",
"how": "",
"disable_setting": "",
"issue": "",
"write": "",
"discord": ""
}
}, },
"toolBar": { "toolBar": {
"selection": "āĻŦāĻžāĻ›āĻžāχ", "selection": "āĻŦāĻžāĻ›āĻžāχ",
@@ -319,8 +302,7 @@
"doubleClick": "", "doubleClick": "",
"drag": "", "drag": "",
"editor": "", "editor": "",
"editLineArrowPoints": "", "editSelectedShape": "",
"editText": "",
"github": "", "github": "",
"howto": "", "howto": "",
"or": "āĻ…āĻĨāĻŦāĻž", "or": "āĻ…āĻĨāĻŦāĻž",

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