lint & format

This commit is contained in:
dwelle
2026-01-24 22:27:43 +01:00
parent be9981bda5
commit 29ba7fe96d
181 changed files with 3968 additions and 2654 deletions
@@ -10,11 +10,11 @@ import { FONT_FAMILY } from "@excalidraw/excalidraw";
`FONT_FAMILY` contains all the font families used in `Excalidraw`. The default families are the following:
| Font Family | Description |
| ----------- | ---------------------- |
| `Excalifont` | The `Hand-drawn` font |
| `Nunito` | The `Normal` Font |
| `Comic Shanns` | The `Code` Font |
| Font Family | Description |
| -------------- | --------------------- |
| `Excalifont` | The `Hand-drawn` font |
| `Nunito` | The `Normal` Font |
| `Comic Shanns` | The `Code` Font |
Pre-selected family is `FONT_FAMILY.Excalifont`, unless it's overriden with `initialData.appState.currentItemFontFamily`.
@@ -13,7 +13,7 @@ Once the callback is triggered, you will need to store the api in state to acces
```jsx showLineNumbers
export default function App() {
const [excalidrawAPI, setExcalidrawAPI] = useState(null);
return <Excalidraw excalidrawAPI={(api)=> setExcalidrawAPI(api)} />;
return <Excalidraw excalidrawAPI={(api) => setExcalidrawAPI(api)} />;
}
```
@@ -362,10 +362,9 @@ This API has the below signature. It sets the `tool` passed in param as the acti
```ts
(
tool: (
| { type: ToolType }
| { type: "custom"; customType: string }
) & { locked?: boolean },
tool: ({ type: ToolType } | { type: "custom"; customType: string }) & {
locked?: boolean;
},
) => {};
```
@@ -1,7 +1,15 @@
# initialData
<pre>
&#123; elements?: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ExcalidrawElement[]</a>, appState?: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">AppState</a> &#125;
&#123; elements?:{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">
ExcalidrawElement[]
</a>
, appState?:{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">
AppState
</a>{" "}
&#125;
</pre>
This helps to load Excalidraw with `initialData`. It must be an object or a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise) which resolves to an object containing the below optional fields.
@@ -46,7 +54,7 @@ function App() {
},
],
appState: { zenModeEnabled: true, viewBackgroundColor: "#a5d8ff" },
scrollToContent: true
scrollToContent: true,
}}
/>
</div>
@@ -3,7 +3,7 @@
All `props` are _optional_.
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| --- | --- | --- | --- | --- |
| [`initialData`](/docs/@excalidraw/excalidraw/api/props/initialdata) | `object` &#124; `null` &#124; <code>Promise<object &#124; null></code> | `null` | The initial data with which app loads. |
| [`excalidrawAPI`](/docs/@excalidraw/excalidraw/api/props/excalidraw-api) | `function` | \_ | Callback triggered with the excalidraw api once rendered |
| [`isCollaborating`](#iscollaborating) | `boolean` | \_ | This indicates if the app is in `collaboration` mode |
@@ -31,7 +31,7 @@ All `props` are _optional_.
| [`generateIdForFile`](#generateidforfile) | `function` | \_ | Allows you to override `id` generation for files added on canvas |
| [`validateEmbeddable`](#validateembeddable) | `string[]` \| `boolean` \| `RegExp` \| `RegExp[]` \| <code>((link: string) => boolean &#124; undefined)</code> | \_ | use for custom src url validation |
| [`renderEmbeddable`](/docs/@excalidraw/excalidraw/api/props/render-props#renderEmbeddable) | `function` | \_ | Render function that can override the built-in `<iframe>` |
| [`renderScrollbars`] | `boolean`| | `false` | Indicates whether scrollbars will be shown
| [`renderScrollbars`] | `boolean` | | `false` | Indicates whether scrollbars will be shown |
### Storing custom data on Excalidraw elements
@@ -247,7 +247,7 @@ This prop indicates whether to `focus` the Excalidraw component on page load. De
Allows you to override `id` generation for files added on canvas (images). By default, an SHA-1 digest of the file is used.
```tsx
(file: File) => string | Promise<string>
(file: File) => string | Promise<string>;
```
### validateEmbeddable
@@ -65,7 +65,7 @@ If user choses to `dock` the sidebar, it will push the right part of the UI towa
function App() {
return (
<div style={{ height: "500px" }}>
<Excalidraw UIOptions={{dockedSidebarBreakpoint: 200}}/>
<Excalidraw UIOptions={{ dockedSidebarBreakpoint: 200 }} />
</div>
);
}
@@ -73,9 +73,8 @@ function App() {
## tools
This `prop` controls the visibility of the tools in the editor.
Currently you can control the visibility of `image` tool via this prop.
This `prop` controls the visibility of the tools in the editor. Currently you can control the visibility of `image` tool via this prop.
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| image | boolean | true | Decides whether `image` tool should be visible.
| Prop | Type | Default | Description |
| ----- | ------- | ------- | ----------------------------------------------- |
| image | boolean | true | Decides whether `image` tool should be visible. |
@@ -14,35 +14,44 @@ We're working on much improved export utilities. Stay tuned!
**_Signature_**
<pre>
exportToCanvas(&#123;<br/>&nbsp;
elements,<br/>&nbsp;
appState<br/>&nbsp;
getDimensions,<br/>&nbsp;
files,<br/>&nbsp;
exportPadding?: number;<br/>
&#125;: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/utils/export.ts#L24">ExportOpts</a>
exportToCanvas(&#123;
<br />
&nbsp; elements,
<br />
&nbsp; appState
<br />
&nbsp; getDimensions,
<br />
&nbsp; files,
<br />
&nbsp; exportPadding?: number;
<br />
&#125;:{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/utils/export.ts#L24">
ExportOpts
</a>
</pre>
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `elements` | [Excalidraw Element []](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114) | | The elements to be exported to canvas. |
| `appState` | [AppState](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/packages/utils.ts#L23) | [Default App State](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/appState.ts#L17) | The app state of the scene. |
| [`getDimensions`](#getdimensions) | `function` | _ | A function which returns the `width`, `height`, and optionally `scale` (defaults to `1`), with which canvas is to be exported. |
| `maxWidthOrHeight` | `number` | _ | The maximum `width` or `height` of the exported image. If provided, `getDimensions` is ignored. |
| `files` | [BinaryFiles](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L59) | _ | The files added to the scene. |
| [`getDimensions`](#getdimensions) | `function` | \_ | A function which returns the `width`, `height`, and optionally `scale` (defaults to `1`), with which canvas is to be exported. |
| `maxWidthOrHeight` | `number` | \_ | The maximum `width` or `height` of the exported image. If provided, `getDimensions` is ignored. |
| `files` | [BinaryFiles](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L59) | \_ | The files added to the scene. |
| `exportPadding` | `number` | `10` | The `padding` to be added on canvas. |
#### getDimensions
```tsx
(width: number, height: number) => {
(width: number, height: number) => {
width: number,
height: number,
scale?: number
height: number,
scale?: number
}
```
A function which returns the `width`, `height`, and optionally `scale` (defaults to `1`), with which canvas is to be exported.
A function which returns the `width`, `height`, and optionally `scale` (defaults to `1`), with which canvas is to be exported.
**How to use**
@@ -57,17 +66,17 @@ function App() {
const [canvasUrl, setCanvasUrl] = useState("");
const [excalidrawAPI, setExcalidrawAPI] = useState(null);
return (
return (
<>
<button
className="custom-button"
onClick={async () => {
if (!excalidrawAPI) {
return
return;
}
const elements = excalidrawAPI.getSceneElements();
if (!elements || !elements.length) {
return
return;
}
const canvas = await exportToCanvas({
elements,
@@ -76,7 +85,9 @@ function App() {
exportWithDarkMode: false,
},
files: excalidrawAPI.getFiles(),
getDimensions: () => { return {width: 350, height: 350}}
getDimensions: () => {
return { width: 350, height: 350 };
},
});
const ctx = canvas.getContext("2d");
ctx.font = "30px Virgil";
@@ -90,15 +101,13 @@ function App() {
<img src={canvasUrl} alt="" />
</div>
<div style={{ height: "400px" }}>
<Excalidraw excalidrawAPI={(api) => setExcalidrawAPI(api)}
/>
<Excalidraw excalidrawAPI={(api) => setExcalidrawAPI(api)} />
</div>
</>
)
);
}
```
### exportToBlob
**_Signature_**
@@ -114,7 +123,7 @@ exportToBlob(<br/>&nbsp;
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `opts` | `object` | _ | This param is passed to `exportToCanvas`. You can refer to [`exportToCanvas`](#exporttocanvas) |
| `opts` | `object` | \_ | This param is passed to `exportToCanvas`. You can refer to [`exportToCanvas`](#exporttocanvas) |
| `mimeType` | `string` | `image/png` | Indicates the image format. |
| `quality` | `number` | `0.92` | A value between `0` and `1` indicating the [image quality](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#parameters). Applies only to `image/jpeg`/`image/webp` MIME types. |
| `exportPadding` | `number` | `10` | The padding to be added on canvas. |
@@ -132,26 +141,34 @@ Returns a promise which resolves with a [blob](https://developer.mozilla.org/en-
**_Signature_**
<pre>
exportToSvg(&#123;<br/>&nbsp;
elements:&nbsp;
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">
ExcalidrawElement[]
</a>,<br/>&nbsp;
appState:
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95"> AppState
</a>,<br/>&nbsp;
exportPadding: number,<br/>&nbsp;
metadata: string,<br/>&nbsp;
files:&nbsp;
exportToSvg(&#123;
<br />
&nbsp; elements:&nbsp;
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">
ExcalidrawElement[]
</a>
,<br />
&nbsp; appState:
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">
{" "}
AppState
</a>
,<br />
&nbsp; exportPadding: number,
<br />
&nbsp; metadata: string,
<br />
&nbsp; files:&nbsp;
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L59">
BinaryFiles
</a>,<br/>
&#125;);
BinaryFiles
</a>
,<br />
&#125;);
</pre>
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| elements | [Excalidraw Element []](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114) | | The elements to exported as `svg `|
| elements | [Excalidraw Element []](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114) | | The elements to exported as `svg ` |
| appState | [AppState](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95) | [defaultAppState](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/appState.ts#L11) | The `appState` of the scene |
| exportPadding | number | 10 | The `padding` to be added on canvas |
| files | [BinaryFiles](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L64) | undefined | The `files` added to the scene. |
@@ -176,7 +193,7 @@ exportToClipboard(<br/>&nbsp;
| `opts` | | | This param is same as the params passed to `exportToCanvas`. You can refer to [`exportToCanvas`](#exporttocanvas). |
| `mimeType` | `string` | `image/png` | Indicates the image format, this will be used when exporting as `png`. |
| `quality` | `number` | `0.92` | A value between `0` and `1` indicating the [image quality](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#parameters). Applies only to `image/jpeg` / `image/webp` MIME types. This will be used when exporting as `png`. |
| `type` | 'png' &#124; 'svg' &#124; 'json' | _ | This determines the format to which the scene data should be `exported`. |
| `type` | 'png' &#124; 'svg' &#124; 'json' | \_ | This determines the format to which the scene data should be `exported`. |
**How to use**
@@ -20,8 +20,7 @@ import { restoreAppState } from "@excalidraw/excalidraw";
This function will make sure all the `keys` have appropriate `values` in [appState](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95) and if any key is missing, it will be set to its `default` value.
When `localAppState` is supplied, it's used in place of values that are missing (`undefined`) in `appState` instead of the defaults.
Use this as a way to not override user's defaults if you persist them.
You can pass `null` / `undefined` if not applicable.
Use this as a way to not override user's defaults if you persist them. You can pass `null` / `undefined` if not applicable.
### restoreElements
@@ -36,10 +35,10 @@ restoreElements(
</pre>
| Prop | Type | Description |
| ---- | ---- | ---- |
| --- | --- | --- |
| `elements` | <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/element/types.ts#L114">ImportedDataState["elements"]</a> | The `elements` to be restored |
| [`localElements`](#localelements) | <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/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`](#localelements) | <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/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
@@ -47,13 +46,14 @@ When `localElements` are supplied, they are used to ensure that existing restore
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|
| --- | --- | ------|
| 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. |
| `normalizeIndices` |`boolean` | Indicates whether _fractional indices_ for the elements should be normalized. This is to prevent possible issues caused by using stale (too old, too long) indices. |
| `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. |
| `normalizeIndices` | `boolean` | Indicates whether _fractional indices_ for the elements should be normalized. This is to prevent possible issues caused by using stale (too old, too long) indices. |
**_How to use_**
@@ -94,8 +94,12 @@ This function makes sure elements and state is set to appropriate values and set
**_Signature_**
<pre>
restoreLibraryItems(libraryItems: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L34">ImportedDataState["libraryItems"]</a>,<br/>&nbsp;
defaultStatus: "published" | "unpublished")
restoreLibraryItems(libraryItems:{" "}
<a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/types.ts#L34">
ImportedDataState["libraryItems"]
</a>
,<br />
&nbsp; defaultStatus: "published" | "unpublished")
</pre>
**_How to use_**
@@ -38,6 +38,7 @@ For a complete list of variables, check [theme.scss](https://github.com/excalidr
--color-primary-light: #dcbec9;
}
```
```tsx live
function App() {
return (
@@ -23,7 +23,7 @@ To start the example app using the `@excalidraw/excalidraw` package, follow the
```
[http://localhost:3001](http://localhost:3001) will open in your default browser.
This is the same example as the [CodeSandbox](https://codesandbox.io/p/sandbox/github/excalidraw/excalidraw/tree/master/examples/with-script-in-browser) example.
## Releasing
+4 -9
View File
@@ -6,21 +6,17 @@ No, Excalidraw package doesn't come with collaboration built in, since the imple
### 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.
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)
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**
![Aggressive block fingerprinting](../../assets/aggressive-block-fingerprint.png)
2. Once opened, look for **Aggressively Block Fingerprinting** ![Aggressive block fingerprinting](../../assets/aggressive-block-fingerprint.png)
3. Switch to **Block Fingerprinting**
![Block filtering](../../assets/block-fingerprint.png)
3. Switch to **Block Fingerprinting** ![Block filtering](../../assets/block-fingerprint.png)
4. Thats all. All text elements should be fixed now 🎉
@@ -28,7 +24,6 @@ We strongly recommend turning it off. You can follow the steps below on how to d
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).
### ReferenceError: process is not defined
When using `vite` or any build tools, you will have to make sure the `process` is accessible as we are accessing `process.env.IS_PREACT` to decide whether to use `preact` build.
@@ -31,9 +31,7 @@ or, if you serve your assets from the root of your CDN, you would do:
```js
// Vanilla
<head>
<script>
window.EXCALIDRAW_ASSET_PATH = "https://my.cdn.com/assets/";
</script>
<script>window.EXCALIDRAW_ASSET_PATH = "https://my.cdn.com/assets/";</script>
</head>
```
@@ -41,8 +39,8 @@ or, if you prefer the path to be dynamicly set based on the `location.origin`, y
```jsx
// Next.js
<Script id="load-env-variables" strategy="beforeInteractive" >
{ `window["EXCALIDRAW_ASSET_PATH"] = location.origin;` } // or use just "/"!
<Script id="load-env-variables" strategy="beforeInteractive">
{`window["EXCALIDRAW_ASSET_PATH"] = location.origin;`} // or use just "/"!
</Script>
```
@@ -12,8 +12,7 @@ import { Excalidraw } from "@excalidraw/excalidraw";
Throughout the documentation we use live, editable Excalidraw examples like the one shown below.
While we aim for the examples to closely reflect what you'd get if you rendered it yourself, we actually initialize it with some props behind the scenes.
For example, we're passing a `theme` prop to it based on the current color theme of the docs you're just reading.
While we aim for the examples to closely reflect what you'd get if you rendered it yourself, we actually initialize it with some props behind the scenes. For example, we're passing a `theme` prop to it based on the current color theme of the docs you're just reading.
:::
@@ -58,80 +57,76 @@ If you are using `pages router` then importing the wrapper dynamically would wor
<Tabs>
<TabItem value="Excalidraw Wrapper" label="Excalidraw Wrapper" >
```jsx showLineNumbers
"use client";
import { Excalidraw, convertToExcalidrawElements } from "@excalidraw/excalidraw";
```jsx showLineNumbers
"use client";
import { Excalidraw, convertToExcalidrawElements } from "@excalidraw/excalidraw";
import "@excalidraw/excalidraw/index.css";
import "@excalidraw/excalidraw/index.css";
const ExcalidrawWrapper: React.FC = () => {
console.info(convertToExcalidrawElements([{
type: "rectangle",
id: "rect-1",
width: 186.47265625,
height: 141.9765625,
},]));
return (
<div style={{height:"500px", width:"500px"}}>
<Excalidraw />
</div>
);
};
export default ExcalidrawWrapper;
```
const ExcalidrawWrapper: React.FC = () => {
console.info(convertToExcalidrawElements([{
type: "rectangle",
id: "rect-1",
width: 186.47265625,
height: 141.9765625,
},]));
return (
<div style={{height:"500px", width:"500px"}}>
<Excalidraw />
</div>
);
};
export default ExcalidrawWrapper;
```
</TabItem>
<TabItem value="pages" label="Pages router">
```jsx showLineNumbers
import dynamic from "next/dynamic";
```jsx showLineNumbers
import dynamic from "next/dynamic";
// Since client components get prerenderd on server as well hence importing
// the excalidraw stuff dynamically with ssr false
// Since client components get prerenderd on server as well hence importing
// the excalidraw stuff dynamically with ssr false
const ExcalidrawWrapper = dynamic(
async () => (await import("../excalidrawWrapper")).default,
{
ssr: false,
},
);
const ExcalidrawWrapper = dynamic(
async () => (await import("../excalidrawWrapper")).default,
{
ssr: false,
},
);
export default function Page() {
return <ExcalidrawWrapper />;
}
```
export default function Page() {
return (
<ExcalidrawWrapper />
);
}
```
</TabItem>
<TabItem value="app" label="App router">
```jsx showLineNumbers
import dynamic from "next/dynamic";
```jsx showLineNumbers
import dynamic from "next/dynamic";
// Since client components get prerenderd on server as well hence importing
// the excalidraw stuff dynamically with ssr false
// Since client components get prerenderd on server as well hence importing
// the excalidraw stuff dynamically with ssr false
const ExcalidrawWrapper = dynamic(
async () => (await import("../excalidrawWrapper")).default,
{
ssr: false,
},
);
const ExcalidrawWrapper = dynamic(
async () => (await import("../excalidrawWrapper")).default,
{
ssr: false,
},
);
export default function Page() {
return (
<ExcalidrawWrapper />
);
}
```
export default function Page() {
return <ExcalidrawWrapper />;
}
```
</TabItem>
</Tabs>
{/* Link should be updated to point to the latest! */}
Here is a [source code](https://github.com/excalidraw/excalidraw/tree/master/examples/with-nextjs) for the example with app and pages router. You you can try it out [here](https://excalidraw-package-example-with-nextjs.vercel.app/).
{/* Link should be updated to point to the latest! */} Here is a [source code](https://github.com/excalidraw/excalidraw/tree/master/examples/with-nextjs) for the example with app and pages router. You you can try it out [here](https://excalidraw-package-example-with-nextjs.vercel.app/).
The `types` are available at `@excalidraw/excalidraw/types`, check [CodeSandbox](https://codesandbox.io/p/sandbox/github/excalidraw/excalidraw/tree/master/examples/with-script-in-browser) example for details.
@@ -154,6 +149,7 @@ Since Vite removes env variables by default, you can update the vite config to e
"process.env.IS_PREACT": JSON.stringify("true"),
},
```
:::
## Browser
@@ -180,15 +176,16 @@ import TabItem from "@theme/TabItem";
/>
<link rel="stylesheet" href="./index.css" />
<script>
window.EXCALIDRAW_ASSET_PATH = "https://esm.sh/@excalidraw/excalidraw@0.18.0/dist/prod/";
</script>
window.EXCALIDRAW_ASSET_PATH =
"https://esm.sh/@excalidraw/excalidraw@0.18.0/dist/prod/";
</script>
<script type="importmap">
{
"imports": {
"react": "https://esm.sh/react@19.0.0",
"react/jsx-runtime": "https://esm.sh/react@19.0.0/jsx-runtime",
"react-dom": "https://esm.sh/react-dom@19.0.0"
}
}
}
</script>
</head>
@@ -208,9 +205,9 @@ import TabItem from "@theme/TabItem";
```js showLineNumbers
// See https://www.npmjs.com/package/@excalidraw/excalidraw documentation.
import * as ExcalidrawLib from 'https://esm.sh/@excalidraw/excalidraw@0.18.0/dist/dev/index.js?external=react,react-dom';
import * as ExcalidrawLib from "https://esm.sh/@excalidraw/excalidraw@0.18.0/dist/dev/index.js?external=react,react-dom";
import React from "https://esm.sh/react@19.0.0";
import ReactDOM from "https://esm.sh/react-dom@19.0.0"
import ReactDOM from "https://esm.sh/react-dom@19.0.0";
window.ExcalidrawLib = ExcalidrawLib;
console.log("Excalidraw library", ExcalidrawLib);
@@ -41,18 +41,24 @@ flowchart TD
C -->|One| D[Laptop]
C -->|Two| E[iPhone]
C -->|Three| F[Car]
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/c8ea84fc-e9fb-4652-9a12-154136d1a798" width="250" height="200"/>
```
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/c8ea84fc-e9fb-4652-9a12-154136d1a798"
width="250"
height="200"
/>
```
flowchart LR
id1((Hello from Circle))
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/6202a8b9-8aa7-451e-9478-4d8d75c0f2fa" width="250" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/6202a8b9-8aa7-451e-9478-4d8d75c0f2fa"
width="250"
height="200"
/>
#### Subgraphs
@@ -72,7 +78,11 @@ flowchart TB
end
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/098bce52-8f93-437c-9a06-c6972e27c70a" width="350" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/098bce52-8f93-437c-9a06-c6972e27c70a"
width="350"
height="200"
/>
#### Unsupported shapes fallback to Rectangle
@@ -87,9 +97,14 @@ flowchart LR
id5[/Parallelogram fallback to Rectangle /]
id6[/Trapezoid fallback to Rectangle\]
```
The above shapes are not supported in Excalidraw hence they fallback to Rectangle
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/cb269473-16c5-4c35-bd7a-d631d8cc5b47" width="350" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/cb269473-16c5-4c35-bd7a-d631d8cc5b47"
width="350"
height="200"
/>
#### Markdown fallback to Regular text
@@ -99,7 +114,12 @@ Since we don't support wysiwyg text editor yet, hence [Markdown Strings](https:/
flowchart LR
A("`Hello **World**`") --> B("`Whats **up** ?`")
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/107bd428-9ab9-42d4-ba12-b1e29c8db478" width="250" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/107bd428-9ab9-42d4-ba12-b1e29c8db478"
width="250"
height="200"
/>
#### Basic FontAwesome fallback to text
@@ -112,8 +132,11 @@ flowchart TD
B-->E(A fa:fa-camera-retro perhaps?)
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/7a693863-c3f9-42ff-b325-4b3f8303c7af" width="250" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/7a693863-c3f9-42ff-b325-4b3f8303c7af"
width="250"
height="200"
/>
#### Cross Arrow head fallback to Bar Arrow head
@@ -121,8 +144,12 @@ flowchart TD
flowchart LR
Start x--x Stop
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/217dd1ad-7f4e-4c80-8c1c-03647b42d821" width="250" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/217dd1ad-7f4e-4c80-8c1c-03647b42d821"
width="250"
height="200"
/>
## Unsupported Diagram Types
@@ -135,7 +162,11 @@ erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : uses
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/c1d3fdb3-32ef-4bf3-a38a-02ac3d7d2cb9" width="300" height="200"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/c1d3fdb3-32ef-4bf3-a38a-02ac3d7d2cb9"
width="300"
height="200"
/>
```
gitGraph
@@ -152,4 +183,8 @@ gitGraph
```
<img src="https://github.com/excalidraw/excalidraw/assets/11256141/e5dcec0b-d570-4eb4-b981-412a996aa96c" width="400" height="300"/>
<img
src="https://github.com/excalidraw/excalidraw/assets/11256141/e5dcec0b-d570-4eb4-b981-412a996aa96c"
width="400"
height="300"
/>
@@ -2,6 +2,6 @@
The Codebase is divided into 2 Sections
* [How Parser Works under the hood](/docs/@excalidraw/mermaid-to-excalidraw/codebase/parser) - If you are interested in understanding and deep diving into inner workings of the Parser, then make sure to checkout this section.
- [How Parser Works under the hood](/docs/@excalidraw/mermaid-to-excalidraw/codebase/parser) - If you are interested in understanding and deep diving into inner workings of the Parser, then make sure to checkout this section.
* [Adding a new diagram type](/docs/@excalidraw/mermaid-to-excalidraw/codebase/new-diagram-type) - If you want to help us make the mermaid to Excalidraw Parser more powerful, you will find all information in this section to do so.
- [Adding a new diagram type](/docs/@excalidraw/mermaid-to-excalidraw/codebase/new-diagram-type) - If you want to help us make the mermaid to Excalidraw Parser more powerful, you will find all information in this section to do so.
@@ -10,7 +10,7 @@ lets run the playground server in local :point_down:
yarn start
```
This will start the playground server in port `1234` and open it in browser so you start playing with the playground.
This will start the playground server in port `1234` and open it in browser so you start playing with the playground.
## Update Supported Diagram Types
@@ -26,13 +26,13 @@ For this create a file named `{{diagramType}}.ts` in [`src/parser`](https://gith
The main aim of the parser is :point_down:
1. Determine how elements are connected in the diagram and thus finding arrow and text bindings.
1. Determine how elements are connected in the diagram and thus finding arrow and text bindings.
For this you might have to dig in to the parser `diagram.parser.yy` and which attributes to parse for the new diagram.
2. Determine the position and dimensions of each element, for this would be using the `svg`
Once the parser is ready, lets start using it.
Once the parser is ready, lets start using it.
Add the diagram type in switch case in [`parseMermaid`](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/parseMermaid.ts#L97) and call the parser for the same.
@@ -51,4 +51,3 @@ Thats it, you have added the new diagram type 🥳, now lets test it out!
2. Incase the new diagram type added is present in [`unsupported.ts`](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/playground/testcases/unsupported.ts) then remove it from there.
3. Verify if the test cases are running fine in playground.
@@ -8,12 +8,10 @@ In this section we will be diving into how the [flowchart parser](https://github
We use `diagram.parser.yy` attribute to parse the data. If you want to know more about how the `diagram.parse.yy` attribute looks like, you can check it [here](https://github.com/mermaid-js/mermaid/blob/00d06c7282a701849793680c1e97da1cfdfcce62/packages/mermaid/src/diagrams/flowchart/flowDb.js#L768), however for scope of flowchart we are using **3** APIs from this parser to compute `vertices`, `edges` and `clusters` as we need these data to transform to [ExcalidrawElementSkeleton](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/transform.ts#L133C13-L133C38).
For computing `vertices` and `edge`s lets consider the below svg generated by mermaid
![image](https://github.com/excalidraw/excalidraw/assets/11256141/d7013305-0b90-4fa0-a66e-b4f4604ad0b2)
## Computing the vertices
We use `getVertices` API from `diagram.parse.yy` to get the vertices for a given flowchart.
@@ -42,9 +40,10 @@ Considering the same example this is the response from the API
}
}
```
The dimensions and position is missing in this response and we need that to transform to [ExcalidrawElementSkeleton](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/transform.ts#L133C13-L133C38), for this we have our own parser [`parseVertex`](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/parseMermaid.ts#L178) which takes the above response and uses the `svg` together to compute position, dimensions and cleans up the response.
The final output from `parseVertex` looks like :point_down:
The final output from `parseVertex` looks like :point_down:
```js
{
@@ -73,57 +72,55 @@ The dimensions and position is missing in this response and we need that to tran
}
```
## Computing the edges
The lines and arrows are considered as `edges` in mermaid as shown in the above diagram.
We use `getEdges` API from `diagram.parse.yy` to get the edges for a given flowchart.
Considering the same example this is the response from the API
The lines and arrows are considered as `edges` in mermaid as shown in the above diagram. We use `getEdges` API from `diagram.parse.yy` to get the edges for a given flowchart. Considering the same example this is the response from the API
```js
[
{
"start": "start",
"end": "stop",
"type": "arrow_point",
"text": "",
"labelType": "text",
"stroke": "normal",
"length": 1
}
]
{
start: "start",
end: "stop",
type: "arrow_point",
text: "",
labelType: "text",
stroke: "normal",
length: 1,
},
];
```
Similarly here the dimensions and position is missing and we compute that from the svg. The [`parseEdge`](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/parseMermaid.ts#L245) takes the above response along with `svg` and computes the position, dimensions and cleans up the response.
The final output from `parseEdge` looks like :point_down:
The final output from `parseEdge` looks like :point_down:
```js
[
{
"start": "start",
"end": "stop",
"type": "arrow_point",
"text": "",
"labelType": "text",
"stroke": "normal",
"startX": 67.797,
"startY": 22,
"endX": 117.797,
"endY": 22,
"reflectionPoints": [
{
"x": 67.797,
"y": 22
},
{
"x": 117.797,
"y": 22
}
]
}
]
{
start: "start",
end: "stop",
type: "arrow_point",
text: "",
labelType: "text",
stroke: "normal",
startX: 67.797,
startY: 22,
endX: 117.797,
endY: 22,
reflectionPoints: [
{
x: 67.797,
y: 22,
},
{
x: 117.797,
y: 22,
},
],
},
];
```
## Computing the Subgraphs
`Subgraphs` is collection of elements grouped together. The Subgraphs map to `grouping` elements in Excalidraw.
@@ -132,46 +129,35 @@ Lets consider the below example :point_down:
![image](https://github.com/excalidraw/excalidraw/assets/11256141/5243ce4c-beaa-43d2-812a-0577b0a574d7)
We use `getSubgraphs` API to get the subgraph data for a given flowchart.
Considering the same example this is the response from the API
We use `getSubgraphs` API to get the subgraph data for a given flowchart. Considering the same example this is the response from the API
```js
[
{
"id": "one",
"nodes": [
"flowchart-a2-1399",
"flowchart-a1-1400"
],
"title": "one",
"classes": [],
"labelType": "text"
}
]
{
id: "one",
nodes: ["flowchart-a2-1399", "flowchart-a1-1400"],
title: "one",
classes: [],
labelType: "text",
},
];
```
For position and dimensions we use the svg to compute. The [`parseSubgraph`](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/parseMermaid.ts#L139) takes the above response along with `svg` and computes the position, dimensions and cleans up the response.
```js
[
{
"id": "one",
"nodes": [
"flowchart-a2-1399",
"flowchart-a1-1400"
],
"title": "one",
"labelType": "text",
"nodeIds": [
"a2",
"a1"
],
"x": 75.4921875,
"y": 0,
"width": 121.25,
"height": 188,
"text": "one"
}
]
```
{
id: "one",
nodes: ["flowchart-a2-1399", "flowchart-a1-1400"],
title: "one",
labelType: "text",
nodeIds: ["a2", "a1"],
x: 75.4921875,
y: 0,
width: 121.25,
height: 188,
text: "one",
},
];
```
@@ -2,7 +2,6 @@
[This](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/index.ts) is the entry point of the library.
`parseMermaidToExcalidraw` function is the only function exposed which receives mermaid syntax as the input, parses the mermaid syntax and resolves to Excalidraw Skeleton.
Lets look at the high level overview at how the parse works :point_down:
@@ -13,10 +12,10 @@ Lets dive deeper into individual section now to understand better.
## Parsing Mermaid diagram
One of the dependencies of the library is [`mermaid`](https://www.npmjs.com/package/mermaid) library.
We need the mermaid diagram in some extractable format so we can parse it to Excalidraw Elements.
One of the dependencies of the library is [`mermaid`](https://www.npmjs.com/package/mermaid) library. We need the mermaid diagram in some extractable format so we can parse it to Excalidraw Elements.
Parsing is broken into two steps
1. [`Rendering Mermaid to Svg`](/docs/@excalidraw/mermaid-to-excalidraw/codebase/parser#rendering-mermaid-to-svg) - This helps in determining the position and dimensions of each element in the diagram
2. [`Parsing the mermaid syntax`](/docs/@excalidraw/mermaid-to-excalidraw/codebase/parser#parsing-the-mermaid-syntax) - We also need to know how elements are connected which isn't possible with svg alone hence we also parse the mermaid syntax which helps in determining the connections and bindings between elements in the diagram.
@@ -27,10 +26,8 @@ Parsing is broken into two steps
The [`mermaid`](https://www.npmjs.com/package/mermaid) library provides the API `mermaid.render` API which gives the output of the diagram in `svg`.
If the diagram isn't supported, this svg is converted to `dataURL` and can be rendered as an image in Excalidraw.
### Parsing the mermaid syntax
For this we first need to process the options along with mermaid defination for diagram provided by the user.
@@ -57,9 +54,8 @@ If you want to understand how flowchart parser works, you can navigate to [Flowc
Now we have all the data, we just need to transform it to [ExcalidrawElementSkeleton](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/transform.ts#L133C13-L133C38) API so it can be rendered in Excalidraw.
For this we have `converters` which takes the parsed mermaid data and gives back the Excalidraw Skeleton.
For Unsupported types, we have already mentioned above that we convert it to `dataURL` and return the ExcalidrawImageSkeleton.
For this we have `converters` which takes the parsed mermaid data and gives back the Excalidraw Skeleton. For Unsupported types, we have already mentioned above that we convert it to `dataURL` and return the ExcalidrawImageSkeleton.
For supported types, currently only flowchart, we have [flowchartConverter](https://github.com/excalidraw/mermaid-to-excalidraw/blob/master/src/converter/types/flowchart.ts#L24) which parses the data and converts to [ExcalidrawElementSkeleton](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/data/transform.ts#L133C13-L133C38).
![image](https://github.com/excalidraw/excalidraw/assets/11256141/00226e9d-043d-4a08-989a-3ad9d2a574f1)
![image](https://github.com/excalidraw/excalidraw/assets/11256141/00226e9d-043d-4a08-989a-3ad9d2a574f1)
@@ -10,7 +10,6 @@ To set up the library in local, follow the below steps 👇🏼
Go to [@excalidraw/mermaid-to-excalidraw](https://github.com/excalidraw/mermaid-to-excalidraw) and clone the repository to your local.
```bash
git clone git@github.com:excalidraw/mermaid-to-excalidraw.git
```
@@ -20,7 +20,7 @@ Once the library is installed, its ready to use.
```js
import { parseMermaidToExcalidraw } from "@excalidraw/mermaid-to-excalidraw";
import { convertToExcalidrawElements} from "@excalidraw/excalidraw"
import { convertToExcalidrawElements } from "@excalidraw/excalidraw";
try {
const { elements, files } = await parseMermaid(diagramDefinition, {
@@ -38,5 +38,4 @@ try {
## Playground
Try it out [here](https://mermaid-to-excalidraw.vercel.app)
Try it out [here](https://mermaid-to-excalidraw.vercel.app)
+2 -6
View File
@@ -2,8 +2,7 @@
Pull requests are welcome. For major changes, please [open an issue](https://github.com/excalidraw/excalidraw/issues/new) first to discuss what you would like to change.
We have a [roadmap](https://github.com/orgs/excalidraw/projects/3) which we strongly recommend to go through and check if something interests you.
For new contributors we would recommend to start with *Easy* tasks.
We have a [roadmap](https://github.com/orgs/excalidraw/projects/3) which we strongly recommend to go through and check if something interests you. For new contributors we would recommend to start with _Easy_ tasks.
In case you want to pick up something from the roadmap, comment on that issue and one of the project maintainers will assign it to you, post which you can discuss in the issue and start working on it.
@@ -60,10 +59,7 @@ It's also a good idea to consider if your change should include additional tests
Finally - always manually test your changes using the convenient staging environment deployed for each pull request. As much as local development attempts to replicate production, there can still be subtle differences in behavior. For larger features consider testing your change in multiple browsers as well.
:::note
Some checks, such as the `lint` and `test`, require approval from the maintainers to run.
They will appear as `Expected — Waiting for status to be reported` in the PR checks when they are waiting for approval.
:::
:::note Some checks, such as the `lint` and `test`, require approval from the maintainers to run. They will appear as `Expected — Waiting for status to be reported` in the PR checks when they are waiting for approval. :::
## Translating
+1 -7
View File
@@ -54,7 +54,7 @@ yarn
yarn start
```
### Reformat all files with Prettier
### Lint & format
```bash
yarn fix
@@ -72,12 +72,6 @@ yarn test
yarn test:update
```
### Test for formatting with Prettier
```bash
yarn test:code
```
### Docker Compose
You can use docker-compose to work on Excalidraw locally if you don't want to setup a Node.js env.
@@ -11,7 +11,7 @@ const ExcalidrawWrapper: React.FC = () => {
<>
<App
appTitle={"Excalidraw with Nextjs Example"}
useCustom={(api: any, args?: any[]) => {}}
useCustom={() => {}}
excalidrawLib={excalidrawLib}
>
<Excalidraw />
+7 -1
View File
@@ -23,6 +23,12 @@
},
"forceConsistentCasingInFileNames": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "build/types/**/*.ts"],
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"build/types/**/*.ts"
],
"exclude": ["node_modules"]
}
@@ -238,7 +238,7 @@ export default function ExampleApp({
left: "50%",
transform: "translateX(-50%)",
bottom: "20px",
zIndex: 9999999999999999,
zIndex: 999999999999999,
}}
>
Toggle Custom Sidebar
@@ -250,7 +250,7 @@ export default function ExampleApp({
</TTDDialogTrigger>
)}
<TTDDialog
onTextSubmit={async (_) => {
onTextSubmit={async () => {
console.info("submit");
// sleep for 2s
await new Promise((resolve) => setTimeout(resolve, 2000));
@@ -555,7 +555,7 @@ export default function ExampleApp({
if (!comment) {
return null;
}
const appState = excalidrawAPI?.getAppState()!;
const appState = excalidrawAPI?.getAppState();
const { x, y } = sceneCoordsToViewportCoords(
{ sceneX: comment.x, sceneY: comment.y },
appState,
+1 -1
View File
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
+1 -1
View File
@@ -20,7 +20,7 @@ root.render(
<StrictMode>
<App
appTitle={"Excalidraw Example"}
useCustom={(api: any, args?: any[]) => {}}
useCustom={() => {}}
excalidrawLib={window.ExcalidrawLib}
>
<Excalidraw />
+7 -7
View File
@@ -2,6 +2,13 @@
"name": "with-script-in-browser",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "vite",
"build": "vite build",
"preview": "vite preview --port 5002",
"build:preview": "yarn build && yarn preview",
"build:packages": "yarn --cwd ../../ build:packages"
},
"dependencies": {
"@excalidraw/excalidraw": "0.18.0",
"browser-fs-access": "0.29.1",
@@ -11,12 +18,5 @@
"devDependencies": {
"typescript": "^5",
"vite": "5.0.12"
},
"scripts": {
"start": "vite",
"build": "vite build",
"preview": "vite preview --port 5002",
"build:preview": "yarn build && yarn preview",
"build:packages": "yarn --cwd ../../ build:packages"
}
}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -192,7 +192,7 @@ if (window.self !== window.top) {
if (parentUrl.origin === currentUrl.origin) {
isSelfEmbedding = true;
}
} catch (error) {
} catch {
// ignore
}
}
@@ -310,7 +310,7 @@ const initializeScene = async (opts: {
) {
return { scene: data, isExternalScene };
}
} catch (error: any) {
} catch {
return {
scene: {
appState: {
+5 -3
View File
@@ -210,7 +210,9 @@ class Collab extends PureComponent<CollabProps, CollabState> {
window.addEventListener(EVENT.UNLOAD, this.onUnload);
const unsubOnUserFollow = this.excalidrawAPI.onUserFollow((payload) => {
this.portal.socket && this.portal.broadcastUserFollowed(payload);
if (this.portal.socket) {
this.portal.broadcastUserFollowed(payload);
}
});
const throttledRelayUserViewportBounds = throttleRAF(
this.relayVisibleSceneBounds,
@@ -915,9 +917,9 @@ class Collab extends PureComponent<CollabProps, CollabState> {
button: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["button"];
pointersMap: Gesture["pointers"];
}) => {
payload.pointersMap.size < 2 &&
this.portal.socket &&
if (payload.pointersMap.size < 2 && this.portal.socket) {
this.portal.broadcastMouseLocation(payload);
}
},
CURSOR_SYNC_TIMEOUT,
);
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../../packages/excalidraw/css/variables.module.scss";
@use "../../packages/excalidraw/css/variables.module.scss" as *;
.excalidraw {
.collab-errors-button {
+1 -1
View File
@@ -46,7 +46,7 @@ class Portal {
trackEvent("share", "room joined");
}
});
this.socket.on("new-user", async (_socketId: string) => {
this.socket.on("new-user", async () => {
this.broadcastScene(
WS_SUBTYPES.INIT,
this.collab.getSceneElementsIncludingDeleted(),
+1 -1
View File
@@ -95,7 +95,7 @@ export const AIComponents = ({
return {
html,
};
} catch (error: any) {
} catch {
throw new Error("Generation failed (invalid response)");
}
}}
+2 -5
View File
@@ -16,11 +16,8 @@
background-position: center;
background-repeat: no-repeat;
background-image: radial-gradient(
circle,
transparent 60%,
var(--sidebar-bg-color) 100%
),
background-image:
radial-gradient(circle, transparent 60%, var(--sidebar-bg-color) 100%),
var(--image-source);
display: flex;
@@ -28,7 +28,7 @@ export class TopErrorBoundary extends React.Component<
for (const [key, value] of Object.entries({ ...localStorage })) {
try {
_localStorage[key] = JSON.parse(value);
} catch (error: any) {
} catch {
_localStorage[key] = value;
}
}
@@ -37,7 +37,7 @@ export class TopErrorBoundary extends React.Component<
scope.setExtras(errorInfo);
const eventId = Sentry.captureException(error);
this.setState((state) => ({
this.setState(() => ({
hasError: true,
sentryEventId: eventId,
localStorage: JSON.stringify(_localStorage),
+2 -2
View File
@@ -44,7 +44,7 @@ import type { Socket } from "socket.io-client";
let FIREBASE_CONFIG: Record<string, any>;
try {
FIREBASE_CONFIG = JSON.parse(import.meta.env.VITE_APP_FIREBASE_CONFIG);
} catch (error: any) {
} catch {
console.warn(
`Error JSON parsing firebase config. Supplied value: ${
import.meta.env.VITE_APP_FIREBASE_CONFIG
@@ -162,7 +162,7 @@ export const saveFilesToFirebase = async ({
cacheControl: `public, max-age=${FILE_CACHE_MAX_AGE_SEC}`,
});
savedFiles.push(id);
} catch (error: any) {
} catch {
erroredFiles.push(id);
}
}),
+1 -1
View File
@@ -181,7 +181,7 @@ const legacy_decodeFromBackend = async ({
const iv = buffer.slice(0, IV_LENGTH_BYTES);
const encrypted = buffer.slice(IV_LENGTH_BYTES, buffer.byteLength);
decrypted = await decryptData(new Uint8Array(iv), encrypted, decryptionKey);
} catch (error: any) {
} catch {
// Fixed IV (old format, backward compatibility)
const fixedIv = new Uint8Array(IV_LENGTH_BYTES);
decrypted = await decryptData(fixedIv, buffer, decryptionKey);
+1 -1
View File
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../packages/excalidraw/css/variables.module.scss";
@use "../packages/excalidraw/css/variables.module.scss" as *;
.excalidraw {
--color-primary-contrast-offset: #625ee0; // to offset Chubb illusion
+28 -29
View File
@@ -3,6 +3,34 @@
"version": "1.0.0",
"private": true,
"homepage": ".",
"scripts": {
"build-node": "node ./scripts/build-node.js",
"build:app:docker": "cross-env VITE_APP_DISABLE_SENTRY=true vite build",
"build:app": "cross-env VITE_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA cross-env VITE_APP_ENABLE_TRACKING=true vite build",
"build:version": "node ../scripts/build-version.js",
"build": "yarn build:app && yarn build:version",
"start": "yarn && vite",
"start:production": "yarn build && yarn serve",
"serve": "npx http-server build -a localhost -p 5001 -o",
"build:preview": "yarn build && vite preview --port 5000"
},
"dependencies": {
"@excalidraw/random-username": "1.0.0",
"@sentry/browser": "9.0.1",
"callsites": "4.2.0",
"firebase": "11.3.1",
"i18next-browser-languagedetector": "6.1.4",
"idb-keyval": "6.0.3",
"jotai": "2.11.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"socket.io-client": "4.7.2",
"uqr": "0.1.2",
"vite-plugin-html": "3.2.2"
},
"devDependencies": {
"vite-plugin-sitemap": "0.7.1"
},
"browserslist": {
"production": [
">0.2%",
@@ -24,34 +52,5 @@
},
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"@excalidraw/random-username": "1.0.0",
"@sentry/browser": "9.0.1",
"callsites": "4.2.0",
"firebase": "11.3.1",
"i18next-browser-languagedetector": "6.1.4",
"idb-keyval": "6.0.3",
"jotai": "2.11.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"socket.io-client": "4.7.2",
"uqr": "0.1.2",
"vite-plugin-html": "3.2.2"
},
"prettier": "@excalidraw/prettier-config",
"scripts": {
"build-node": "node ./scripts/build-node.js",
"build:app:docker": "cross-env VITE_APP_DISABLE_SENTRY=true vite build",
"build:app": "cross-env VITE_APP_GIT_SHA=$VERCEL_GIT_COMMIT_SHA cross-env VITE_APP_ENABLE_TRACKING=true vite build",
"build:version": "node ../scripts/build-version.js",
"build": "yarn build:app && yarn build:version",
"start": "yarn && vite",
"start:production": "yarn build && yarn serve",
"serve": "npx http-server build -a localhost -p 5001 -o",
"build:preview": "yarn build && vite preview --port 5000"
},
"devDependencies": {
"vite-plugin-sitemap": "0.7.1"
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
@import "../../packages/excalidraw/css/variables.module.scss";
@use "../../packages/excalidraw/css/variables.module.scss" as *;
.excalidraw {
.ShareDialog {
+2 -2
View File
@@ -73,7 +73,7 @@ const ActiveRoomDialog = ({
const copyRoomLink = async () => {
try {
await copyTextToSystemClipboard(activeRoomLink);
} catch (e) {
} catch {
collabAPI.setCollabError(t("errors.copyToSystemClipboardFailed"));
}
@@ -97,7 +97,7 @@ const ActiveRoomDialog = ({
text: t("roomDialog.shareTitle"),
url: activeRoomLink,
});
} catch (error: any) {
} catch {
// Just ignore.
}
};
+39 -41
View File
@@ -1,48 +1,11 @@
{
"private": true,
"name": "excalidraw-monorepo",
"packageManager": "yarn@1.22.22",
"private": true,
"homepage": ".",
"workspaces": [
"excalidraw-app",
"packages/*"
],
"devDependencies": {
"@babel/preset-env": "7.26.9",
"@types/chai": "4.3.0",
"@types/jest": "27.4.0",
"@types/lodash.throttle": "4.1.7",
"@types/react": "19.0.10",
"@types/react-dom": "19.0.4",
"@types/socket.io-client": "3.0.0",
"@vitejs/plugin-react": "3.1.0",
"@vitest/coverage-v8": "3.0.7",
"@vitest/ui": "2.0.5",
"chai": "4.3.6",
"dotenv": "16.0.1",
"http-server": "14.1.1",
"husky": "7.0.4",
"jsdom": "22.1.0",
"lint-staged": "12.3.7",
"oxfmt": "0.26.0",
"oxlint": "1.41.0",
"pepjs": "0.5.3",
"rewire": "6.0.0",
"rimraf": "^5.0.0",
"typescript": "5.9.3",
"vite": "5.0.12",
"vite-plugin-checker": "0.7.2",
"vite-plugin-ejs": "1.7.0",
"vite-plugin-oxlint": "github:dwelle/vite-plugin-oxlint",
"vite-plugin-pwa": "0.21.1",
"vite-plugin-svgr": "4.2.0",
"vitest": "3.0.6",
"vitest-canvas-mock": "0.3.3"
},
"engines": {
"node": ">=18.0.0"
},
"homepage": ".",
"scripts": {
"build-node": "node ./scripts/build-node.js",
"build:app:docker": "yarn --cwd ./excalidraw-app build:app:docker",
@@ -83,8 +46,43 @@
"rm:node_modules": "rimraf --glob node_modules excalidraw-app/node_modules packages/*/node_modules",
"clean-install": "yarn rm:node_modules && yarn install"
},
"devDependencies": {
"@babel/preset-env": "7.26.9",
"@types/chai": "4.3.0",
"@types/jest": "27.4.0",
"@types/lodash.throttle": "4.1.7",
"@types/react": "19.0.10",
"@types/react-dom": "19.0.4",
"@types/socket.io-client": "3.0.0",
"@vitejs/plugin-react": "3.1.0",
"@vitest/coverage-v8": "3.0.7",
"@vitest/ui": "2.0.5",
"chai": "4.3.6",
"dotenv": "16.0.1",
"http-server": "14.1.1",
"husky": "7.0.4",
"jsdom": "22.1.0",
"lint-staged": "12.3.7",
"oxfmt": "0.26.0",
"oxlint": "1.41.0",
"pepjs": "0.5.3",
"rewire": "6.0.0",
"rimraf": "^5.0.0",
"typescript": "5.9.3",
"vite": "5.0.12",
"vite-plugin-checker": "0.7.2",
"vite-plugin-ejs": "1.7.0",
"vite-plugin-oxlint": "github:dwelle/vite-plugin-oxlint",
"vite-plugin-pwa": "0.21.1",
"vite-plugin-svgr": "4.2.0",
"vitest": "3.0.6",
"vitest-canvas-mock": "0.3.3"
},
"resolutions": {
"strip-ansi": "6.0.1"
}
},
"engines": {
"node": ">=18.0.0"
},
"packageManager": "yarn@1.22.22"
}
+22 -22
View File
@@ -1,10 +1,21 @@
{
"name": "@excalidraw/common",
"version": "0.18.0",
"description": "Excalidraw common functions, constants, etc.",
"keywords": [
"excalidraw",
"excalidraw-utils"
],
"bugs": "https://github.com/excalidraw/excalidraw/issues",
"license": "MIT",
"repository": "https://github.com/excalidraw/excalidraw",
"files": [
"dist/*"
],
"type": "module",
"types": "./dist/types/common/src/index.d.ts",
"main": "./dist/prod/index.js",
"module": "./dist/prod/index.js",
"types": "./dist/types/common/src/index.d.ts",
"exports": {
".": {
"types": "./dist/types/common/src/index.d.ts",
@@ -19,18 +30,19 @@
"default": "./dist/prod/index.js"
}
},
"files": [
"dist/*"
],
"description": "Excalidraw common functions, constants, etc.",
"publishConfig": {
"access": "public"
},
"license": "MIT",
"keywords": [
"excalidraw",
"excalidraw-utils"
],
"scripts": {
"gen:types": "rimraf types && tsc",
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
},
"dependencies": {
"tinycolor2": "1.6.0"
},
"devDependencies": {
"@types/tinycolor2": "1.4.6"
},
"browserslist": {
"production": [
">0.2%",
@@ -49,17 +61,5 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"bugs": "https://github.com/excalidraw/excalidraw/issues",
"repository": "https://github.com/excalidraw/excalidraw",
"scripts": {
"gen:types": "rimraf types && tsc",
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
},
"dependencies": {
"tinycolor2": "1.6.0"
},
"devDependencies": {
"@types/tinycolor2": "1.4.6"
}
}
+9 -6
View File
@@ -118,12 +118,15 @@ const pick = <R extends Record<string, any>, K extends readonly (keyof R)[]>(
source: R,
keys: K,
) => {
return keys.reduce((acc, key: K[number]) => {
if (key in source) {
acc[key] = source[key];
}
return acc;
}, {} as Pick<R, K[number]>) as Pick<R, K[number]>;
return keys.reduce(
(acc, key: K[number]) => {
if (key in source) {
acc[key] = source[key];
}
return acc;
},
{} as Pick<R, K[number]>,
) as Pick<R, K[number]>;
};
export type ColorTuple = readonly [string, string, string, string, string];
+2 -2
View File
@@ -193,7 +193,7 @@ export const loadDesktopUIModePreference = () => {
if (stored === "compact" || stored === "full") {
return stored as EditorInterface["desktopUIMode"];
}
} catch (error) {
} catch {
// ignore storage access issues (e.g., Safari private mode)
}
@@ -206,7 +206,7 @@ const persistDesktopUIMode = (mode: EditorInterface["desktopUIMode"]) => {
}
try {
window.localStorage.setItem(DESKTOP_UI_MODE_STORAGE_KEY, mode);
} catch (error) {
} catch {
// ignore storage access issues (e.g., Safari private mode)
}
};
+4 -6
View File
@@ -44,9 +44,8 @@ export type ForwardRef<T, P = any> = Parameters<
CallableType<React.ForwardRefRenderFunction<T, P>>
>[1];
export type ExtractSetType<T extends Set<any>> = T extends Set<infer U>
? U
: never;
export type ExtractSetType<T extends Set<any>> =
T extends Set<infer U> ? U : never;
export type SameType<T, U> = T extends U ? (U extends T ? true : false) : false;
export type Assert<T extends true> = T;
@@ -74,6 +73,5 @@ export type DTO<T> = {
[K in keyof T as T[K] extends Function ? never : K]: T[K];
};
export type MapEntry<M extends Map<any, any>> = M extends Map<infer K, infer V>
? [K, V]
: never;
export type MapEntry<M extends Map<any, any>> =
M extends Map<infer K, infer V> ? [K, V] : never;
+48 -39
View File
@@ -667,10 +667,13 @@ export const arrayToMap = <T extends { id: string } | string>(
if (items instanceof Map) {
return items;
}
return items.reduce((acc: Map<string, T>, element) => {
acc.set(typeof element === "string" ? element : element.id, element);
return acc;
}, new Map() as Map<string, T>);
return items.reduce(
(acc: Map<string, T>, element) => {
acc.set(typeof element === "string" ? element : element.id, element);
return acc;
},
new Map() as Map<string, T>,
);
};
export const arrayToMapWithIndex = <T extends { id: string }>(
@@ -688,10 +691,13 @@ export const arrayToObject = <T>(
array: readonly T[],
groupBy?: (value: T) => string | number,
) =>
array.reduce((acc, value, idx) => {
acc[groupBy ? groupBy(value) : idx] = value;
return acc;
}, {} as { [key: string]: T });
array.reduce(
(acc, value, idx) => {
acc[groupBy ? groupBy(value) : idx] = value;
return acc;
},
{} as { [key: string]: T },
);
/** Doubly linked node */
export type Node<T> = T & {
@@ -799,7 +805,7 @@ export const isPrimitive = (val: any) => {
export const getFrame = () => {
try {
return window.self === window.top ? "top" : "iframe";
} catch (error) {
} catch {
return "iframe";
}
};
@@ -1019,8 +1025,8 @@ export const isMemberOf = <T extends string>(
return collection instanceof Set || collection instanceof Map
? collection.has(value as T)
: "includes" in collection
? collection.includes(value as T)
: collection.hasOwnProperty(value);
? collection.includes(value as T)
: collection.hasOwnProperty(value);
};
export const cloneJSON = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
@@ -1151,35 +1157,38 @@ export type HasBrand<T> = {
[K in keyof T]: K extends `~brand${infer _}` | "_brand" ? true : never;
}[keyof T];
type RemoveAllBrands<T> = HasBrand<T> extends true
? {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[K in keyof T as K extends `~brand~${infer _}` | "_brand"
? never
: K]: T[K];
}
: T;
type RemoveAllBrands<T> =
HasBrand<T> extends true
? {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
[K in keyof T as K extends `~brand~${infer _}` | "_brand"
? never
: K]: T[K];
}
: T;
// For accepting values - uses loose matching for branded types
// Preserves readonly modifier: mutable array requires mutable input
type UnbrandForValue<T> = T extends Map<infer E, infer F>
? Map<UnbrandForValue<E>, UnbrandForValue<F>>
: T extends Set<infer E>
? Set<UnbrandForValue<E>>
: T extends readonly any[]
? T extends any[]
? unknown[] // mutable array - require mutable input
: readonly unknown[] // readonly array - accept readonly input
: RemoveAllBrands<T>;
type UnbrandForValue<T> =
T extends Map<infer E, infer F>
? Map<UnbrandForValue<E>, UnbrandForValue<F>>
: T extends Set<infer E>
? Set<UnbrandForValue<E>>
: T extends readonly any[]
? T extends any[]
? unknown[] // mutable array - require mutable input
: readonly unknown[] // readonly array - accept readonly input
: RemoveAllBrands<T>;
// For return types - preserves array element unbranding
export type Unbrand<T> = T extends Map<infer E, infer F>
? Map<Unbrand<E>, Unbrand<F>>
: T extends Set<infer E>
? Set<Unbrand<E>>
: T extends readonly (infer E)[]
? Array<Unbrand<E>>
: RemoveAllBrands<T>;
export type Unbrand<T> =
T extends Map<infer E, infer F>
? Map<Unbrand<E>, Unbrand<F>>
: T extends Set<infer E>
? Set<Unbrand<E>>
: T extends readonly (infer E)[]
? Array<Unbrand<E>>
: RemoveAllBrands<T>;
export type CombineBrands<BrandedType, CurrentType> =
BrandedType extends readonly (infer BE)[]
@@ -1191,8 +1200,8 @@ export type CombineBrands<BrandedType, CurrentType> =
export type CombineBrandsIfNeeded<T, Required> = [T] extends [Required]
? T[]
: HasBrand<T> extends true
? CombineBrands<T, Required>[]
: Required[];
? CombineBrands<T, Required>[]
: Required[];
/**
* Makes type into a branded type, ensuring that value is assignable to
@@ -1259,8 +1268,8 @@ export const sizeOf = (
return isReadonlyArray(value)
? value.length
: value instanceof Map || value instanceof Set
? value.size
: Object.keys(value).length;
? value.size
: Object.keys(value).length;
};
export const reduceToCommonValue = <T, R = T>(
+20 -20
View File
@@ -1,10 +1,21 @@
{
"name": "@excalidraw/element",
"version": "0.18.0",
"description": "Excalidraw elements-related logic",
"keywords": [
"excalidraw",
"excalidraw-utils"
],
"bugs": "https://github.com/excalidraw/excalidraw/issues",
"license": "MIT",
"repository": "https://github.com/excalidraw/excalidraw",
"files": [
"dist/*"
],
"type": "module",
"types": "./dist/types/element/src/index.d.ts",
"main": "./dist/prod/index.js",
"module": "./dist/prod/index.js",
"types": "./dist/types/element/src/index.d.ts",
"exports": {
".": {
"types": "./dist/types/element/src/index.d.ts",
@@ -25,18 +36,17 @@
"default": "./dist/prod/visualdebug.js"
}
},
"files": [
"dist/*"
],
"description": "Excalidraw elements-related logic",
"publishConfig": {
"access": "public"
},
"license": "MIT",
"keywords": [
"excalidraw",
"excalidraw-utils"
],
"scripts": {
"gen:types": "rimraf types && tsc",
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
},
"dependencies": {
"@excalidraw/common": "0.18.0",
"@excalidraw/math": "0.18.0"
},
"browserslist": {
"production": [
">0.2%",
@@ -55,15 +65,5 @@
"last 1 firefox version",
"last 1 safari version"
]
},
"bugs": "https://github.com/excalidraw/excalidraw/issues",
"repository": "https://github.com/excalidraw/excalidraw",
"scripts": {
"gen:types": "rimraf types && tsc",
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
},
"dependencies": {
"@excalidraw/common": "0.18.0",
"@excalidraw/math": "0.18.0"
}
}
+1 -1
View File
@@ -90,7 +90,7 @@ const hashSelectionOpts = (
type _ = Assert<
SameType<
Required<HashableKeys>,
Pick<Required<HashableKeys>, typeof keys[number]>
Pick<Required<HashableKeys>, (typeof keys)[number]>
>
>;
+50 -56
View File
@@ -258,7 +258,7 @@ const bindingStrategyForElbowArrowEndpointDragging = (
globalPoint,
elements,
elementsMap,
(element) => maxBindingDistance_simple(zoom),
() => maxBindingDistance_simple(zoom),
);
const current = hit
@@ -391,7 +391,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
element: otherElement,
focusPoint: shiftKey
? elementCenterPoint(otherElement, elementsMap)
: origin ?? pointFrom<GlobalPoint>(arrow.x, arrow.y),
: (origin ?? pointFrom<GlobalPoint>(arrow.x, arrow.y)),
};
// We are hovering another element with the end point
@@ -522,41 +522,35 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
}
// The opposite binding is inside the same element
// eslint-disable-next-line no-else-return
else {
current = { element: hit, mode: "inside", focusPoint: point };
return { current, other: isMultiPoint ? { mode: undefined } : other };
}
}
// The opposite binding is on a different element (or nested)
// eslint-disable-next-line no-else-return
else {
// Handle the nested element case
if (isOverlapping && oppositeElement && !otherIsTransparent) {
current = {
element: oppositeElement,
mode: "inside",
focusPoint: point,
};
} else {
current = {
element: hit,
mode: "orbit",
focusPoint: isNested ? point : point,
};
}
current = { element: hit, mode: "inside", focusPoint: point };
return { current, other: isMultiPoint ? { mode: undefined } : other };
}
// The opposite binding is on a different element (or nested)
// eslint-disable-next-line no-else-return
// Handle the nested element case
if (isOverlapping && oppositeElement && !otherIsTransparent) {
current = {
element: oppositeElement,
mode: "inside",
focusPoint: point,
};
} else {
current = {
element: hit,
mode: "orbit",
focusPoint: isNested ? point : point,
};
}
return { current, other: isMultiPoint ? { mode: undefined } : other };
}
// The opposite binding is on a different element or no binding
else {
current = {
element: hit,
mode: "orbit",
focusPoint: point,
};
}
current = {
element: hit,
mode: "orbit",
focusPoint: point,
};
// Must return as only one endpoint is dragged, therefore
// the end binding strategy might accidentally gets overriden
@@ -683,7 +677,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
globalPoint,
elements,
elementsMap,
(e) => maxBindingDistance_simple(appState.zoom),
() => maxBindingDistance_simple(appState.zoom),
);
const pointInElement =
hit &&
@@ -726,13 +720,13 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
focusPoint: startDragged
? globalPoint
: // NOTE: Can only affect the start point because new arrows always drag the end point
opts?.newArrow
? appState.selectedLinearElement!.initialState.origin!
: LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
0,
elementsMap,
), // startFixedPoint,
opts?.newArrow
? appState.selectedLinearElement!.initialState.origin!
: LinearElementEditor.getPointAtIndexGlobalCoordinates(
arrow,
0,
elementsMap,
), // startFixedPoint,
},
end: {
mode: "inside",
@@ -810,19 +804,19 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
focusPoint: appState.selectedLinearElement.initialState.altFocusPoint,
}
: opts?.angleLocked && otherBindableElement
? {
mode: "orbit",
element: otherBindableElement,
focusPoint:
projectFixedPointOntoDiagonal(
arrow,
otherEndpoint,
otherBindableElement,
startDragged ? "end" : "start",
elementsMap,
) || otherEndpoint,
}
: { mode: undefined };
? {
mode: "orbit",
element: otherBindableElement,
focusPoint:
projectFixedPointOntoDiagonal(
arrow,
otherEndpoint,
otherBindableElement,
startDragged ? "end" : "start",
elementsMap,
) || otherEndpoint,
}
: { mode: undefined };
return {
start: startDragged ? current : other,
@@ -1944,9 +1938,9 @@ const newBoundElements = (
nextBoundElements.push(
...elementsToAdd.map(
(x) =>
({ id: x.id, type: x.type } as
({ id: x.id, type: x.type }) as
| ExcalidrawArrowElement
| ExcalidrawTextElement),
| ExcalidrawTextElement,
),
);
@@ -2414,7 +2408,7 @@ const SHAPE_CONFIGS: Record<ShapeType, SectorConfig[]> = {
const getSectorBoundaries = (
config: SectorConfig[],
): Array<{ start: number; end: number; side: Side }> => {
return config.map((sector, index) => {
return config.map((sector) => {
const halfWidth = sector.sectorWidth / 2;
let start = sector.centerAngle - halfWidth;
let end = sector.centerAngle + halfWidth;
+7 -10
View File
@@ -974,7 +974,7 @@ export class AppStateDelta implements DeltaContainer<AppState> {
inserted,
"selectedElementIds",
// ts language server has a bit trouble resolving this, so we are giving it a little push
(_) => true as ValueOf<T["selectedElementIds"]>,
() => true as ValueOf<T["selectedElementIds"]>,
);
Delta.diffObjects(
deleted,
@@ -995,9 +995,8 @@ export class AppStateDelta implements DeltaContainer<AppState> {
if (isTestEnv() || isDevEnv()) {
throw e;
}
} finally {
return [deleted, inserted];
}
return [deleted, inserted];
}
private static orderAppStateKeys(partial: Partial<ObservedAppState>) {
@@ -1459,9 +1458,8 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
if (isTestEnv() || isDevEnv()) {
throw e;
}
} finally {
return [nextElements, flags.containsVisibleDifference];
}
return [nextElements, flags.containsVisibleDifference];
}
public squash(delta: ElementsDelta): this {
@@ -1802,7 +1800,7 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
// updated delta is affecting the binding only in case it contains changed binding or bindable property
for (const [id] of Array.from(Object.entries(this.updated)).filter(
([_, delta]) =>
([, delta]) =>
Object.keys({ ...delta.deleted, ...delta.inserted }).find((prop) =>
bindingProperties.has(prop as BindingProp | BindableProp),
),
@@ -1908,9 +1906,8 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
if (isTestEnv() || isDevEnv()) {
throw e;
}
} finally {
return nextElements;
}
return nextElements;
}
private static redrawTextBoundingBoxes(
@@ -2051,9 +2048,9 @@ export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
if (isTestEnv() || isDevEnv()) {
throw e;
}
} finally {
return [deleted, inserted];
}
return [deleted, inserted];
}
private static stripIrrelevantProps(
+38 -36
View File
@@ -255,11 +255,12 @@ const handleSegmentRenormalization = (
);
}
isDevEnv() &&
if (isDevEnv()) {
invariant(
validateElbowPoints(nextPoints),
"Invalid elbow points with fixed segments",
);
}
return normalizeArrowElementUpdate(
nextPoints,
@@ -521,8 +522,8 @@ const handleSegmentMove = (
? segmentLength / 2
: BASE_PADDING
: segmentIsTooShort
? -segmentLength / 2
: -BASE_PADDING;
? -segmentLength / 2
: -BASE_PADDING;
fixedSegments[activelyModifiedSegmentIdx].start = pointFrom<LocalPoint>(
fixedSegments[activelyModifiedSegmentIdx].start[0] +
(startIsHorizontal ? padding : 0),
@@ -547,8 +548,8 @@ const handleSegmentMove = (
? segmentLength / 2
: BASE_PADDING
: segmentIsTooShort
? -segmentLength / 2
: -BASE_PADDING;
? -segmentLength / 2
: -BASE_PADDING;
fixedSegments[activelyModifiedSegmentIdx].end = pointFrom<LocalPoint>(
fixedSegments[activelyModifiedSegmentIdx].end[0] +
(endIsHorizontal ? padding : 0),
@@ -571,7 +572,7 @@ const handleSegmentMove = (
}));
// For start, clone old arrow points
const newPoints: GlobalPoint[] = arrow.points.map((p, i) =>
const newPoints: GlobalPoint[] = arrow.points.map((p) =>
pointFrom<GlobalPoint>(arrow.x + p[0], arrow.y + p[1]),
);
@@ -720,11 +721,11 @@ const handleEndpointDrag = (
i === 0
? pointFrom<GlobalPoint>(arrow.x + p[0], arrow.y + p[1])
: i === updatedPoints.length - 1
? pointFrom<GlobalPoint>(arrow.x + p[0], arrow.y + p[1])
: pointFrom<GlobalPoint>(
arrow.x + arrow.points[i][0],
arrow.y + arrow.points[i][1],
),
? pointFrom<GlobalPoint>(arrow.x + p[0], arrow.y + p[1])
: pointFrom<GlobalPoint>(
arrow.x + arrow.points[i][0],
arrow.y + arrow.points[i][1],
),
);
const nextFixedSegments = fixedSegments.map((segment) => ({
...segment,
@@ -982,8 +983,8 @@ export const updateElbowArrowPoints = (
idx === 0
? updates.points![0]
: idx === arrow.points.length - 1
? updates.points![1]
: p,
? updates.points![1]
: p,
)
: updates.points.slice()
: arrow.points.slice();
@@ -1489,8 +1490,12 @@ const routeElbowArrow = (
node.pos[0],
node.pos[1],
]) as GlobalPoint[];
startDongle && points.unshift(startGlobalPoint);
endDongle && points.push(endGlobalPoint);
if (startDongle) {
points.unshift(startGlobalPoint);
}
if (endDongle) {
points.push(endGlobalPoint);
}
return points;
}
@@ -1680,29 +1685,29 @@ const generateDynamicAABBs = (
? Math.min((startEl[0] + endEl[2]) / 2, a[0] - startLeft)
: (startEl[0] + endEl[2]) / 2
: a[0] > b[0]
? a[0] - startLeft
: common[0] - startLeft,
? a[0] - startLeft
: common[0] - startLeft,
a[1] > b[3]
? a[0] > b[2] || a[2] < b[0]
? Math.min((startEl[1] + endEl[3]) / 2, a[1] - startUp)
: (startEl[1] + endEl[3]) / 2
: a[1] > b[1]
? a[1] - startUp
: common[1] - startUp,
? a[1] - startUp
: common[1] - startUp,
a[2] < b[0]
? a[1] > b[3] || a[3] < b[1]
? Math.max((startEl[2] + endEl[0]) / 2, a[2] + startRight)
: (startEl[2] + endEl[0]) / 2
: a[2] < b[2]
? a[2] + startRight
: common[2] + startRight,
? a[2] + startRight
: common[2] + startRight,
a[3] < b[1]
? a[0] > b[2] || a[2] < b[0]
? Math.max((startEl[3] + endEl[1]) / 2, a[3] + startDown)
: (startEl[3] + endEl[1]) / 2
: a[3] < b[3]
? a[3] + startDown
: common[3] + startDown,
? a[3] + startDown
: common[3] + startDown,
] as Bounds;
const second = [
b[0] > a[2]
@@ -1710,29 +1715,29 @@ const generateDynamicAABBs = (
? Math.min((endEl[0] + startEl[2]) / 2, b[0] - endLeft)
: (endEl[0] + startEl[2]) / 2
: b[0] > a[0]
? b[0] - endLeft
: common[0] - endLeft,
? b[0] - endLeft
: common[0] - endLeft,
b[1] > a[3]
? b[0] > a[2] || b[2] < a[0]
? Math.min((endEl[1] + startEl[3]) / 2, b[1] - endUp)
: (endEl[1] + startEl[3]) / 2
: b[1] > a[1]
? b[1] - endUp
: common[1] - endUp,
? b[1] - endUp
: common[1] - endUp,
b[2] < a[0]
? b[1] > a[3] || b[3] < a[1]
? Math.max((endEl[2] + startEl[0]) / 2, b[2] + endRight)
: (endEl[2] + startEl[0]) / 2
: b[2] < a[2]
? b[2] + endRight
: common[2] + endRight,
? b[2] + endRight
: common[2] + endRight,
b[3] < a[1]
? b[0] > a[2] || b[2] < a[0]
? Math.max((endEl[3] + startEl[1]) / 2, b[3] + endDown)
: (endEl[3] + startEl[1]) / 2
: b[3] < a[3]
? b[3] + endDown
: common[3] + endDown,
? b[3] + endDown
: common[3] + endDown,
] as Bounds;
const c = commonAABB([first, second]);
@@ -2272,11 +2277,8 @@ const getHoveredElement = (
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
zoom?: AppState["zoom"],
) => {
return getHoveredElementForBinding(
origPoint,
elements,
elementsMap,
(element) => maxBindingDistance_simple(zoom),
return getHoveredElementForBinding(origPoint, elements, elementsMap, () =>
maxBindingDistance_simple(zoom),
);
};
+2 -2
View File
@@ -13,7 +13,7 @@ import type { ExcalidrawElement } from "./types";
export const defaultGetElementLinkFromSelection: Exclude<
AppProps["generateLinkForSelection"],
undefined
> = (id, type) => {
> = (id) => {
const url = window.location.href;
try {
@@ -86,7 +86,7 @@ export const isElementLink = (url: string) => {
_url.searchParams.has(ELEMENT_LINK_KEY) &&
_url.host === window.location.host
);
} catch (error) {
} catch {
return false;
}
};
+2 -2
View File
@@ -63,7 +63,7 @@ const parseYouTubeTimestamp = (url: string): number => {
const urlObj = new URL(url.startsWith("http") ? url : `https://${url}`);
timeParam =
urlObj.searchParams.get("t") || urlObj.searchParams.get("start");
} catch (error) {
} catch {
const timeMatch = url.match(/[?&#](?:t|start)=([^&#\s]+)/);
timeParam = timeMatch?.[1];
}
@@ -388,7 +388,7 @@ const matchHostname = (
if (bareDomain === bareAllowedHostname) {
return bareAllowedHostname;
}
} catch (error) {
} catch {
// ignore
}
return null;
+4 -4
View File
@@ -198,8 +198,8 @@ const getOffsets = (
linkedNodes.length === 0
? 0
: (linkedNodes.length + 1) % 2 === 0
? ((linkedNodes.length + 1) / 2) * _HORIZONTAL_OFFSET
: (linkedNodes.length / 2) * _HORIZONTAL_OFFSET * -1;
? ((linkedNodes.length + 1) / 2) * _HORIZONTAL_OFFSET
: (linkedNodes.length / 2) * _HORIZONTAL_OFFSET * -1;
if (direction === "up") {
return {
@@ -222,8 +222,8 @@ const getOffsets = (
linkedNodes.length === 0
? 0
: (linkedNodes.length + 1) % 2 === 0
? ((linkedNodes.length + 1) / 2) * _VERTICAL_OFFSET
: (linkedNodes.length / 2) * _VERTICAL_OFFSET * -1;
? ((linkedNodes.length + 1) / 2) * _VERTICAL_OFFSET
: (linkedNodes.length / 2) * _VERTICAL_OFFSET * -1;
if (direction === "left") {
return {
+1 -1
View File
@@ -187,7 +187,7 @@ export const syncMovedIndices = (
for (const [element, { index }] of elementsUpdates) {
mutateElement(element, elementsMap, { index });
}
} catch (e) {
} catch {
// fallback to default sync
syncInvalidIndices(elements);
}
+1 -1
View File
@@ -797,7 +797,7 @@ export const isElementInFrame = (
for (const gid of _element.groupIds) {
if (opts?.checkedGroups?.has(gid)) {
return opts.checkedGroups.get(gid)!!;
return opts.checkedGroups.get(gid)!;
}
}
+4 -4
View File
@@ -231,8 +231,8 @@ export const getSelectedGroupIds = (
appState: InteractiveCanvasAppState,
): GroupId[] =>
Object.entries(appState.selectedGroupIds)
.filter(([groupId, isSelected]) => isSelected)
.map(([groupId, isSelected]) => groupId);
.filter(([, isSelected]) => isSelected)
.map(([groupId]) => groupId);
// given a list of elements, return the the actual group ids that should be selected
// or used to update the elements
@@ -325,8 +325,8 @@ export const getMaximumGroups = (
elements: ExcalidrawElement[],
elementsMap: ElementsMap,
): ExcalidrawElement[][] => {
const groups: Map<String, ExcalidrawElement[]> = new Map<
String,
const groups: Map<string, ExcalidrawElement[]> = new Map<
string,
ExcalidrawElement[]
>();
elements.forEach((element: ExcalidrawElement) => {
+10 -10
View File
@@ -268,16 +268,16 @@ export const headingForPointFromElement = <Point extends GlobalPoint>(
)
? HEADING_UP
: triangleIncludesPoint<Point>(
[topRight, bottomRight, midPoint] as Triangle<Point>,
p,
)
? HEADING_RIGHT
: triangleIncludesPoint<Point>(
[bottomRight, bottomLeft, midPoint] as Triangle<Point>,
p,
)
? HEADING_DOWN
: HEADING_LEFT;
[topRight, bottomRight, midPoint] as Triangle<Point>,
p,
)
? HEADING_RIGHT
: triangleIncludesPoint<Point>(
[bottomRight, bottomLeft, midPoint] as Triangle<Point>,
p,
)
? HEADING_DOWN
: HEADING_LEFT;
};
export const flipHeading = (h: Heading): Heading =>
+1 -1
View File
@@ -69,7 +69,7 @@ export const updateImageCache = async ({
const image = await imagePromise;
imageCache.set(fileId, { ...data, image });
} catch (error: any) {
} catch {
erroredFiles.set(fileId, true);
}
})(),
+48 -48
View File
@@ -606,10 +606,10 @@ export class LinearElementEditor {
updates?.suggestedBinding?.id !== startBindingElement.id // The end point is not hovering the start bindable + it's binding gap
? startBindingElement
: startIsSelected && // The "other" end (i.e. "start") is dragged
endBindingElement &&
updates?.suggestedBinding?.id !== endBindingElement.id // The start point is not hovering the end bindable + it's binding gap
? endBindingElement
: null;
endBindingElement &&
updates?.suggestedBinding?.id !== endBindingElement.id // The start point is not hovering the end bindable + it's binding gap
? endBindingElement
: null;
const newLinearElementEditor: LinearElementEditor = {
...linearElementEditor,
@@ -721,8 +721,8 @@ export class LinearElementEditor {
)
: selectedPointsIndices
: selectedPointsIndices?.includes(pointerDownState.lastClickedPoint)
? [pointerDownState.lastClickedPoint]
: selectedPointsIndices,
? [pointerDownState.lastClickedPoint]
: selectedPointsIndices,
isDragging: false,
pointerOffset: { x: 0, y: 0 },
customLineAngle: null,
@@ -976,7 +976,7 @@ export class LinearElementEditor {
const appState = app.state;
const elementsMap = scene.getNonDeletedElementsMap();
const ret: ReturnType<typeof LinearElementEditor["handlePointerDown"]> = {
const ret: ReturnType<(typeof LinearElementEditor)["handlePointerDown"]> = {
didAddPoint: false,
hitElement: null,
linearElementEditor: null,
@@ -2130,8 +2130,8 @@ const pointDraggingUpdates = (
suggestedBinding: startIsDragged
? start.element
: endIsDragged
? end.element
: null,
? end.element
: null,
},
};
}
@@ -2222,14 +2222,14 @@ const pointDraggingUpdates = (
updates.startBinding === undefined
? element.startBinding
: updates.startBinding === null
? null
: updates.startBinding,
? null
: updates.startBinding,
endBinding:
updates.endBinding === undefined
? element.endBinding
: updates.endBinding === null
? null
: updates.endBinding,
? null
: updates.endBinding,
};
// We need to use a custom intersector to ensure that if there is a big "jump"
@@ -2261,28 +2261,28 @@ const pointDraggingUpdates = (
// We need to update the non-dragged point too if bound,
// so we look up the old binding to trigger updateBoundPoint
const endBindable = nextArrow.endBinding
? end.element ??
? (end.element ??
(elementsMap.get(
nextArrow.endBinding.elementId,
)! as ExcalidrawBindableElement)
)! as ExcalidrawBindableElement))
: null;
const endLocalPoint = startIsDraggingOverEndElement
? nextArrow.points[nextArrow.points.length - 1]
: endIsDraggingOverStartElement &&
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[0]
: endBindable
? updateBoundPoint(
element,
"endBinding",
nextArrow.endBinding,
endBindable,
elementsMap,
endCustomIntersector,
) || nextArrow.points[nextArrow.points.length - 1]
: nextArrow.points[nextArrow.points.length - 1];
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[0]
: endBindable
? updateBoundPoint(
element,
"endBinding",
nextArrow.endBinding,
endBindable,
elementsMap,
endCustomIntersector,
) || nextArrow.points[nextArrow.points.length - 1]
: nextArrow.points[nextArrow.points.length - 1];
// We need to keep the simulated next arrow up-to-date, because
// updateBoundPoint looks at the opposite point
@@ -2291,29 +2291,29 @@ const pointDraggingUpdates = (
// We need to update the non-dragged point too if bound,
// so we look up the old binding to trigger updateBoundPoint
const startBindable = nextArrow.startBinding
? start.element ??
? (start.element ??
(elementsMap.get(
nextArrow.startBinding.elementId,
)! as ExcalidrawBindableElement)
)! as ExcalidrawBindableElement))
: null;
const startLocalPoint =
endIsDraggingOverStartElement && getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[0]
: startIsDraggingOverEndElement &&
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[nextArrow.points.length - 1]
: startBindable
? updateBoundPoint(
element,
"startBinding",
nextArrow.startBinding,
startBindable,
elementsMap,
startCustomIntersector,
) || nextArrow.points[0]
: nextArrow.points[0];
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[nextArrow.points.length - 1]
: startBindable
? updateBoundPoint(
element,
"startBinding",
nextArrow.startBinding,
startBindable,
elementsMap,
startCustomIntersector,
) || nextArrow.points[0]
: nextArrow.points[0];
const endChanged =
pointDistance(
@@ -2350,11 +2350,11 @@ const pointDraggingUpdates = (
isDragging: true,
}
: idx === element.points.length - 1
? {
point: endLocalPoint,
isDragging: true,
}
: naiveDraggingPoints.get(idx)!,
? {
point: endLocalPoint,
isDragging: true,
}
: naiveDraggingPoints.get(idx)!,
];
}),
),
+2 -2
View File
@@ -230,8 +230,8 @@ const getTextElementPositionOffsets = (
opts.textAlign === "center"
? metrics.width / 2
: opts.textAlign === "right"
? metrics.width
: 0,
? metrics.width
: 0,
y: opts.verticalAlign === "middle" ? metrics.height / 2 : 0,
};
};
+2 -2
View File
@@ -514,8 +514,8 @@ const drawElementOnCanvas = (
element.textAlign === "center"
? element.width / 2
: element.textAlign === "right"
? element.width
: 0;
? element.width
: 0;
const lineHeightPx = getLineHeightInPx(
element.fontSize,
+3 -3
View File
@@ -819,8 +819,8 @@ export const resizeSingleElement = (
nextHeight,
origElement.angle,
handleDirection,
shouldMaintainAspectRatio!!,
shouldResizeFromCenter!!,
shouldMaintainAspectRatio,
shouldResizeFromCenter,
);
if (isLinearElement(origElement) && rescaledPoints.points) {
@@ -1370,7 +1370,7 @@ export const resizeMultipleElements = (
false,
);
const update: typeof elementsAndUpdates[0]["update"] = {
const update: (typeof elementsAndUpdates)[0]["update"] = {
x,
y,
width,
+22 -16
View File
@@ -137,22 +137,28 @@ export const getElementWithTransformHandleType = (
elementsMap: ElementsMap,
editorInterface: EditorInterface,
) => {
return elements.reduce((result, element) => {
if (result) {
return result;
}
const transformHandleType = resizeTest(
element,
elementsMap,
appState,
scenePointerX,
scenePointerY,
zoom,
pointerType,
editorInterface,
);
return transformHandleType ? { element, transformHandleType } : null;
}, null as { element: NonDeletedExcalidrawElement; transformHandleType: MaybeTransformHandleType } | null);
return elements.reduce(
(result, element) => {
if (result) {
return result;
}
const transformHandleType = resizeTest(
element,
elementsMap,
appState,
scenePointerX,
scenePointerY,
zoom,
pointerType,
editorInterface,
);
return transformHandleType ? { element, transformHandleType } : null;
},
null as {
element: NonDeletedExcalidrawElement;
transformHandleType: MaybeTransformHandleType;
} | null,
);
};
export const getTransformHandleTypeFromCoords = <
+4 -4
View File
@@ -223,10 +223,10 @@ export const getTargetElements = (
appState.editingTextElement
? [appState.editingTextElement]
: appState.newElement
? [appState.newElement]
: getSelectedElements(elements, appState, {
includeBoundTextElement: true,
});
? [appState.newElement]
: getSelectedElements(elements, appState, {
includeBoundTextElement: true,
});
/**
* returns prevState's selectedElementids if no change from previous, so as to
+16 -16
View File
@@ -201,8 +201,8 @@ export const generateRoughOptions = (
element.strokeStyle === "dashed"
? getDashArrayDashed(element.strokeWidth)
: element.strokeStyle === "dotted"
? getDashArrayDotted(element.strokeWidth)
: undefined,
? getDashArrayDotted(element.strokeWidth)
: undefined,
// for non-solid strokes, disable multiStroke because it tends to make
// dashes/dots overlay each other
disableMultiStroke: element.strokeStyle !== "solid",
@@ -235,8 +235,8 @@ export const generateRoughOptions = (
options.fill = isTransparent(element.backgroundColor)
? undefined
: isDarkMode
? applyDarkModeFilter(element.backgroundColor)
: element.backgroundColor;
? applyDarkModeFilter(element.backgroundColor)
: element.backgroundColor;
if (element.type === "ellipse") {
options.curveFitting = 1;
}
@@ -250,8 +250,8 @@ export const generateRoughOptions = (
element.backgroundColor === "transparent"
? undefined
: isDarkMode
? applyDarkModeFilter(element.backgroundColor)
: element.backgroundColor;
? applyDarkModeFilter(element.backgroundColor)
: element.backgroundColor;
}
return options;
}
@@ -708,20 +708,20 @@ const _generateElementShape = (
rightX - verticalRadius
} ${rightY - horizontalRadius}
C ${rightX} ${rightY}, ${rightX} ${rightY}, ${
rightX - verticalRadius
} ${rightY + horizontalRadius}
rightX - verticalRadius
} ${rightY + horizontalRadius}
L ${bottomX + verticalRadius} ${bottomY - horizontalRadius}
C ${bottomX} ${bottomY}, ${bottomX} ${bottomY}, ${
bottomX - verticalRadius
} ${bottomY - horizontalRadius}
bottomX - verticalRadius
} ${bottomY - horizontalRadius}
L ${leftX + verticalRadius} ${leftY + horizontalRadius}
C ${leftX} ${leftY}, ${leftX} ${leftY}, ${leftX + verticalRadius} ${
leftY - horizontalRadius
}
leftY - horizontalRadius
}
L ${topX - verticalRadius} ${topY + horizontalRadius}
C ${topX} ${topY}, ${topX} ${topY}, ${topX + verticalRadius} ${
topY + horizontalRadius
}`,
topY + horizontalRadius
}`,
generateRoughOptions(element, true, isDarkMode),
);
} else {
@@ -1057,8 +1057,8 @@ export const getFreedrawOutlinePoints = (
const inputPoints = element.simulatePressure
? element.points
: element.points.length
? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
: [[0, 0, 0.5]];
? element.points.map(([x, y], i) => [x, y, element.pressures[i]])
: [[0, 0, 0.5]];
return getStroke(inputPoints as number[][], {
simulatePressure: element.simulatePressure,
@@ -10,13 +10,13 @@ export const showSelectedShapeActions = (
) =>
Boolean(
!appState.viewModeEnabled &&
appState.openDialog?.name !== "elementLinkSelector" &&
((appState.activeTool.type !== "custom" &&
(appState.editingTextElement ||
(appState.activeTool.type !== "selection" &&
appState.activeTool.type !== "lasso" &&
appState.activeTool.type !== "eraser" &&
appState.activeTool.type !== "hand" &&
appState.activeTool.type !== "laser"))) ||
getSelectedElements(elements, appState).length),
appState.openDialog?.name !== "elementLinkSelector" &&
((appState.activeTool.type !== "custom" &&
(appState.editingTextElement ||
(appState.activeTool.type !== "selection" &&
appState.activeTool.type !== "lasso" &&
appState.activeTool.type !== "eraser" &&
appState.activeTool.type !== "hand" &&
appState.activeTool.type !== "laser"))) ||
getSelectedElements(elements, appState).length),
);
+1 -1
View File
@@ -89,7 +89,7 @@ const CJK = {
* BREAK BEFORE "「"
* BREAK AFTER "」"
*/
// eslint-disable-next-line prettier/prettier
// prettier-ignore
OPENING://u,
CLOSING: //u,
/**
+89 -92
View File
@@ -73,104 +73,101 @@ export type ValidLinearElement = {
textAlign?: TextAlign;
verticalAlign?: VerticalAlign;
} & MarkOptional<ElementConstructorOpts, "x" | "y">;
end?:
end?: (
| (
| (
| {
type: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
id?: ExcalidrawGenericElement["id"];
}
| {
id: ExcalidrawGenericElement["id"];
type?: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
}
)
| ((
| {
type: "text";
text: string;
}
| {
type?: "text";
id: ExcalidrawTextElement["id"];
text: string;
}
) &
Partial<ExcalidrawTextElement>)
| {
type: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
id?: ExcalidrawGenericElement["id"];
}
| {
id: ExcalidrawGenericElement["id"];
type?: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
}
)
| ((
| {
type: "text";
text: string;
}
| {
type?: "text";
id: ExcalidrawTextElement["id"];
text: string;
}
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
start?:
Partial<ExcalidrawTextElement>)
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
start?: (
| (
| (
| {
type: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
id?: ExcalidrawGenericElement["id"];
}
| {
id: ExcalidrawGenericElement["id"];
type?: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
}
)
| ((
| {
type: "text";
text: string;
}
| {
type?: "text";
id: ExcalidrawTextElement["id"];
text: string;
}
) &
Partial<ExcalidrawTextElement>)
| {
type: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
id?: ExcalidrawGenericElement["id"];
}
| {
id: ExcalidrawGenericElement["id"];
type?: Exclude<
ExcalidrawBindableElement["type"],
| "image"
| "text"
| "frame"
| "magicframe"
| "embeddable"
| "iframe"
>;
}
)
| ((
| {
type: "text";
text: string;
}
| {
type?: "text";
id: ExcalidrawTextElement["id"];
text: string;
}
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
Partial<ExcalidrawTextElement>)
) &
MarkOptional<ElementConstructorOpts, "x" | "y">;
} & Partial<ExcalidrawLinearElement>;
export type ValidContainer =
| {
type: Exclude<ExcalidrawGenericElement["type"], "selection">;
id?: ExcalidrawGenericElement["id"];
label?: {
text: string;
fontSize?: number;
fontFamily?: FontFamilyValues;
textAlign?: TextAlign;
verticalAlign?: VerticalAlign;
} & MarkOptional<ElementConstructorOpts, "x" | "y">;
} & ElementConstructorOpts;
export type ValidContainer = {
type: Exclude<ExcalidrawGenericElement["type"], "selection">;
id?: ExcalidrawGenericElement["id"];
label?: {
text: string;
fontSize?: number;
fontFamily?: FontFamilyValues;
textAlign?: TextAlign;
verticalAlign?: VerticalAlign;
} & MarkOptional<ElementConstructorOpts, "x" | "y">;
} & ElementConstructorOpts;
export type ExcalidrawElementSkeleton =
| Extract<
+2 -2
View File
@@ -312,8 +312,8 @@ export const getTransformHandles = (
const margin = isLinearElement(element)
? DEFAULT_TRANSFORM_HANDLE_SPACING + 8
: isImageElement(element)
? 0
: DEFAULT_TRANSFORM_HANDLE_SPACING;
? 0
: DEFAULT_TRANSFORM_HANDLE_SPACING;
return getTransformHandlesFromCoords(
getElementAbsoluteCoords(element, elementsMap, true),
element.angle,
+12 -13
View File
@@ -18,18 +18,18 @@ import type {
export type ChartType = "bar" | "line";
export type FillStyle = "hachure" | "cross-hatch" | "solid" | "zigzag";
export type FontFamilyKeys = keyof typeof FONT_FAMILY;
export type FontFamilyValues = typeof FONT_FAMILY[FontFamilyKeys];
export type Theme = typeof THEME[keyof typeof THEME];
export type FontFamilyValues = (typeof FONT_FAMILY)[FontFamilyKeys];
export type Theme = (typeof THEME)[keyof typeof THEME];
export type FontString = string & { _brand: "fontString" };
export type GroupId = string;
export type PointerType = "mouse" | "pen" | "touch";
export type StrokeRoundness = "round" | "sharp";
export type RoundnessType = ValueOf<typeof ROUNDNESS>;
export type StrokeStyle = "solid" | "dashed" | "dotted";
export type TextAlign = typeof TEXT_ALIGN[keyof typeof TEXT_ALIGN];
export type TextAlign = (typeof TEXT_ALIGN)[keyof typeof TEXT_ALIGN];
type VerticalAlignKeys = keyof typeof VERTICAL_ALIGN;
export type VerticalAlign = typeof VERTICAL_ALIGN[VerticalAlignKeys];
export type VerticalAlign = (typeof VERTICAL_ALIGN)[VerticalAlignKeys];
export type FractionalIndex = string & { _brand: "franctionalIndex" };
export type BoundElement = Readonly<{
@@ -124,15 +124,14 @@ export type ExcalidrawIframeLikeElement =
| ExcalidrawIframeElement
| ExcalidrawEmbeddableElement;
export type IframeData =
| {
intrinsicSize: { w: number; h: number };
error?: Error;
sandbox?: { allowSameOrigin?: boolean };
} & (
| { type: "video" | "generic"; link: string }
| { type: "document"; srcdoc: (theme: Theme) => string }
);
export type IframeData = {
intrinsicSize: { w: number; h: number };
error?: Error;
sandbox?: { allowSameOrigin?: boolean };
} & (
| { type: "video" | "generic"; link: string }
| { type: "document"; srcdoc: (theme: Theme) => string }
);
export type ImageCrop = {
x: number;
+2 -1
View File
@@ -252,6 +252,7 @@ const addToCurrentFrame = (element: DebugElement) => {
if (window.visualDebug?.data && window.visualDebug.data.length === 0) {
window.visualDebug.data[0] = [];
}
window.visualDebug?.data &&
if (window.visualDebug?.data) {
window.visualDebug.data[window.visualDebug.data.length - 1].push(element);
}
};
+1 -1
View File
@@ -335,7 +335,7 @@ const shiftElementsByOne = (
.map((idx) => elements[idx].id),
);
groupedIndices.forEach((indices, i) => {
groupedIndices.forEach((indices) => {
const leadingIndex = indices[0];
const trailingIndex = indices[indices.length - 1];
const boundaryIndex = direction === "left" ? leadingIndex : trailingIndex;
+1 -1
View File
@@ -37,7 +37,7 @@ const _ce = ({
width: w,
height: h,
angle: a,
} as ExcalidrawElement);
}) as ExcalidrawElement;
describe("getElementAbsoluteCoords", () => {
it("test x1 coordinate", () => {
+1 -1
View File
@@ -24,7 +24,7 @@ describe("Test measureText", () => {
...params,
});
expect(getContainerCoords(element)).toEqual({
x: 44.2893218813452455,
x: 44.289321881345245,
y: 39.64466094067262,
});
});
-6
View File
@@ -974,7 +974,6 @@ define: {
- Exposed `DefaultSidebar` component to allow modifying the default sidebar, such as adding custom tabs to it. [#6213](https://github.com/excalidraw/excalidraw/pull/6213)
#### BREAKING CHANGES
- `props.renderSidebar` is removed in favor of rendering as `children`.
- `appState.isSidebarDocked` replaced with `appState.defaultSidebarDockedPreference` with slightly different semantics, and relating only to the default sidebar. You need to handle `docked` state for your custom sidebars yourself.
- Sidebar `props.dockable` is removed. To indicate dockability, supply `props.onDock()` alongside setting `props.docked`.
@@ -1929,11 +1928,9 @@ Check out the [release notes](https://github.com/excalidraw/excalidraw/releases/
- [`scrollToContent`](https://github.com/excalidraw/excalidraw/blob/master/src/components/App.tsx#L265) API now supports passing just a single Excalidraw element, or none at all (which will default to current elements on the scene) [#3482](https://github.com/excalidraw/excalidraw/pull/3482).
#### BREAKING CHANGE
- Renamed `setScrollToContent` to [`scrollToContent`](https://github.com/excalidraw/excalidraw/blob/master/src/components/App.tsx#L265).
- Make library local to given excalidraw instance (previously, all instances on the same page shared one global library) [#3451](https://github.com/excalidraw/excalidraw/pull/3451).
- Added prop [onLibraryChange](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#onLibraryChange) which if supplied will be called when library is updated.
- Added attribute `libraryItems` to prop [initialData](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#initialdata) which can be used to load excalidraw with existing library items.
@@ -1941,13 +1938,11 @@ Check out the [release notes](https://github.com/excalidraw/excalidraw/releases/
- Assign a [unique id](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#Id) to the excalidraw component. The id can be accessed via [`ref`](https://github.com/excalidraw/excalidraw/blob/master/src/components/App.tsx#L298).
#### BREAKING CHANGE
- From now on the host application is responsible for [persisting the library](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#onLibraryChange) to LocalStorage (or elsewhere), and [importing it on mount](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#initialdata).
- Bind the keyboard events to component and added a prop [`handleKeyboardGlobally`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#handleKeyboardGlobally) which if set to true will bind the keyboard events to document [#3430](https://github.com/excalidraw/excalidraw/pull/3430).
#### BREAKING CHANGE
- Earlier keyboard events were bind to document but now its bind to Excalidraw component by default. So you will need to set [`handleKeyboardGlobally`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#handleKeyboardGlobally) to true if you want the previous behaviour (bind the keyboard events to document).
- Recompute offsets on `scroll` of the nearest scrollable container [#3408](https://github.com/excalidraw/excalidraw/pull/3408). This can be disabled by setting [`detectScroll`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#detectScroll) to `false`.
@@ -1969,7 +1964,6 @@ Check out the [release notes](https://github.com/excalidraw/excalidraw/releases/
### Refactor
- #### BREAKING CHANGE
- Removed exposing `getSyncableElements` helper which was specific to excalidraw app collab implementation [#3471](https://github.com/excalidraw/excalidraw/pull/3471). If you happened to use it, you can easily reimplement it yourself using the newly exposed [isInvisiblySmallElement](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#isInvisiblySmallElement) helper:
```ts
@@ -158,7 +158,9 @@ export const actionBindText = register({
verticalAlign: VERTICAL_ALIGN.MIDDLE,
textAlign: TEXT_ALIGN.CENTER,
autoResize: true,
angle: (isArrowElement(container) ? 0 : container?.angle ?? 0) as Radians,
angle: (isArrowElement(container)
? 0
: (container?.angle ?? 0)) as Radians,
});
app.scene.mutateElement(container, {
boundElements: (container.boundElements || []).concat({
+6 -7
View File
@@ -64,12 +64,12 @@ export const actionChangeViewBackgroundColor = register<Partial<AppState>>({
perform: (_, appState, value) => {
return {
appState: { ...appState, ...value },
captureUpdate: !!value?.viewBackgroundColor
captureUpdate: value?.viewBackgroundColor
? CaptureUpdateAction.IMMEDIATELY
: CaptureUpdateAction.EVENTUALLY,
};
},
PanelComponent: ({ elements, appState, updateData, appProps, data }) => {
PanelComponent: ({ elements, appState, updateData }) => {
// FIXME move me to src/components/mainMenu/DefaultItems.tsx
return (
<ColorPicker
@@ -138,7 +138,7 @@ export const actionZoomIn = register({
viewMode: true,
icon: ZoomInIcon,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
perform: (_elements, appState) => {
return {
appState: {
...appState,
@@ -179,7 +179,7 @@ export const actionZoomOut = register({
icon: ZoomOutIcon,
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
perform: (_elements, appState) => {
return {
appState: {
...appState,
@@ -220,7 +220,7 @@ export const actionResetZoom = register({
icon: ZoomResetIcon,
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
perform: (_elements, appState) => {
return {
appState: {
...appState,
@@ -474,8 +474,7 @@ export const actionToggleTheme = register<AppState["theme"]>({
: "buttons.darkMode";
},
keywords: ["toggle", "dark", "light", "mode", "theme"],
icon: (appState, elements) =>
appState.theme === THEME.LIGHT ? MoonIcon : SunIcon,
icon: (appState) => (appState.theme === THEME.LIGHT ? MoonIcon : SunIcon),
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_, appState, value) => {
@@ -263,7 +263,7 @@ export const copyText = register({
try {
copyTextToSystemClipboard(getTextFromElements(selectedElements));
} catch (e) {
} catch {
throw new Error(t("errors.copyToSystemClipboardFailed"));
}
return {
@@ -43,7 +43,7 @@ export const actionToggleCropEditor = register({
}
return false;
},
PanelComponent: ({ appState, updateData, app }) => {
PanelComponent: ({ updateData }) => {
const label = t("helpDialog.cropStart");
return (
@@ -302,10 +302,10 @@ export const actionDeleteSelected = register({
: CaptureUpdateAction.EVENTUALLY,
};
},
keyTest: (event, appState, elements) =>
keyTest: (event) =>
(event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE) &&
!event[KEYS.CTRL_OR_CMD],
PanelComponent: ({ elements, appState, updateData, app }) => {
PanelComponent: ({ elements, appState, updateData }) => {
const isMobile = useStylesPanelMode() === "mobile";
return (
@@ -109,7 +109,7 @@ export const actionDuplicateSelection = register({
};
},
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.D,
PanelComponent: ({ elements, appState, updateData, app }) => {
PanelComponent: ({ elements, appState, updateData }) => {
const isMobile = useStylesPanelMode() === "mobile";
return (
@@ -100,7 +100,7 @@ export const actionLinkToElement = register({
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
predicate: (elements, appState, appProps, app) => {
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
@@ -120,8 +120,8 @@ export const actionToggleElementLock = register({
? newGroupId
? newGroupId
: isAGroup
? selectedElements[0].groupIds.at(-1)!
: selectedElements[0].id
? selectedElements[0].groupIds.at(-1)!
: selectedElements[0].id
: null;
return {
+1 -1
View File
@@ -43,7 +43,7 @@ export const actionChangeProjectName = register<AppState["name"]>({
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
PanelComponent: ({ appState, updateData, appProps, data, app }) => (
PanelComponent: ({ updateData, data, app }) => (
<ProjectName
label={t("labels.fileTitle")}
value={app.getName()}
+8 -5
View File
@@ -55,10 +55,13 @@ export const actionSelectAllElementsInFrame = register({
elements,
appState: {
...appState,
selectedElementIds: elementsInFrame.reduce((acc, element) => {
acc[element.id] = true;
return acc;
}, {} as Record<ExcalidrawElement["id"], true>),
selectedElementIds: elementsInFrame.reduce(
(acc, element) => {
acc[element.id] = true;
return acc;
},
{} as Record<ExcalidrawElement["id"], true>,
),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
@@ -164,7 +167,7 @@ export const actionWrapSelectionInFrame = register({
name: "wrapSelectionInFrame",
label: "labels.wrapSelectionInFrame",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
+1 -1
View File
@@ -140,7 +140,7 @@ export const actionGroup = register({
if (groupingElementsFromDifferentFrames) {
const frameElementsMap = groupByFrameLikes(selectedElements);
frameElementsMap.forEach((elementsInFrame, frameId) => {
frameElementsMap.forEach((elementsInFrame) => {
removeElementsFromFrame(
elementsInFrame,
app.scene.getNonDeletedElementsMap(),
@@ -75,7 +75,7 @@ export const createUndoAction: ActionCreator = (history) => ({
),
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && matchKey(event, KEYS.Z) && !event.shiftKey,
PanelComponent: ({ appState, updateData, data, app }) => {
PanelComponent: ({ updateData, data }) => {
const { isUndoStackEmpty } = useEmitter<HistoryChangedEvent>(
history.onHistoryChangedEmitter,
new HistoryChangedEvent(
@@ -115,7 +115,7 @@ export const createRedoAction: ActionCreator = (history) => ({
keyTest: (event) =>
(event[KEYS.CTRL_OR_CMD] && event.shiftKey && matchKey(event, KEYS.Z)) ||
(isWindows && event.ctrlKey && !event.shiftKey && matchKey(event, KEYS.Y)),
PanelComponent: ({ appState, updateData, data, app }) => {
PanelComponent: ({ updateData, data }) => {
const { isRedoStackEmpty } = useEmitter(
history.onHistoryChangedEmitter,
new HistoryChangedEvent(
@@ -56,7 +56,7 @@ export const actionGoToCollaborator = register<Collaborator>({
captureUpdate: CaptureUpdateAction.EVENTUALLY,
};
},
PanelComponent: ({ updateData, data, appState }) => {
PanelComponent: ({ updateData, data }) => {
const { socketId, collaborator, withName, isBeingFollowed } =
data as GoToCollaboratorComponentProps;
@@ -301,7 +301,7 @@ const changeFontSize = (
currentItemFontSize:
newFontSizes.size === 1
? [...newFontSizes][0]
: fallbackValue ?? appState.currentItemFontSize,
: (fallbackValue ?? appState.currentItemFontSize),
},
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
@@ -335,12 +335,12 @@ export const actionChangeStrokeColor = register<
...appState,
...value,
},
captureUpdate: !!value?.currentItemStrokeColor
captureUpdate: value?.currentItemStrokeColor
? CaptureUpdateAction.IMMEDIATELY
: CaptureUpdateAction.EVENTUALLY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => {
PanelComponent: ({ elements, appState, updateData, app }) => {
const { stylesPanelMode } = getStylesPanelInfo(app);
return (
@@ -425,7 +425,7 @@ export const actionChangeBackgroundColor = register<
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => {
PanelComponent: ({ elements, appState, updateData, app }) => {
const { stylesPanelMode } = getStylesPanelInfo(app);
return (
@@ -557,7 +557,7 @@ export const actionChangeStrokeWidth = register<
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<fieldset>
<legend>{t("labels.strokeWidth")}</legend>
<div className="buttonList">
@@ -614,7 +614,7 @@ export const actionChangeSloppiness = register<ExcalidrawElement["roughness"]>({
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<fieldset>
<legend>{t("labels.sloppiness")}</legend>
<div className="buttonList">
@@ -669,7 +669,7 @@ export const actionChangeStrokeStyle = register<
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
};
},
PanelComponent: ({ elements, appState, updateData, app, data }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<fieldset>
<legend>{t("labels.strokeStyle")}</legend>
<div className="buttonList">
@@ -984,7 +984,7 @@ export const actionChangeFontFamily = register<{
const fontsCache = Array.from(Fonts.loadedFontsCache.values());
const fontFamily = Object.entries(FONT_FAMILY).find(
([_, value]) => value === nextFontFamily,
([, value]) => value === nextFontFamily,
)?.[0];
// skip `document.font.check` check on hover, if at least one font family has loaded as it's super slow (could result in slightly different bbox, which is fine)
@@ -1414,19 +1414,19 @@ export const actionChangeVerticalAlign = register<VerticalAlign>({
{
value: VERTICAL_ALIGN.TOP,
text: t("labels.alignTop"),
icon: <TextAlignTopIcon theme={appState.theme} />,
icon: <TextAlignTopIcon />,
testId: "align-top",
},
{
value: VERTICAL_ALIGN.MIDDLE,
text: t("labels.centerVertically"),
icon: <TextAlignMiddleIcon theme={appState.theme} />,
icon: <TextAlignMiddleIcon />,
testId: "align-middle",
},
{
value: VERTICAL_ALIGN.BOTTOM,
text: t("labels.alignBottom"),
icon: <TextAlignBottomIcon theme={appState.theme} />,
icon: <TextAlignBottomIcon />,
testId: "align-bottom",
},
]}
@@ -1533,8 +1533,8 @@ export const actionChangeRoundness = register<"sharp" | "round">({
hasLegacyRoundness
? null
: element.roundness
? "round"
: "sharp",
? "round"
: "sharp",
(element) =>
!isArrowElement(element) && element.hasOwnProperty("roundness"),
(hasSelection) =>
@@ -1715,12 +1715,12 @@ export const actionChangeArrowProperties = register({
name: "changeArrowProperties",
label: "Change arrow properties",
trackEvent: false,
perform: (elements, appState, value, app) => {
perform: () => {
// This action doesn't perform any changes directly
// It's just a container for the arrow type and arrowhead actions
return false;
},
PanelComponent: ({ elements, appState, updateData, app, renderAction }) => {
PanelComponent: ({ renderAction }) => {
return (
<div className="selected-shape-actions">
{renderAction("changeArrowhead")}
@@ -1953,8 +1953,8 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
return element.elbowed
? ARROW_TYPE.elbow
: element.roundness
? ARROW_TYPE.round
: ARROW_TYPE.sharp;
? ARROW_TYPE.round
: ARROW_TYPE.sharp;
}
return null;
@@ -11,14 +11,12 @@ import { getSelectedElements } from "../scene";
import { register } from "./register";
import type { AppClassProperties } from "../types";
export const actionTextAutoResize = register({
name: "autoResize",
label: "labels.autoResize",
icon: null,
trackEvent: { category: "element" },
predicate: (elements, appState, _: unknown, app: AppClassProperties) => {
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
selectedElements.length === 1 &&
@@ -26,7 +24,7 @@ export const actionTextAutoResize = register({
!selectedElements[0].autoResize
);
},
perform: (elements, appState, _, app) => {
perform: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return {
@@ -20,7 +20,7 @@ export const actionToggleShapeSwitch = register({
action: "toggle",
},
keywords: ["change", "switch", "swap"],
perform(elements, appState, _, app) {
perform() {
editorJotaiStore.set(convertElementTypePopupAtom, {
type: "panel",
});
@@ -30,6 +30,6 @@ export const actionToggleShapeSwitch = register({
};
},
checked: (appState) => appState.gridModeEnabled,
predicate: (elements, appState, props) =>
predicate: (elements) =>
getConversionTypeFromElements(elements as ExcalidrawElement[]) !== null,
});
+5 -5
View File
@@ -38,7 +38,7 @@ export const actionSendBackward = register({
event[KEYS.CTRL_OR_CMD] &&
!event.shiftKey &&
event.code === CODES.BRACKET_LEFT,
PanelComponent: ({ updateData, appState }) => (
PanelComponent: ({ updateData }) => (
<button
type="button"
className="zIndexButton"
@@ -68,7 +68,7 @@ export const actionBringForward = register({
event[KEYS.CTRL_OR_CMD] &&
!event.shiftKey &&
event.code === CODES.BRACKET_RIGHT,
PanelComponent: ({ updateData, appState }) => (
PanelComponent: ({ updateData }) => (
<button
type="button"
className="zIndexButton"
@@ -101,7 +101,7 @@ export const actionSendToBack = register({
: event[KEYS.CTRL_OR_CMD] &&
event.shiftKey &&
event.code === CODES.BRACKET_LEFT,
PanelComponent: ({ updateData, appState }) => (
PanelComponent: ({ updateData }) => (
<button
type="button"
className="zIndexButton"
@@ -139,11 +139,11 @@ export const actionBringToFront = register({
: event[KEYS.CTRL_OR_CMD] &&
event.shiftKey &&
event.code === CODES.BRACKET_RIGHT,
PanelComponent: ({ updateData, appState }) => (
PanelComponent: ({ updateData }) => (
<button
type="button"
className="zIndexButton"
onClick={(event) => updateData(null)}
onClick={() => updateData(null)}
title={`${t("labels.bringToFront")}${
isDarwin
? getShortcutKey("CtrlOrCmd+Alt+]")
+2 -2
View File
@@ -263,11 +263,11 @@ const _clearAppStateForStorage = <
exportType: ExportType,
) => {
type ExportableKeys = {
[K in keyof typeof APP_STATE_STORAGE_CONF]: typeof APP_STATE_STORAGE_CONF[K][ExportType] extends true
[K in keyof typeof APP_STATE_STORAGE_CONF]: (typeof APP_STATE_STORAGE_CONF)[K][ExportType] extends true
? K
: never;
}[keyof typeof APP_STATE_STORAGE_CONF];
const stateForExport = {} as { [K in ExportableKeys]?: typeof appState[K] };
const stateForExport = {} as { [K in ExportableKeys]?: (typeof appState)[K] };
for (const key of Object.keys(appState) as (keyof typeof appState)[]) {
const propConfig = APP_STATE_STORAGE_CONF[key];
if (propConfig?.[exportType]) {
+2 -2
View File
@@ -59,7 +59,7 @@ export interface ClipboardData {
programmaticAPI?: boolean;
}
type AllowedPasteMimeTypes = typeof ALLOWED_PASTE_MIME_TYPES[number];
type AllowedPasteMimeTypes = (typeof ALLOWED_PASTE_MIME_TYPES)[number];
type ParsedClipboardEventTextData =
| { type: "text"; value: string }
@@ -242,7 +242,7 @@ function parseHTMLTree(el: ChildNode) {
}
const maybeParseHTMLDataItem = (
dataItem: ParsedDataTransferItemType<typeof MIME_TYPES["html"]>,
dataItem: ParsedDataTransferItemType<(typeof MIME_TYPES)["html"]>,
): { type: "mixedContent"; value: PastedMixedContent } | null => {
const html = dataItem.value;
+10 -11
View File
@@ -479,8 +479,8 @@ const CombinedArrowProperties = ({
return element.elbowed
? "elbow"
: element.roundness
? "round"
: "sharp";
? "round"
: "sharp";
}
return null;
},
@@ -1081,7 +1081,7 @@ export const ShapesSwitcher = ({
return (
<>
{getToolbarTools(app).map(
({ value, icon, key, numericKey, fillable }, index) => {
({ value, icon, key, numericKey, fillable }) => {
if (
UIOptions.tools?.[
value as Extract<
@@ -1160,7 +1160,7 @@ export const ShapesSwitcher = ({
}
}
}}
onChange={({ pointerType }) => {
onChange={() => {
if (app.state.activeTool.type !== value) {
trackEvent("toolbar", value, "ui");
}
@@ -1199,12 +1199,12 @@ export const ShapesSwitcher = ({
{frameToolSelected
? frameToolIcon
: embeddableToolSelected
? EmbedIcon
: laserToolSelected && !app.props.isCollaborating
? laserPointerToolIcon
: lassoToolSelected
? LassoIcon
: extraToolsIcon}
? EmbedIcon
: laserToolSelected && !app.props.isCollaborating
? laserPointerToolIcon
: lassoToolSelected
? LassoIcon
: extraToolsIcon}
</DropdownMenu.Trigger>
<DropdownMenu.Content
onClickOutside={() => setIsExtraToolsMenuOpen(false)}
@@ -1276,7 +1276,6 @@ export const ShapesSwitcher = ({
export const ZoomActions = ({
renderAction,
zoom,
}: {
renderAction: ActionManager["renderAction"];
zoom: Zoom;
+48 -38
View File
@@ -810,7 +810,7 @@ class App extends React.Component<AppProps, AppState> {
let data = null;
try {
data = JSON.parse(event.data);
} catch (e) {}
} catch {}
if (!data) {
return;
}
@@ -1105,13 +1105,13 @@ class App extends React.Component<AppProps, AppState> {
const currentBinding = startDragged
? "startBinding"
: endDragged
? "endBinding"
: null;
? "endBinding"
: null;
const otherBinding = startDragged
? "endBinding"
: endDragged
? "startBinding"
: null;
? "startBinding"
: null;
const isAlreadyInsideBindingToSameElement =
(otherBinding &&
arrow[otherBinding]?.mode === "inside" &&
@@ -1611,7 +1611,7 @@ class App extends React.Component<AppProps, AppState> {
: undefined
}
src={
src?.type !== "document" ? src?.link ?? "" : undefined
src?.type !== "document" ? (src?.link ?? "") : undefined
}
// https://stackoverflow.com/q/18470015
scrolling="no"
@@ -2825,7 +2825,7 @@ class App extends React.Component<AppProps, AppState> {
this.stylesPanelMode = nextStylesPanelMode;
if (prevStylesPanelMode !== "full" && nextStylesPanelMode === "full") {
this.setState((prevState) => ({
this.setState(() => ({
preferredSelectionTool: {
type: "selection",
initialized: true,
@@ -2931,6 +2931,7 @@ class App extends React.Component<AppProps, AppState> {
// note that this check seems to always pass in localhost
if (isBrave() && !isMeasureTextSupported()) {
// oxlint-disable-next-line react/no-did-mount-set-state
this.setState({
errorMessage: <BraveMeasureTextError />,
});
@@ -3243,8 +3244,9 @@ class App extends React.Component<AppProps, AppState> {
// execute only if the condition still holds when the deferred callback
// executes (it can be scheduled multiple times depending on how
// many times the component renders)
this.state.selectedLinearElement?.isEditing &&
if (this.state.selectedLinearElement?.isEditing) {
this.actionManager.executeAction(actionFinalize);
}
});
}
@@ -3633,14 +3635,14 @@ class App extends React.Component<AppProps, AppState> {
typeof opts.position === "object"
? opts.position.clientX
: opts.position === "cursor"
? this.lastViewportPosition.x
: this.state.width / 2 + this.state.offsetLeft;
? this.lastViewportPosition.x
: this.state.width / 2 + this.state.offsetLeft;
const clientY =
typeof opts.position === "object"
? opts.position.clientY
: opts.position === "cursor"
? this.lastViewportPosition.y
: this.state.height / 2 + this.state.offsetTop;
? this.lastViewportPosition.y
: this.state.height / 2 + this.state.offsetTop;
const { x, y } = viewportCoordsToSceneCoords(
{ clientX, clientY },
@@ -4898,8 +4900,8 @@ class App extends React.Component<AppProps, AppState> {
prevState.currentItemArrowType === ARROW_TYPE.sharp
? ARROW_TYPE.round
: prevState.currentItemArrowType === ARROW_TYPE.round
? ARROW_TYPE.elbow
: ARROW_TYPE.sharp,
? ARROW_TYPE.elbow
: ARROW_TYPE.sharp,
}));
}
this.setActiveTool({ type: shape });
@@ -5370,9 +5372,9 @@ class App extends React.Component<AppProps, AppState> {
const elementsMap = this.scene.getElementsMapIncludingDeleted();
const updateElement = (nextOriginalText: string, isDeleted: boolean) => {
this.scene.replaceAllElements([
this.scene.replaceAllElements(
// Not sure why we include deleted elements as well hence using deleted elements map
...this.scene.getElementsIncludingDeleted().map((_element) => {
this.scene.getElementsIncludingDeleted().map((_element) => {
if (_element.id === element.id && isTextElement(_element)) {
return newElementWith(_element, {
originalText: nextOriginalText,
@@ -5388,7 +5390,7 @@ class App extends React.Component<AppProps, AppState> {
}
return _element;
}),
]);
);
};
textWysiwyg({
@@ -6112,10 +6114,7 @@ class App extends React.Component<AppProps, AppState> {
}
};
private redirectToLink = (
event: React.PointerEvent<HTMLCanvasElement>,
isTouchScreen: boolean,
) => {
private redirectToLink = (event: React.PointerEvent<HTMLCanvasElement>) => {
const draggedDistance = pointDistance(
pointFrom(
this.lastPointerDownEvent!.clientX,
@@ -6379,7 +6378,7 @@ class App extends React.Component<AppProps, AppState> {
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
(el) => maxBindingDistance_simple(this.state.zoom),
() => maxBindingDistance_simple(this.state.zoom),
);
if (hoveredElement) {
this.setState({
@@ -6410,7 +6409,7 @@ class App extends React.Component<AppProps, AppState> {
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
(el) => maxBindingDistance_simple(this.state.zoom),
() => maxBindingDistance_simple(this.state.zoom),
);
if (hoveredElement) {
this.actionManager.executeAction(actionFinalize, "ui", {
@@ -6564,7 +6563,7 @@ class App extends React.Component<AppProps, AppState> {
pointFrom<GlobalPoint>(scenePointerX, scenePointerY),
this.scene.getNonDeletedElements(),
this.scene.getNonDeletedElementsMap(),
(el) => maxBindingDistance_simple(this.state.zoom),
() => maxBindingDistance_simple(this.state.zoom),
);
if (
hit &&
@@ -6820,7 +6819,7 @@ class App extends React.Component<AppProps, AppState> {
};
// set touch moving for mobile context menu
private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
private handleTouchMove = () => {
invalidateContextMenu = true;
};
@@ -7039,7 +7038,7 @@ class App extends React.Component<AppProps, AppState> {
//fires only once, if pen is detected, penMode is enabled
//the user can disable this by toggling the penMode button
if (!this.state.penDetected && event.pointerType === "pen") {
this.setState((prevState) => {
this.setState(() => {
return {
penMode: true,
penDetected: true,
@@ -7207,7 +7206,9 @@ class App extends React.Component<AppProps, AppState> {
Object.keys(prevState.selectedElementIds).forEach((id) => {
const element = this.scene.getElement(id);
element && previouslySelectedElements.push(element);
if (element) {
previouslySelectedElements.push(element);
}
});
const hitElement = pointerDownState.hit.element!;
@@ -7435,7 +7436,7 @@ class App extends React.Component<AppProps, AppState> {
) {
this.handleEmbeddableCenterClick(this.hitLinkElement);
} else {
this.redirectToLink(event, this.editorInterface.isTouchScreen);
this.redirectToLink(event);
}
} else if (this.state.viewModeEnabled) {
this.setState({
@@ -7518,7 +7519,7 @@ class App extends React.Component<AppProps, AppState> {
let nextPastePrevented = false;
const isLinux =
typeof window === undefined
typeof window === "undefined"
? false
: /Linux/.test(window.navigator.platform);
@@ -7642,12 +7643,13 @@ class App extends React.Component<AppProps, AppState> {
),
// we need to duplicate because we'll be updating this state
lastCoords: { ...origin },
originalElements: this.scene
.getNonDeletedElements()
.reduce((acc, element) => {
originalElements: this.scene.getNonDeletedElements().reduce(
(acc, element) => {
acc.set(element.id, deepCopyElement(element));
return acc;
}, new Map() as PointerDownState["originalElements"]),
},
new Map() as PointerDownState["originalElements"],
),
resize: {
handleType: false,
isResizing: false,
@@ -8031,7 +8033,9 @@ class App extends React.Component<AppProps, AppState> {
Object.keys(prevState.selectedElementIds).forEach((id) => {
const element = this.scene.getElement(id);
element && previouslySelectedElements.push(element);
if (element) {
previouslySelectedElements.push(element);
}
});
// if hitElement is frame-like, deselect all of its elements
@@ -8860,7 +8864,9 @@ class App extends React.Component<AppProps, AppState> {
): (event: KeyboardEvent) => void {
return withBatchedUpdates((event: KeyboardEvent) => {
// Prevents focus from escaping excalidraw tab
event.key === KEYS.ALT && event.preventDefault();
if (event.key === KEYS.ALT) {
event.preventDefault();
}
if (this.maybeHandleResize(pointerDownState, event)) {
return;
}
@@ -9850,7 +9856,9 @@ class App extends React.Component<AppProps, AppState> {
.map((e) => elementsMap.get(e.id))
.filter((e) => isElbowArrow(e))
.forEach((e) => {
!!e && this.scene.mutateElement(e, {});
if (e) {
this.scene.mutateElement(e, {});
}
});
}
}
@@ -10079,7 +10087,7 @@ class App extends React.Component<AppProps, AppState> {
),
}));
} else {
this.setState((prevState) => ({
this.setState(() => ({
newElement: null,
}));
}
@@ -12091,7 +12099,9 @@ class App extends React.Component<AppProps, AppState> {
offsetTop,
},
() => {
cb && cb();
if (cb) {
cb();
}
},
);
}
+5 -6
View File
@@ -5,11 +5,10 @@ import { composeEventHandlers } from "@excalidraw/common";
import "./Button.scss";
interface ButtonProps
extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
> {
interface ButtonProps extends React.DetailedHTMLProps<
React.ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
> {
type?: "button" | "submit" | "reset";
onSelect: () => any;
/** whether button is in active state */
@@ -33,7 +32,7 @@ export const Button = ({
}: ButtonProps) => {
return (
<button
onClick={composeEventHandlers(rest.onClick, (event) => {
onClick={composeEventHandlers(rest.onClick, () => {
onSelect();
})}
type={type}

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