}
- | { status: "loaded"; libraryItems: LibraryItems }
->({ status: "loaded", libraryItems: [] });
+export const libraryItemsAtom = atom<{
+ status: "loading" | "loaded";
+ isInitialized: boolean;
+ libraryItems: LibraryItems;
+}>({ status: "loaded", isInitialized: true, libraryItems: [] });
const cloneLibraryItems = (libraryItems: LibraryItems): LibraryItems =>
JSON.parse(JSON.stringify(libraryItems));
@@ -40,12 +39,28 @@ const isUniqueItem = (
});
};
+/** Merges otherItems into localItems. Unique items in otherItems array are
+ sorted first. */
+export const mergeLibraryItems = (
+ localItems: LibraryItems,
+ otherItems: LibraryItems,
+): LibraryItems => {
+ const newItems = [];
+ for (const item of otherItems) {
+ if (isUniqueItem(localItems, item)) {
+ newItems.push(item);
+ }
+ }
+
+ return [...newItems, ...localItems];
+};
+
class Library {
- /** cache for currently active promise when initializing/updating libaries
- asynchronously */
- private libraryItemsPromise: Promise | null = null;
- /** last resolved libraryItems */
+ /** latest libraryItems */
private lastLibraryItems: LibraryItems = [];
+ /** indicates whether library is initialized with library items (has gone
+ * though at least one update) */
+ private isInitialized = false;
private app: App;
@@ -53,95 +68,138 @@ class Library {
this.app = app;
}
- resetLibrary = async () => {
- this.saveLibrary([]);
+ private updateQueue: Promise[] = [];
+
+ private getLastUpdateTask = (): Promise | undefined => {
+ return this.updateQueue[this.updateQueue.length - 1];
};
- /** imports library (currently merges, removing duplicates) */
- async importLibrary(
+ private notifyListeners = () => {
+ if (this.updateQueue.length > 0) {
+ jotaiStore.set(libraryItemsAtom, {
+ status: "loading",
+ libraryItems: this.lastLibraryItems,
+ isInitialized: this.isInitialized,
+ });
+ } else {
+ this.isInitialized = true;
+ jotaiStore.set(libraryItemsAtom, {
+ status: "loaded",
+ libraryItems: this.lastLibraryItems,
+ isInitialized: this.isInitialized,
+ });
+ try {
+ this.app.props.onLibraryChange?.(
+ cloneLibraryItems(this.lastLibraryItems),
+ );
+ } catch (error) {
+ console.error(error);
+ }
+ }
+ };
+
+ resetLibrary = () => {
+ return this.setLibrary([]);
+ };
+
+ /**
+ * imports library (from blob or libraryItems), merging with current library
+ * (attempting to remove duplicates)
+ */
+ importLibrary(
library:
| Blob
| Required["libraryItems"]
| Promise["libraryItems"]>,
defaultStatus: LibraryItem["status"] = "unpublished",
- ) {
- return this.saveLibrary(
- new Promise(async (resolve, reject) => {
- try {
- let libraryItems: LibraryItems;
- if (library instanceof Blob) {
- libraryItems = await loadLibraryFromBlob(library, defaultStatus);
- } else {
- libraryItems = restoreLibraryItems(await library, defaultStatus);
- }
-
- const existingLibraryItems = this.lastLibraryItems;
-
- const filteredItems = [];
- for (const item of libraryItems) {
- if (isUniqueItem(existingLibraryItems, item)) {
- filteredItems.push(item);
+ ): Promise {
+ return this.setLibrary(
+ () =>
+ new Promise(async (resolve, reject) => {
+ try {
+ let libraryItems: LibraryItems;
+ if (library instanceof Blob) {
+ libraryItems = await loadLibraryFromBlob(library, defaultStatus);
+ } else {
+ libraryItems = restoreLibraryItems(await library, defaultStatus);
}
- }
- resolve([...filteredItems, ...existingLibraryItems]);
- } catch (error) {
- reject(new Error(t("errors.importLibraryError")));
- }
- }),
+ resolve(mergeLibraryItems(this.lastLibraryItems, libraryItems));
+ } catch (error) {
+ reject(error);
+ }
+ }),
);
}
- loadLibrary = (): Promise => {
+ /**
+ * @returns latest cloned libraryItems. Awaits all in-progress updates first.
+ */
+ getLatestLibrary = (): Promise => {
return new Promise(async (resolve) => {
try {
- resolve(
- cloneLibraryItems(
- await (this.libraryItemsPromise || this.lastLibraryItems),
- ),
- );
+ const libraryItems = await (this.getLastUpdateTask() ||
+ this.lastLibraryItems);
+ if (this.updateQueue.length > 0) {
+ resolve(this.getLatestLibrary());
+ } else {
+ resolve(cloneLibraryItems(libraryItems));
+ }
} catch (error) {
return resolve(this.lastLibraryItems);
}
});
};
- saveLibrary = async (items: LibraryItems | Promise) => {
- const prevLibraryItems = this.lastLibraryItems;
- try {
- let nextLibraryItems;
- if (isPromiseLike(items)) {
- const promise = items.then((items) => cloneLibraryItems(items));
- this.libraryItemsPromise = promise;
- jotaiStore.set(libraryItemsAtom, {
- status: "loading",
- promise,
- libraryItems: null,
- });
- nextLibraryItems = await promise;
- } else {
- nextLibraryItems = cloneLibraryItems(items);
+ setLibrary = (
+ /**
+ * LibraryItems that will replace current items. Can be a function which
+ * will be invoked after all previous tasks are resolved
+ * (this is the prefered way to update the library to avoid race conditions,
+ * but you'll want to manually merge the library items in the callback
+ * - which is what we're doing in Library.importLibrary()).
+ *
+ * If supplied promise is rejected with AbortError, we swallow it and
+ * do not update the library.
+ */
+ libraryItems:
+ | LibraryItems
+ | Promise
+ | ((
+ latestLibraryItems: LibraryItems,
+ ) => LibraryItems | Promise),
+ ): Promise => {
+ const task = new Promise(async (resolve, reject) => {
+ try {
+ await this.getLastUpdateTask();
+
+ if (typeof libraryItems === "function") {
+ libraryItems = libraryItems(this.lastLibraryItems);
+ }
+
+ this.lastLibraryItems = cloneLibraryItems(await libraryItems);
+
+ resolve(this.lastLibraryItems);
+ } catch (error: any) {
+ reject(error);
}
-
- this.lastLibraryItems = nextLibraryItems;
- this.libraryItemsPromise = null;
-
- jotaiStore.set(libraryItemsAtom, {
- status: "loaded",
- libraryItems: nextLibraryItems,
+ })
+ .catch((error) => {
+ if (error.name === "AbortError") {
+ console.warn("Library update aborted by user");
+ return this.lastLibraryItems;
+ }
+ throw error;
+ })
+ .finally(() => {
+ this.updateQueue = this.updateQueue.filter((_task) => _task !== task);
+ this.notifyListeners();
});
- await this.app.props.onLibraryChange?.(
- cloneLibraryItems(nextLibraryItems),
- );
- } catch (error: any) {
- this.lastLibraryItems = prevLibraryItems;
- this.libraryItemsPromise = null;
- jotaiStore.set(libraryItemsAtom, {
- status: "loaded",
- libraryItems: prevLibraryItems,
- });
- throw error;
- }
+
+ this.updateQueue.push(task);
+ this.notifyListeners();
+
+ return task;
};
}
diff --git a/src/element/textWysiwyg.test.tsx b/src/element/textWysiwyg.test.tsx
index d9753c89b..ae7f1341c 100644
--- a/src/element/textWysiwyg.test.tsx
+++ b/src/element/textWysiwyg.test.tsx
@@ -544,6 +544,29 @@ describe("textWysiwyg", () => {
expect((h.elements[1] as ExcalidrawTextElement).containerId).toBe(null);
});
+ it("should'nt bind text to container when not double clicked on center", async () => {
+ expect(h.elements.length).toBe(1);
+ expect(h.elements[0].id).toBe(rectangle.id);
+
+ // clicking somewhere on top left
+ mouse.doubleClickAt(rectangle.x + 20, rectangle.y + 20);
+ expect(h.elements.length).toBe(2);
+
+ const text = h.elements[1] as ExcalidrawTextElementWithContainer;
+ expect(text.type).toBe("text");
+ expect(text.containerId).toBe(null);
+ mouse.down();
+ const editor = document.querySelector(
+ ".excalidraw-textEditorContainer > textarea",
+ ) as HTMLTextAreaElement;
+
+ fireEvent.change(editor, { target: { value: "Hello World!" } });
+
+ await new Promise((r) => setTimeout(r, 0));
+ editor.blur();
+ expect(rectangle.boundElements).toBe(null);
+ });
+
it("should update font family correctly on undo/redo by selecting bounded text when font family was updated", async () => {
expect(h.elements.length).toBe(1);
diff --git a/src/element/textWysiwyg.tsx b/src/element/textWysiwyg.tsx
index 4edea15db..1bd940deb 100644
--- a/src/element/textWysiwyg.tsx
+++ b/src/element/textWysiwyg.tsx
@@ -283,7 +283,14 @@ export const textWysiwyg = ({
// using scrollHeight here since we need to calculate
// number of lines so cannot use editable.style.height
// as that gets updated below
- const lines = editable.scrollHeight / getApproxLineHeight(font);
+ // Rounding here so that the lines calculated is more accurate in all browsers.
+ // The scrollHeight and approxLineHeight differs in diff browsers
+ // eg it gives 1.05 in firefox for handewritten small font due to which
+ // height gets updated as lines > 1 and leads to jumping text for first line in bound container
+ // hence rounding here to avoid that
+ const lines = Math.round(
+ editable.scrollHeight / getApproxLineHeight(font),
+ );
// auto increase height only when lines > 1 so its
// measured correctly and vertically aligns for
// first line as well as setting height to "auto"
@@ -298,7 +305,6 @@ export const textWysiwyg = ({
font,
container!.width,
).split("\n").length;
-
// This is browser behaviour when setting height to "auto"
// It sets the height needed for 2 lines even if actual
// line count is 1 as mentioned above as well
@@ -316,8 +322,6 @@ export const textWysiwyg = ({
}
editable.onkeydown = (event) => {
- event.stopPropagation();
-
if (!event.shiftKey && actionZoomIn.keyTest(event)) {
event.preventDefault();
app.actionManager.executeAction(actionZoomIn);
diff --git a/src/excalidraw-app/index.tsx b/src/excalidraw-app/index.tsx
index 5451a9c82..75f5ae149 100644
--- a/src/excalidraw-app/index.tsx
+++ b/src/excalidraw-app/index.tsx
@@ -19,7 +19,8 @@ import {
} from "../element/types";
import { useCallbackRefState } from "../hooks/useCallbackRefState";
import { Language, t } from "../i18n";
-import Excalidraw, {
+import {
+ Excalidraw,
defaultLang,
languages,
} from "../packages/excalidraw/index";
diff --git a/src/global.d.ts b/src/global.d.ts
index 4d607b9a7..dbaf3922e 100644
--- a/src/global.d.ts
+++ b/src/global.d.ts
@@ -13,6 +13,7 @@ interface Window {
ClipboardItem: any;
__EXCALIDRAW_SHA__: string | undefined;
EXCALIDRAW_ASSET_PATH: string | undefined;
+ EXCALIDRAW_EXPORT_SOURCE: string;
gtag: Function;
}
diff --git a/src/packages/excalidraw/CHANGELOG.md b/src/packages/excalidraw/CHANGELOG.md
index e3aa056d8..402cfd79c 100644
--- a/src/packages/excalidraw/CHANGELOG.md
+++ b/src/packages/excalidraw/CHANGELOG.md
@@ -17,11 +17,18 @@ Please add the latest change on the top under the correct section.
#### Features
+- Export [`MIME_TYPES`](https://github.com/excalidraw/excalidraw/blob/master/src/constants.ts#L92) supported by Excalidraw [#5135](https://github.com/excalidraw/excalidraw/pull/5135).
+- Support [`src`](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L50) for collaborators. Now onwards host can pass `src` to render the customized avatar for collaborators [#5114](https://github.com/excalidraw/excalidraw/pull/5114).
+- Support `libraryItems` argument in `initialData.libraryItems` and `updateScene({ libraryItems })` to be a Promise resolving to `LibraryItems`, and support functional update of `libraryItems` in [`updateScene({ libraryItems })`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#updateScene). [#5101](https://github.com/excalidraw/excalidraw/pull/5101).
+- Expose util [`mergeLibraryItems`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#mergeLibraryItems) [#5101](https://github.com/excalidraw/excalidraw/pull/5101).
+- Expose util [`exportToClipboard`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#exportToClipboard) which allows to copy the scene contents to clipboard as `svg`, `png` or `json` [#5103](https://github.com/excalidraw/excalidraw/pull/5103).
+- Expose `window.EXCALIDRAW_EXPORT_SOURCE` which you can use to overwrite the `source` field in exported data [#5095](https://github.com/excalidraw/excalidraw/pull/5095).
- The `exportToBlob` utility now supports the `exportEmbedScene` option when generating a png image [#5047](https://github.com/excalidraw/excalidraw/pull/5047).
- Exported [`restoreLibraryItems`](https://github.com/excalidraw/excalidraw/blob/master/src/packages/excalidraw/README.md#restoreLibraryItems) API [#4995](https://github.com/excalidraw/excalidraw/pull/4995).
#### Fixes
+- Use `window.EXCALIDRAW_ASSET_PATH` for fonts when exporting to svg [#5065](https://github.com/excalidraw/excalidraw/pull/5065).
- Library menu now properly rerenders if open when library is updated using `updateScene({ libraryItems })` [#4995](https://github.com/excalidraw/excalidraw/pull/4995).
#### Refactor
diff --git a/src/packages/excalidraw/README_NEXT.md b/src/packages/excalidraw/README_NEXT.md
index c20b29151..ca8262bd9 100644
--- a/src/packages/excalidraw/README_NEXT.md
+++ b/src/packages/excalidraw/README_NEXT.md
@@ -436,7 +436,7 @@ This helps to load Excalidraw with `initialData`. It must be an object or a [pro
| `elements` | [ExcalidrawElement[]](https://github.com/excalidraw/excalidraw/blob/master/src/element/types.ts#L78) | The elements with which Excalidraw should be mounted. |
| `appState` | [AppState](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L42) | The App state with which Excalidraw should be mounted. |
| `scrollToContent` | boolean | This attribute implies whether to scroll to the nearest element to center once Excalidraw is mounted. By default, it will not scroll the nearest element to the center. Make sure you pass `initialData.appState.scrollX` and `initialData.appState.scrollY` when `scrollToContent` is false so that scroll positions are retained |
-| `libraryItems` | [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L151) | This library items with which Excalidraw should be mounted. |
+| `libraryItems` | [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200) | Promise<[LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200)> | This library items with which Excalidraw should be mounted. |
| `files` | [BinaryFiles](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L64) | The files added to the scene. |
```json
@@ -512,9 +512,9 @@ You can use this function to update the scene with the sceneData. It accepts the
| --- | --- | --- |
| `elements` | [`ImportedDataState["elements"]`](https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L17) | The `elements` to be updated in the scene |
| `appState` | [`ImportedDataState["appState"]`](https://github.com/excalidraw/excalidraw/blob/master/src/data/types.ts#L18) | The `appState` to be updated in the scene. |
-| `collaborators` |
MapCollaborator>
| The list of collaborators to be updated in the scene. |
+| `collaborators` |
MapCollaborator>
| The list of collaborators to be updated in the scene. |
| `commitToHistory` | `boolean` | Implies if the `history (undo/redo)` should be recorded. Defaults to `false`. |
-| `libraryItems` | [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L258) | The `libraryItems` to be update in the scene. |
+| `libraryItems` | [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200) | Promise<[LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200)> | ((currentItems: [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200)>) => [LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200) | Promise<[LibraryItems](https://github.com/excalidraw/excalidraw/blob/master/src/types.ts#L200)>) | The `libraryItems` to be update in the scene. |
### `addFiles`
@@ -857,7 +857,7 @@ This function returns the canvas with the exported elements, appState and dimens
exportToBlob(
- opts: ExportOpts & {
+ opts: ExportOpts & {
mimeType?: string,
quality?: number;
})
@@ -900,6 +900,34 @@ exportToSvg({
This function returns a promise which resolves to svg of the exported drawing.
+#### `exportToClipboard`
+
+**_Signature_**
+
+
+
+| Name | Type | Default | Description |
+| --- | --- | --- | --- | --- | --- |
+| 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' | 'svg' | 'json' | | This determines the format to which the scene data should be exported. |
+
+**How to use**
+
+```js
+import { exportToClipboard } from "@excalidraw/excalidraw-next";
+```
+
+Copies the scene data in the specified format (determined by `type`) to clipboard.
+
##### Additional attributes of appState for `export\*` APIs
| Name | Type | Default | Description |
@@ -924,17 +952,21 @@ serializeAsJSON({
Takes the scene elements and state and returns a JSON string. Deleted `elements`as well as most properties from `AppState` are removed from the resulting JSON. (see [`serializeAsJSON()`](https://github.com/excalidraw/excalidraw/blob/master/src/data/json.ts#L16) source for details).
+If you want to overwrite the source field in the JSON string, you can set `window.EXCALIDRAW_EXPORT_SOURCE` to the desired value.
+
#### `serializeLibraryAsJSON`
**_Signature_**
Takes the library items and returns a JSON string.
+If you want to overwrite the source field in the JSON string, you can set `window.EXCALIDRAW_EXPORT_SOURCE` to the desired value.
+
#### `getSceneVersion`
**How to use**
@@ -1040,6 +1072,20 @@ getNonDeletedElements(elements:
+mergeLibraryItems(localItems: LibraryItems, otherItems: LibraryItems) => LibraryItems
+
+
+This function merges two `LibraryItems` arrays, where unique items from `otherItems` are sorted first in the returned array.
+
### Exported constants
#### `FONT_FAMILY`
@@ -1077,6 +1123,16 @@ import { THEME } from "@excalidraw/excalidraw-next";
Defaults to `THEME.LIGHT` unless passed in `initialData.appState.theme`
+### `MIME_TYPES`
+
+**How to use **
+
+```js
+import { MIME_TYPES } from "@excalidraw/excalidraw-next";
+```
+
+[`MIME_TYPES`](https://github.com/excalidraw/excalidraw/blob/master/src/constants.ts#L92) contains all the mime types supported by `Excalidraw`.
+
## Need help?
Check out the existing [Q&A](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw). If you have any queries or need help, ask us [here](https://github.com/excalidraw/excalidraw/discussions?discussions_q=label%3Apackage%3Aexcalidraw).
diff --git a/src/packages/excalidraw/entry.js b/src/packages/excalidraw/entry.js
index 8915a1255..02c14fdb1 100644
--- a/src/packages/excalidraw/entry.js
+++ b/src/packages/excalidraw/entry.js
@@ -1,6 +1,5 @@
-import Excalidraw from "./index";
+import "./publicPath";
import "../../../public/fonts.css";
-export { Excalidraw };
export * from "./index";
diff --git a/src/packages/excalidraw/env.js b/src/packages/excalidraw/env.js
index 7ca6283e2..6c5fd56e5 100644
--- a/src/packages/excalidraw/env.js
+++ b/src/packages/excalidraw/env.js
@@ -1,14 +1,18 @@
const dotenv = require("dotenv");
const { readFileSync } = require("fs");
-
+const pkg = require("./package.json");
const parseEnvVariables = (filepath) => {
- return Object.entries(dotenv.parse(readFileSync(filepath))).reduce(
+ const envVars = Object.entries(dotenv.parse(readFileSync(filepath))).reduce(
(env, [key, value]) => {
env[key] = JSON.stringify(value);
return env;
},
{},
);
+ envVars.PKG_NAME = JSON.stringify(pkg.name);
+ envVars.PKG_VERSION = JSON.stringify(pkg.version);
+ envVars.IS_EXCALIDRAW_NPM_PACKAGE = JSON.stringify(true);
+ return envVars;
};
module.exports = { parseEnvVariables };
diff --git a/src/packages/excalidraw/example/App.js b/src/packages/excalidraw/example/App.js
index 70915224b..307ff288a 100644
--- a/src/packages/excalidraw/example/App.js
+++ b/src/packages/excalidraw/example/App.js
@@ -5,15 +5,16 @@ import Sidebar from "./sidebar/Sidebar";
import "./App.scss";
import initialData from "./initialData";
-import { MIME_TYPES } from "../../../constants";
// This is so that we use the bundled excalidraw.development.js file instead
// of the actual source code
const {
- Excalidraw,
exportToCanvas,
exportToSvg,
exportToBlob,
+ exportToClipboard,
+ Excalidraw,
+ MIME_TYPES,
sceneCoordsToViewportCoords,
} = window.ExcalidrawLib;
@@ -49,7 +50,10 @@ const resolvablePromise = () => {
const renderTopRightUI = () => {
return (
-