Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1ac4200cc0 | |||
| 2ca2c0f9fa | |||
| f3b6e9b09f | |||
| 1db2869906 | |||
| 1bb88cb5e9 | |||
| 701e076cc1 | |||
| ad39506585 | |||
| b2331ffd98 |
+1
-2
@@ -25,5 +25,4 @@ packages/excalidraw/types
|
||||
coverage
|
||||
dev-dist
|
||||
html
|
||||
examples/**/bundle.*
|
||||
meta*.json
|
||||
examples/**/bundle.*
|
||||
@@ -58,7 +58,7 @@ If you are using `pages router` then importing the wrapper dynamically would wor
|
||||
|
||||
```jsx showLineNumbers
|
||||
"use client";
|
||||
import { Excalidraw, convertToExcalidrawElements } from "@excalidraw/excalidraw";
|
||||
import { Excalidraw. convertToExcalidrawElements } from "@excalidraw/excalidraw";
|
||||
|
||||
import "@excalidraw/excalidraw/index.css";
|
||||
|
||||
@@ -70,7 +70,7 @@ If you are using `pages router` then importing the wrapper dynamically would wor
|
||||
height: 141.9765625,
|
||||
},]));
|
||||
return (
|
||||
<div style={{height:"500px", width:"500px"}}>
|
||||
<div style={{height:"500px", width:"500px"}}
|
||||
<Excalidraw />
|
||||
</div>
|
||||
);
|
||||
|
||||
+3
-3
@@ -7614,9 +7614,9 @@ webpack-bundle-analyzer@^4.5.0:
|
||||
ws "^7.3.1"
|
||||
|
||||
webpack-dev-middleware@^5.3.1:
|
||||
version "5.3.4"
|
||||
resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-5.3.4.tgz#eb7b39281cbce10e104eb2b8bf2b63fce49a3517"
|
||||
integrity sha512-BVdTqhhs+0IfoeAf7EoH5WE+exCmqGerHfDM0IL096Px60Tq2Mn9MAbnaGUe6HiMa41KMCYF19gyzZmBcq/o4Q==
|
||||
version "5.3.3"
|
||||
resolved "https://registry.yarnpkg.com/webpack-dev-middleware/-/webpack-dev-middleware-5.3.3.tgz#efae67c2793908e7311f1d9b06f2a08dcc97e51f"
|
||||
integrity sha512-hj5CYrY0bZLB+eTO+x/j67Pkrquiy7kWepMHmUMoPsmcUaeEnQJqFzHJOyxgWlq746/wUuA64p9ta34Kyb01pA==
|
||||
dependencies:
|
||||
colorette "^2.0.10"
|
||||
memfs "^3.4.3"
|
||||
|
||||
+45
-51
@@ -30,6 +30,7 @@ import {
|
||||
} from "../packages/excalidraw/index";
|
||||
import {
|
||||
AppState,
|
||||
LibraryItems,
|
||||
ExcalidrawImperativeAPI,
|
||||
BinaryFiles,
|
||||
ExcalidrawInitialDataState,
|
||||
@@ -63,6 +64,7 @@ import {
|
||||
loadScene,
|
||||
} from "./data";
|
||||
import {
|
||||
getLibraryItemsFromStorage,
|
||||
importFromLocalStorage,
|
||||
importUsernameFromLocalStorage,
|
||||
} from "./data/localStorage";
|
||||
@@ -80,11 +82,7 @@ import { updateStaleImageStatuses } from "./data/FileManager";
|
||||
import { newElementWith } from "../packages/excalidraw/element/mutateElement";
|
||||
import { isInitializedImageElement } from "../packages/excalidraw/element/typeChecks";
|
||||
import { loadFilesFromFirebase } from "./data/firebase";
|
||||
import {
|
||||
LibraryIndexedDBAdapter,
|
||||
LibraryLocalStorageMigrationAdapter,
|
||||
LocalData,
|
||||
} from "./data/LocalData";
|
||||
import { LocalData } from "./data/LocalData";
|
||||
import { isBrowserStorageStateNewer } from "./data/tabSync";
|
||||
import clsx from "clsx";
|
||||
import { reconcileElements } from "./collab/reconciliation";
|
||||
@@ -106,7 +104,7 @@ import { openConfirmModal } from "../packages/excalidraw/components/OverwriteCon
|
||||
import { OverwriteConfirmDialog } from "../packages/excalidraw/components/OverwriteConfirm/OverwriteConfirm";
|
||||
import Trans from "../packages/excalidraw/components/Trans";
|
||||
import { ShareDialog, shareDialogStateAtom } from "./share/ShareDialog";
|
||||
import CollabError, { collabErrorIndicatorAtom } from "./collab/CollabError";
|
||||
import { getFileName } from "../packages/excalidraw/data/filename";
|
||||
|
||||
polyfill();
|
||||
|
||||
@@ -313,13 +311,10 @@ const ExcalidrawWrapper = () => {
|
||||
const [isCollaborating] = useAtomWithInitialValue(isCollaboratingAtom, () => {
|
||||
return isCollaborationLink(window.location.href);
|
||||
});
|
||||
const collabError = useAtomValue(collabErrorIndicatorAtom);
|
||||
|
||||
useHandleLibrary({
|
||||
excalidrawAPI,
|
||||
adapter: LibraryIndexedDBAdapter,
|
||||
// TODO maybe remove this in several months (shipped: 24-03-11)
|
||||
migrationAdapter: LibraryLocalStorageMigrationAdapter,
|
||||
getInitialLibraryItems: getLibraryItemsFromStorage,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@@ -449,12 +444,8 @@ const ExcalidrawWrapper = () => {
|
||||
excalidrawAPI.updateScene({
|
||||
...localDataState,
|
||||
});
|
||||
LibraryIndexedDBAdapter.load().then((data) => {
|
||||
if (data) {
|
||||
excalidrawAPI.updateLibrary({
|
||||
libraryItems: data.libraryItems,
|
||||
});
|
||||
}
|
||||
excalidrawAPI.updateLibrary({
|
||||
libraryItems: getLibraryItemsFromStorage(),
|
||||
});
|
||||
collabAPI?.setUsername(username || "");
|
||||
}
|
||||
@@ -666,6 +657,15 @@ const ExcalidrawWrapper = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const onLibraryChange = async (items: LibraryItems) => {
|
||||
if (!items.length) {
|
||||
localStorage.removeItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY);
|
||||
return;
|
||||
}
|
||||
const serializedItems = JSON.stringify(items);
|
||||
localStorage.setItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY, serializedItems);
|
||||
};
|
||||
|
||||
const isOffline = useAtomValue(isOfflineAtom);
|
||||
|
||||
const onCollabDialogOpen = useCallback(
|
||||
@@ -691,7 +691,6 @@ const ExcalidrawWrapper = () => {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{ height: "100%" }}
|
||||
@@ -710,30 +709,27 @@ const ExcalidrawWrapper = () => {
|
||||
toggleTheme: true,
|
||||
export: {
|
||||
onExportToBackend,
|
||||
renderCustomUI: excalidrawAPI
|
||||
? (elements, appState, files) => {
|
||||
return (
|
||||
<ExportToExcalidrawPlus
|
||||
elements={elements}
|
||||
appState={appState}
|
||||
files={files}
|
||||
name={excalidrawAPI.getName()}
|
||||
onError={(error) => {
|
||||
excalidrawAPI?.updateScene({
|
||||
appState: {
|
||||
errorMessage: error.message,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onSuccess={() => {
|
||||
excalidrawAPI.updateScene({
|
||||
appState: { openDialog: null },
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
: undefined,
|
||||
renderCustomUI: (elements, appState, files) => {
|
||||
return (
|
||||
<ExportToExcalidrawPlus
|
||||
elements={elements}
|
||||
appState={appState}
|
||||
files={files}
|
||||
onError={(error) => {
|
||||
excalidrawAPI?.updateScene({
|
||||
appState: {
|
||||
errorMessage: error.message,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onSuccess={() => {
|
||||
excalidrawAPI?.updateScene({
|
||||
appState: { openDialog: null },
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
@@ -741,6 +737,7 @@ const ExcalidrawWrapper = () => {
|
||||
renderCustomStats={renderCustomStats}
|
||||
detectScroll={false}
|
||||
handleKeyboardGlobally={true}
|
||||
onLibraryChange={onLibraryChange}
|
||||
autoFocus={true}
|
||||
theme={theme}
|
||||
renderTopRightUI={(isMobile) => {
|
||||
@@ -748,15 +745,12 @@ const ExcalidrawWrapper = () => {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div className="top-right-ui">
|
||||
{collabError.message && <CollabError collabError={collabError} />}
|
||||
<LiveCollaborationTrigger
|
||||
isCollaborating={isCollaborating}
|
||||
onSelect={() =>
|
||||
setShareDialogState({ isOpen: true, type: "share" })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<LiveCollaborationTrigger
|
||||
isCollaborating={isCollaborating}
|
||||
onSelect={() =>
|
||||
setShareDialogState({ isOpen: true, type: "share" })
|
||||
}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -781,7 +775,7 @@ const ExcalidrawWrapper = () => {
|
||||
excalidrawAPI.getSceneElements(),
|
||||
excalidrawAPI.getAppState(),
|
||||
excalidrawAPI.getFiles(),
|
||||
excalidrawAPI.getName(),
|
||||
getFileName(),
|
||||
);
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -39,14 +39,10 @@ export const STORAGE_KEYS = {
|
||||
LOCAL_STORAGE_ELEMENTS: "excalidraw",
|
||||
LOCAL_STORAGE_APP_STATE: "excalidraw-state",
|
||||
LOCAL_STORAGE_COLLAB: "excalidraw-collab",
|
||||
LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
||||
LOCAL_STORAGE_THEME: "excalidraw-theme",
|
||||
VERSION_DATA_STATE: "version-dataState",
|
||||
VERSION_FILES: "version-files",
|
||||
|
||||
IDB_LIBRARY: "excalidraw-library",
|
||||
|
||||
// do not use apart from migrations
|
||||
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
||||
} as const;
|
||||
|
||||
export const COOKIES = {
|
||||
|
||||
@@ -81,7 +81,6 @@ import { appJotaiStore } from "../app-jotai";
|
||||
import { Mutable, ValueOf } from "../../packages/excalidraw/utility-types";
|
||||
import { getVisibleSceneBounds } from "../../packages/excalidraw/element/bounds";
|
||||
import { withBatchedUpdates } from "../../packages/excalidraw/reactUtils";
|
||||
import { collabErrorIndicatorAtom } from "./CollabError";
|
||||
|
||||
export const collabAPIAtom = atom<CollabAPI | null>(null);
|
||||
export const isCollaboratingAtom = atom(false);
|
||||
@@ -89,8 +88,6 @@ export const isOfflineAtom = atom(false);
|
||||
|
||||
interface CollabState {
|
||||
errorMessage: string | null;
|
||||
/** errors related to saving */
|
||||
dialogNotifiedErrors: Record<string, boolean>;
|
||||
username: string;
|
||||
activeRoomLink: string | null;
|
||||
}
|
||||
@@ -110,7 +107,7 @@ export interface CollabAPI {
|
||||
setUsername: CollabInstance["setUsername"];
|
||||
getUsername: CollabInstance["getUsername"];
|
||||
getActiveRoomLink: CollabInstance["getActiveRoomLink"];
|
||||
setCollabError: CollabInstance["setErrorDialog"];
|
||||
setErrorMessage: CollabInstance["setErrorMessage"];
|
||||
}
|
||||
|
||||
interface CollabProps {
|
||||
@@ -132,7 +129,6 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
super(props);
|
||||
this.state = {
|
||||
errorMessage: null,
|
||||
dialogNotifiedErrors: {},
|
||||
username: importUsernameFromLocalStorage() || "",
|
||||
activeRoomLink: null,
|
||||
};
|
||||
@@ -201,7 +197,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
setUsername: this.setUsername,
|
||||
getUsername: this.getUsername,
|
||||
getActiveRoomLink: this.getActiveRoomLink,
|
||||
setCollabError: this.setErrorDialog,
|
||||
setErrorMessage: this.setErrorMessage,
|
||||
};
|
||||
|
||||
appJotaiStore.set(collabAPIAtom, collabAPI);
|
||||
@@ -280,35 +276,18 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
this.excalidrawAPI.getAppState(),
|
||||
);
|
||||
|
||||
this.resetErrorIndicator();
|
||||
|
||||
if (this.isCollaborating() && savedData && savedData.reconciledElements) {
|
||||
this.handleRemoteSceneUpdate(
|
||||
this.reconcileElements(savedData.reconciledElements),
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
const errorMessage = /is longer than.*?bytes/.test(error.message)
|
||||
? t("errors.collabSaveFailed_sizeExceeded")
|
||||
: t("errors.collabSaveFailed");
|
||||
|
||||
if (
|
||||
!this.state.dialogNotifiedErrors[errorMessage] ||
|
||||
!this.isCollaborating()
|
||||
) {
|
||||
this.setErrorDialog(errorMessage);
|
||||
this.setState({
|
||||
dialogNotifiedErrors: {
|
||||
...this.state.dialogNotifiedErrors,
|
||||
[errorMessage]: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (this.isCollaborating()) {
|
||||
this.setErrorIndicator(errorMessage);
|
||||
}
|
||||
|
||||
this.setState({
|
||||
// firestore doesn't return a specific error code when size exceeded
|
||||
errorMessage: /is longer than.*?bytes/.test(error.message)
|
||||
? t("errors.collabSaveFailed_sizeExceeded")
|
||||
: t("errors.collabSaveFailed"),
|
||||
});
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
@@ -317,7 +296,6 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
this.queueBroadcastAllElements.cancel();
|
||||
this.queueSaveToFirebase.cancel();
|
||||
this.loadImageFiles.cancel();
|
||||
this.resetErrorIndicator(true);
|
||||
|
||||
this.saveCollabRoomToFirebase(
|
||||
getSyncableElements(
|
||||
@@ -486,7 +464,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
this.portal.socket.once("connect_error", fallbackInitializationHandler);
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
this.setErrorDialog(error.message);
|
||||
this.setState({ errorMessage: error.message });
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -945,26 +923,8 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
|
||||
getActiveRoomLink = () => this.state.activeRoomLink;
|
||||
|
||||
setErrorIndicator = (errorMessage: string | null) => {
|
||||
appJotaiStore.set(collabErrorIndicatorAtom, {
|
||||
message: errorMessage,
|
||||
nonce: Date.now(),
|
||||
});
|
||||
};
|
||||
|
||||
resetErrorIndicator = (resetDialogNotifiedErrors = false) => {
|
||||
appJotaiStore.set(collabErrorIndicatorAtom, { message: null, nonce: 0 });
|
||||
if (resetDialogNotifiedErrors) {
|
||||
this.setState({
|
||||
dialogNotifiedErrors: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
setErrorDialog = (errorMessage: string | null) => {
|
||||
this.setState({
|
||||
errorMessage,
|
||||
});
|
||||
setErrorMessage = (errorMessage: string | null) => {
|
||||
this.setState({ errorMessage });
|
||||
};
|
||||
|
||||
render() {
|
||||
@@ -973,7 +933,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
||||
return (
|
||||
<>
|
||||
{errorMessage != null && (
|
||||
<ErrorDialog onClose={() => this.setErrorDialog(null)}>
|
||||
<ErrorDialog onClose={() => this.setState({ errorMessage: null })}>
|
||||
{errorMessage}
|
||||
</ErrorDialog>
|
||||
)}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
@import "../../packages/excalidraw/css/variables.module.scss";
|
||||
|
||||
.excalidraw {
|
||||
.collab-errors-button {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
margin-inline-end: 1rem;
|
||||
|
||||
color: var(--color-danger);
|
||||
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.collab-errors-button-shake {
|
||||
animation: strong-shake 0.15s 6;
|
||||
}
|
||||
|
||||
@keyframes strong-shake {
|
||||
0% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
25% {
|
||||
transform: rotate(10deg);
|
||||
}
|
||||
50% {
|
||||
transform: rotate(0eg);
|
||||
}
|
||||
75% {
|
||||
transform: rotate(-10deg);
|
||||
}
|
||||
100% {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { Tooltip } from "../../packages/excalidraw/components/Tooltip";
|
||||
import { warning } from "../../packages/excalidraw/components/icons";
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import "./CollabError.scss";
|
||||
import { atom } from "jotai";
|
||||
|
||||
type ErrorIndicator = {
|
||||
message: string | null;
|
||||
/** used to rerun the useEffect responsible for animation */
|
||||
nonce: number;
|
||||
};
|
||||
|
||||
export const collabErrorIndicatorAtom = atom<ErrorIndicator>({
|
||||
message: null,
|
||||
nonce: 0,
|
||||
});
|
||||
|
||||
const CollabError = ({ collabError }: { collabError: ErrorIndicator }) => {
|
||||
const [isAnimating, setIsAnimating] = useState(false);
|
||||
const clearAnimationRef = useRef<string | number | NodeJS.Timeout>();
|
||||
|
||||
useEffect(() => {
|
||||
setIsAnimating(true);
|
||||
clearAnimationRef.current = setTimeout(() => {
|
||||
setIsAnimating(false);
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
clearTimeout(clearAnimationRef.current);
|
||||
};
|
||||
}, [collabError.message, collabError.nonce]);
|
||||
|
||||
if (!collabError.message) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip label={collabError.message} long={true}>
|
||||
<div
|
||||
className={clsx("collab-errors-button", {
|
||||
"collab-errors-button-shake": isAnimating,
|
||||
})}
|
||||
>
|
||||
{warning}
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
CollabError.displayName = "CollabError";
|
||||
|
||||
export default CollabError;
|
||||
@@ -65,18 +65,19 @@ export const RoomModal = ({
|
||||
const copyRoomLink = async () => {
|
||||
try {
|
||||
await copyTextToSystemClipboard(activeRoomLink);
|
||||
} catch (e) {
|
||||
setErrorMessage(t("errors.copyToSystemClipboardFailed"));
|
||||
}
|
||||
setJustCopied(true);
|
||||
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
setJustCopied(true);
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
} catch (error: any) {
|
||||
setErrorMessage(error.message);
|
||||
}
|
||||
|
||||
ref.current?.select();
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ import { MIME_TYPES } from "../../packages/excalidraw/constants";
|
||||
import { trackEvent } from "../../packages/excalidraw/analytics";
|
||||
import { getFrame } from "../../packages/excalidraw/utils";
|
||||
import { ExcalidrawLogo } from "../../packages/excalidraw/components/ExcalidrawLogo";
|
||||
import { getFileName } from "../../packages/excalidraw/data/filename";
|
||||
|
||||
export const exportToExcalidrawPlus = async (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
@@ -90,10 +91,9 @@ export const ExportToExcalidrawPlus: React.FC<{
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
appState: Partial<AppState>;
|
||||
files: BinaryFiles;
|
||||
name: string;
|
||||
onError: (error: Error) => void;
|
||||
onSuccess: () => void;
|
||||
}> = ({ elements, appState, files, name, onError, onSuccess }) => {
|
||||
}> = ({ elements, appState, files, onError, onSuccess }) => {
|
||||
const { t } = useI18n();
|
||||
return (
|
||||
<Card color="primary">
|
||||
@@ -119,7 +119,12 @@ export const ExportToExcalidrawPlus: React.FC<{
|
||||
onClick={async () => {
|
||||
try {
|
||||
trackEvent("export", "eplus", `ui (${getFrame()})`);
|
||||
await exportToExcalidrawPlus(elements, appState, files, name);
|
||||
await exportToExcalidrawPlus(
|
||||
elements,
|
||||
appState,
|
||||
files,
|
||||
getFileName(),
|
||||
);
|
||||
onSuccess();
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
|
||||
@@ -10,18 +10,8 @@
|
||||
* (localStorage, indexedDB).
|
||||
*/
|
||||
|
||||
import {
|
||||
createStore,
|
||||
entries,
|
||||
del,
|
||||
getMany,
|
||||
set,
|
||||
setMany,
|
||||
get,
|
||||
} from "idb-keyval";
|
||||
import { createStore, entries, del, getMany, set, setMany } from "idb-keyval";
|
||||
import { clearAppStateForLocalStorage } from "../../packages/excalidraw/appState";
|
||||
import { LibraryPersistedData } from "../../packages/excalidraw/data/library";
|
||||
import { ImportedDataState } from "../../packages/excalidraw/data/types";
|
||||
import { clearElementsForLocalStorage } from "../../packages/excalidraw/element";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
@@ -32,7 +22,6 @@ import {
|
||||
BinaryFileData,
|
||||
BinaryFiles,
|
||||
} from "../../packages/excalidraw/types";
|
||||
import { MaybePromise } from "../../packages/excalidraw/utility-types";
|
||||
import { debounce } from "../../packages/excalidraw/utils";
|
||||
import { SAVE_TO_LOCAL_STORAGE_TIMEOUT, STORAGE_KEYS } from "../app_constants";
|
||||
import { FileManager } from "./FileManager";
|
||||
@@ -194,52 +183,3 @@ export class LocalData {
|
||||
},
|
||||
});
|
||||
}
|
||||
export class LibraryIndexedDBAdapter {
|
||||
/** IndexedDB database and store name */
|
||||
private static idb_name = STORAGE_KEYS.IDB_LIBRARY;
|
||||
/** library data store key */
|
||||
private static key = "libraryData";
|
||||
|
||||
private static store = createStore(
|
||||
`${LibraryIndexedDBAdapter.idb_name}-db`,
|
||||
`${LibraryIndexedDBAdapter.idb_name}-store`,
|
||||
);
|
||||
|
||||
static async load() {
|
||||
const IDBData = await get<LibraryPersistedData>(
|
||||
LibraryIndexedDBAdapter.key,
|
||||
LibraryIndexedDBAdapter.store,
|
||||
);
|
||||
|
||||
return IDBData || null;
|
||||
}
|
||||
|
||||
static save(data: LibraryPersistedData): MaybePromise<void> {
|
||||
return set(
|
||||
LibraryIndexedDBAdapter.key,
|
||||
data,
|
||||
LibraryIndexedDBAdapter.store,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** LS Adapter used only for migrating LS library data
|
||||
* to indexedDB */
|
||||
export class LibraryLocalStorageMigrationAdapter {
|
||||
static load() {
|
||||
const LSData = localStorage.getItem(
|
||||
STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY,
|
||||
);
|
||||
if (LSData != null) {
|
||||
const libraryItems: ImportedDataState["libraryItems"] =
|
||||
JSON.parse(LSData);
|
||||
if (libraryItems) {
|
||||
return { libraryItems };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
static clear() {
|
||||
localStorage.removeItem(STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "../../packages/excalidraw/appState";
|
||||
import { clearElementsForLocalStorage } from "../../packages/excalidraw/element";
|
||||
import { STORAGE_KEYS } from "../app_constants";
|
||||
import { ImportedDataState } from "../../packages/excalidraw/data/types";
|
||||
|
||||
export const saveUsernameToLocalStorage = (username: string) => {
|
||||
try {
|
||||
@@ -87,13 +88,28 @@ export const getTotalStorageSize = () => {
|
||||
try {
|
||||
const appState = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_APP_STATE);
|
||||
const collab = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_COLLAB);
|
||||
const library = localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY);
|
||||
|
||||
const appStateSize = appState?.length || 0;
|
||||
const collabSize = collab?.length || 0;
|
||||
const librarySize = library?.length || 0;
|
||||
|
||||
return appStateSize + collabSize + getElementsStorageSize();
|
||||
return appStateSize + collabSize + librarySize + getElementsStorageSize();
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
export const getLibraryItemsFromStorage = () => {
|
||||
try {
|
||||
const libraryItems: ImportedDataState["libraryItems"] = JSON.parse(
|
||||
localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_LIBRARY) as string,
|
||||
);
|
||||
|
||||
return libraryItems || [];
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,13 +4,6 @@
|
||||
&.theme--dark {
|
||||
--color-primary-contrast-offset: #726dff; // to offset Chubb illusion
|
||||
}
|
||||
|
||||
.top-right-ui {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.footer-center {
|
||||
justify-content: flex-end;
|
||||
margin-top: auto;
|
||||
|
||||
@@ -69,20 +69,20 @@ const ActiveRoomDialog = ({
|
||||
const copyRoomLink = async () => {
|
||||
try {
|
||||
await copyTextToSystemClipboard(activeRoomLink);
|
||||
} catch (e) {
|
||||
collabAPI.setCollabError(t("errors.copyToSystemClipboardFailed"));
|
||||
|
||||
setJustCopied(true);
|
||||
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
} catch (error: any) {
|
||||
collabAPI.setErrorMessage(error.message);
|
||||
}
|
||||
|
||||
setJustCopied(true);
|
||||
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
|
||||
ref.current?.select();
|
||||
};
|
||||
|
||||
|
||||
@@ -15,24 +15,14 @@ Please add the latest change on the top under the correct section.
|
||||
|
||||
### Features
|
||||
|
||||
- Add `useHandleLibrary`'s `opts.adapter` as the new recommended pattern to handle library initialization and persistence on library updates. [#7655](https://github.com/excalidraw/excalidraw/pull/7655)
|
||||
- Add `useHandleLibrary`'s `opts.migrationAdapter` adapter to handle library migration during init, when migrating from one data store to another (e.g. from LocalStorage to IndexedDB). [#7655](https://github.com/excalidraw/excalidraw/pull/7655)
|
||||
- Soft-deprecate `useHandleLibrary`'s `opts.getInitialLibraryItems` in favor of `opts.adapter`. [#7655](https://github.com/excalidraw/excalidraw/pull/7655)
|
||||
|
||||
- Add `onPointerUp` prop [#7638](https://github.com/excalidraw/excalidraw/pull/7638).
|
||||
|
||||
- Expose `getVisibleSceneBounds` helper to get scene bounds of visible canvas area. [#7450](https://github.com/excalidraw/excalidraw/pull/7450)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Keep customData when converting to ExcalidrawElement. [#7656](https://github.com/excalidraw/excalidraw/pull/7656)
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- `ExcalidrawEmbeddableElement.validated` was removed and moved to private editor state. This should largely not affect your apps unless you were reading from this attribute. We keep validating embeddable urls internally, and the public [`props.validateEmbeddable`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props#validateembeddable) still applies. [#7539](https://github.com/excalidraw/excalidraw/pull/7539)
|
||||
|
||||
- `ExcalidrawTextElement.baseline` was removed and replaced with a vertical offset computation based on font metrics, performed on each text element re-render. In case of custom font usage, extend the `FONT_METRICS` object with the related properties.
|
||||
|
||||
- Create an `ESM` build for `@excalidraw/excalidraw`. The API is in progress and subject to change before stable release. There are some changes on how the package will be consumed
|
||||
|
||||
#### Bundler
|
||||
@@ -67,12 +57,10 @@ Please add the latest change on the top under the correct section.
|
||||
|
||||
- `appState.openDialog` type was changed from `null | string` to `null | { name: string }`. [#7336](https://github.com/excalidraw/excalidraw/pull/7336)
|
||||
|
||||
## 0.17.3 (2024-02-09)
|
||||
## 0.17.1 (2023-11-28)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Keep customData when converting to ExcalidrawElement. [#7656](https://github.com/excalidraw/excalidraw/pull/7656)
|
||||
|
||||
- Umd build for browser since it was breaking in v0.17.0 [#7349](https://github.com/excalidraw/excalidraw/pull/7349). Also make sure that when using `Vite`, the `process.env.IS_PREACT` is set as `"true"` (string) and not a boolean.
|
||||
|
||||
```
|
||||
@@ -81,10 +69,6 @@ define: {
|
||||
}
|
||||
```
|
||||
|
||||
- Disable caching bounds for arrow labels [#7343](https://github.com/excalidraw/excalidraw/pull/7343)
|
||||
|
||||
- Bounds cached prematurely resulting in incorrectly rendered labels [#7339](https://github.com/excalidraw/excalidraw/pull/7339)
|
||||
|
||||
## Excalidraw Library
|
||||
|
||||
### Fixes
|
||||
|
||||
@@ -49,7 +49,7 @@ export const actionUnbindText = register({
|
||||
selectedElements.forEach((element) => {
|
||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
||||
if (boundTextElement) {
|
||||
const { width, height } = measureText(
|
||||
const { width, height, baseline } = measureText(
|
||||
boundTextElement.originalText,
|
||||
getFontString(boundTextElement),
|
||||
boundTextElement.lineHeight,
|
||||
@@ -58,15 +58,12 @@ export const actionUnbindText = register({
|
||||
element.id,
|
||||
);
|
||||
resetOriginalContainerCache(element.id);
|
||||
const { x, y } = computeBoundTextPosition(
|
||||
element,
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
const { x, y } = computeBoundTextPosition(element, boundTextElement);
|
||||
mutateElement(boundTextElement as ExcalidrawTextElement, {
|
||||
containerId: null,
|
||||
width,
|
||||
height,
|
||||
baseline,
|
||||
text: boundTextElement.originalText,
|
||||
x,
|
||||
y,
|
||||
@@ -148,11 +145,7 @@ export const actionBindText = register({
|
||||
}),
|
||||
});
|
||||
const originalContainerHeight = container.height;
|
||||
redrawTextBoundingBox(
|
||||
textElement,
|
||||
container,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
redrawTextBoundingBox(textElement, container);
|
||||
// overwritting the cache with original container height so
|
||||
// it can be restored when unbind
|
||||
updateOriginalContainerCache(container.id, originalContainerHeight);
|
||||
@@ -293,11 +286,7 @@ export const actionWrapTextInContainer = register({
|
||||
},
|
||||
false,
|
||||
);
|
||||
redrawTextBoundingBox(
|
||||
textElement,
|
||||
container,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
redrawTextBoundingBox(textElement, container);
|
||||
|
||||
updatedElements = pushContainerBelowText(
|
||||
[...updatedElements, container],
|
||||
|
||||
@@ -13,6 +13,7 @@ import { exportCanvas, prepareElementsForExport } from "../data/index";
|
||||
import { isTextElement } from "../element";
|
||||
import { t } from "../i18n";
|
||||
import { isFirefox } from "../constants";
|
||||
import { getFileName } from "../data/filename";
|
||||
|
||||
export const actionCopy = register({
|
||||
name: "copy",
|
||||
@@ -107,7 +108,7 @@ export const actionCut = register({
|
||||
trackEvent: { category: "element" },
|
||||
perform: (elements, appState, event: ClipboardEvent | null, app) => {
|
||||
actionCopy.perform(elements, appState, event, app);
|
||||
return actionDeleteSelected.perform(elements, appState, null, app);
|
||||
return actionDeleteSelected.perform(elements, appState);
|
||||
},
|
||||
contextItemLabel: "labels.cut",
|
||||
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.X,
|
||||
@@ -138,7 +139,7 @@ export const actionCopyAsSvg = register({
|
||||
{
|
||||
...appState,
|
||||
exportingFrame,
|
||||
name: app.getName(),
|
||||
name: app.props.name || getFileName(),
|
||||
},
|
||||
);
|
||||
return {
|
||||
@@ -185,7 +186,7 @@ export const actionCopyAsPng = register({
|
||||
await exportCanvas("clipboard", exportedElements, appState, app.files, {
|
||||
...appState,
|
||||
exportingFrame,
|
||||
name: app.getName(),
|
||||
name: app.props.name || getFileName(),
|
||||
});
|
||||
return {
|
||||
appState: {
|
||||
@@ -238,11 +239,7 @@ export const copyText = register({
|
||||
return acc;
|
||||
}, [])
|
||||
.join("\n\n");
|
||||
try {
|
||||
copyTextToSystemClipboard(text);
|
||||
} catch (e) {
|
||||
throw new Error(t("errors.copyToSystemClipboardFailed"));
|
||||
}
|
||||
copyTextToSystemClipboard(text);
|
||||
return {
|
||||
commitToHistory: false,
|
||||
};
|
||||
|
||||
@@ -73,7 +73,7 @@ const handleGroupEditingState = (
|
||||
export const actionDeleteSelected = register({
|
||||
name: "deleteSelectedElements",
|
||||
trackEvent: { category: "element", action: "delete" },
|
||||
perform: (elements, appState, formData, app) => {
|
||||
perform: (elements, appState) => {
|
||||
if (appState.editingLinearElement) {
|
||||
const {
|
||||
elementId,
|
||||
@@ -81,8 +81,7 @@ export const actionDeleteSelected = register({
|
||||
startBindingElement,
|
||||
endBindingElement,
|
||||
} = appState.editingLinearElement;
|
||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -35,14 +35,10 @@ import {
|
||||
export const actionDuplicateSelection = register({
|
||||
name: "duplicateSelection",
|
||||
trackEvent: { category: "element" },
|
||||
perform: (elements, appState, formData, app) => {
|
||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||
perform: (elements, appState) => {
|
||||
// duplicate selected point(s) if editing a line
|
||||
if (appState.editingLinearElement) {
|
||||
const ret = LinearElementEditor.duplicateSelectedPoints(
|
||||
appState,
|
||||
elementsMap,
|
||||
);
|
||||
const ret = LinearElementEditor.duplicateSelectedPoints(appState);
|
||||
|
||||
if (!ret) {
|
||||
return false;
|
||||
|
||||
@@ -17,6 +17,7 @@ import { getNonDeletedElements } from "../element";
|
||||
import { isImageFileHandle } from "../data/blob";
|
||||
import { nativeFileSystemSupported } from "../data/filesystem";
|
||||
import { Theme } from "../element/types";
|
||||
import { getFileName } from "../data/filename";
|
||||
|
||||
import "../components/ToolIcon.scss";
|
||||
|
||||
@@ -26,11 +27,14 @@ export const actionChangeProjectName = register({
|
||||
perform: (_elements, appState, value) => {
|
||||
return { appState: { ...appState, name: value }, commitToHistory: false };
|
||||
},
|
||||
PanelComponent: ({ appState, updateData, appProps, data, app }) => (
|
||||
PanelComponent: ({ appState, updateData, appProps, data }) => (
|
||||
<ProjectName
|
||||
label={t("labels.fileTitle")}
|
||||
value={app.getName()}
|
||||
value={appProps.name}
|
||||
onChange={(name: string) => updateData(name)}
|
||||
isNameEditable={
|
||||
typeof appProps.name === "undefined" && !appState.viewModeEnabled
|
||||
}
|
||||
ignoreFocus={data?.ignoreFocus ?? false}
|
||||
/>
|
||||
),
|
||||
@@ -145,9 +149,14 @@ export const actionSaveToActiveFile = register({
|
||||
elements,
|
||||
appState,
|
||||
app.files,
|
||||
app.getName(),
|
||||
app.props.name || getFileName(),
|
||||
)
|
||||
: await saveAsJSON(elements, appState, app.files, app.getName());
|
||||
: await saveAsJSON(
|
||||
elements,
|
||||
appState,
|
||||
app.files,
|
||||
app.props.name || getFileName(),
|
||||
);
|
||||
|
||||
return {
|
||||
commitToHistory: false,
|
||||
@@ -192,7 +201,7 @@ export const actionSaveFileToDisk = register({
|
||||
fileHandle: null,
|
||||
},
|
||||
app.files,
|
||||
app.getName(),
|
||||
app.props.name || getFileName(),
|
||||
);
|
||||
return {
|
||||
commitToHistory: false,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { KEYS } from "../keys";
|
||||
import { isInvisiblySmallElement } from "../element";
|
||||
import { arrayToMap, updateActiveTool } from "../utils";
|
||||
import { updateActiveTool } from "../utils";
|
||||
import { ToolButton } from "../components/ToolButton";
|
||||
import { done } from "../components/icons";
|
||||
import { t } from "../i18n";
|
||||
@@ -26,12 +26,10 @@ export const actionFinalize = register({
|
||||
_,
|
||||
{ interactiveCanvas, focusContainer, scene },
|
||||
) => {
|
||||
const elementsMap = scene.getNonDeletedElementsMap();
|
||||
|
||||
if (appState.editingLinearElement) {
|
||||
const { elementId, startBindingElement, endBindingElement } =
|
||||
appState.editingLinearElement;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
|
||||
if (element) {
|
||||
if (isBindingElement(element)) {
|
||||
@@ -39,7 +37,6 @@ export const actionFinalize = register({
|
||||
element,
|
||||
startBindingElement,
|
||||
endBindingElement,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
return {
|
||||
@@ -128,14 +125,12 @@ export const actionFinalize = register({
|
||||
const [x, y] = LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
multiPointElement,
|
||||
-1,
|
||||
arrayToMap(elements),
|
||||
);
|
||||
maybeBindLinearElement(
|
||||
multiPointElement,
|
||||
appState,
|
||||
Scene.getScene(multiPointElement)!,
|
||||
{ x, y },
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -191,7 +186,7 @@ export const actionFinalize = register({
|
||||
// To select the linear element when user has finished mutipoint editing
|
||||
selectedLinearElement:
|
||||
multiPointElement && isLinearElement(multiPointElement)
|
||||
? new LinearElementEditor(multiPointElement)
|
||||
? new LinearElementEditor(multiPointElement, scene)
|
||||
: appState.selectedLinearElement,
|
||||
pendingImageElementId: null,
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getNonDeletedElements } from "../element";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
NonDeleted,
|
||||
NonDeletedElementsMap,
|
||||
NonDeletedSceneElementsMap,
|
||||
} from "../element/types";
|
||||
import { resizeMultipleElements } from "../element/resizeElements";
|
||||
@@ -67,7 +68,7 @@ export const actionFlipVertical = register({
|
||||
|
||||
const flipSelectedElements = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elementsMap: NonDeletedElementsMap | NonDeletedSceneElementsMap,
|
||||
appState: Readonly<AppState>,
|
||||
flipDirection: "horizontal" | "vertical",
|
||||
) => {
|
||||
@@ -82,7 +83,6 @@ const flipSelectedElements = (
|
||||
|
||||
const updatedElements = flipElements(
|
||||
selectedElements,
|
||||
elements,
|
||||
elementsMap,
|
||||
appState,
|
||||
flipDirection,
|
||||
@@ -97,8 +97,7 @@ const flipSelectedElements = (
|
||||
|
||||
const flipElements = (
|
||||
selectedElements: NonDeleted<ExcalidrawElement>[],
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elementsMap: NonDeletedElementsMap | NonDeletedSceneElementsMap,
|
||||
appState: AppState,
|
||||
flipDirection: "horizontal" | "vertical",
|
||||
): ExcalidrawElement[] => {
|
||||
@@ -114,9 +113,9 @@ const flipElements = (
|
||||
flipDirection === "horizontal" ? minY : maxY,
|
||||
);
|
||||
|
||||
isBindingEnabled(appState)
|
||||
? bindOrUnbindSelectedElements(selectedElements, elements, elementsMap)
|
||||
: unbindLinearElements(selectedElements, elementsMap);
|
||||
(isBindingEnabled(appState)
|
||||
? bindOrUnbindSelectedElements
|
||||
: unbindLinearElements)(selectedElements);
|
||||
|
||||
return selectedElements;
|
||||
};
|
||||
|
||||
@@ -180,8 +180,6 @@ export const actionUngroup = register({
|
||||
trackEvent: { category: "element" },
|
||||
perform: (elements, appState, _, app) => {
|
||||
const groupIds = getSelectedGroupIds(appState);
|
||||
const elementsMap = arrayToMap(elements);
|
||||
|
||||
if (groupIds.length === 0) {
|
||||
return { appState, elements, commitToHistory: false };
|
||||
}
|
||||
@@ -228,12 +226,7 @@ export const actionUngroup = register({
|
||||
if (frame) {
|
||||
nextElements = replaceAllElementsInFrame(
|
||||
nextElements,
|
||||
getElementsInResizingFrame(
|
||||
nextElements,
|
||||
frame,
|
||||
appState,
|
||||
elementsMap,
|
||||
),
|
||||
getElementsInResizingFrame(nextElements, frame, appState),
|
||||
frame,
|
||||
app,
|
||||
);
|
||||
|
||||
@@ -24,7 +24,7 @@ export const actionToggleLinearEditor = register({
|
||||
const editingLinearElement =
|
||||
appState.editingLinearElement?.elementId === selectedElement.id
|
||||
? null
|
||||
: new LinearElementEditor(selectedElement);
|
||||
: new LinearElementEditor(selectedElement, app.scene);
|
||||
return {
|
||||
appState: {
|
||||
...appState,
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { getContextMenuLabel } from "../components/hyperlink/Hyperlink";
|
||||
import { LinkIcon } from "../components/icons";
|
||||
import { ToolButton } from "../components/ToolButton";
|
||||
import { isEmbeddableElement } from "../element/typeChecks";
|
||||
import { t } from "../i18n";
|
||||
import { KEYS } from "../keys";
|
||||
import { getSelectedElements } from "../scene";
|
||||
import { getShortcutKey } from "../utils";
|
||||
import { register } from "./register";
|
||||
|
||||
export const actionLink = register({
|
||||
name: "hyperlink",
|
||||
perform: (elements, appState) => {
|
||||
if (appState.showHyperlinkPopup === "editor") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
elements,
|
||||
appState: {
|
||||
...appState,
|
||||
showHyperlinkPopup: "editor",
|
||||
openMenu: null,
|
||||
},
|
||||
commitToHistory: true,
|
||||
};
|
||||
},
|
||||
trackEvent: { category: "hyperlink", action: "click" },
|
||||
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.K,
|
||||
contextItemLabel: (elements, appState) =>
|
||||
getContextMenuLabel(elements, appState),
|
||||
predicate: (elements, appState) => {
|
||||
const selectedElements = getSelectedElements(elements, appState);
|
||||
return selectedElements.length === 1;
|
||||
},
|
||||
PanelComponent: ({ elements, appState, updateData }) => {
|
||||
const selectedElements = getSelectedElements(elements, appState);
|
||||
|
||||
return (
|
||||
<ToolButton
|
||||
type="button"
|
||||
icon={LinkIcon}
|
||||
aria-label={t(getContextMenuLabel(elements, appState))}
|
||||
title={`${
|
||||
isEmbeddableElement(elements[0])
|
||||
? t("labels.link.labelEmbed")
|
||||
: t("labels.link.label")
|
||||
} - ${getShortcutKey("CtrlOrCmd+K")}`}
|
||||
onClick={() => updateData(null)}
|
||||
selected={selectedElements.length === 1 && !!selectedElements[0].link}
|
||||
/>
|
||||
);
|
||||
},
|
||||
});
|
||||
@@ -1,15 +1,10 @@
|
||||
import { getClientColor } from "../clients";
|
||||
import { Avatar } from "../components/Avatar";
|
||||
import { GoToCollaboratorComponentProps } from "../components/UserList";
|
||||
import {
|
||||
eyeIcon,
|
||||
microphoneIcon,
|
||||
microphoneMutedIcon,
|
||||
} from "../components/icons";
|
||||
import { eyeIcon } from "../components/icons";
|
||||
import { t } from "../i18n";
|
||||
import { Collaborator } from "../types";
|
||||
import { register } from "./register";
|
||||
import clsx from "clsx";
|
||||
|
||||
export const actionGoToCollaborator = register({
|
||||
name: "goToCollaborator",
|
||||
@@ -44,45 +39,14 @@ export const actionGoToCollaborator = register({
|
||||
};
|
||||
},
|
||||
PanelComponent: ({ updateData, data, appState }) => {
|
||||
const { socketId, collaborator, withName, isBeingFollowed } =
|
||||
const { clientId, collaborator, withName, isBeingFollowed } =
|
||||
data as GoToCollaboratorComponentProps;
|
||||
|
||||
const background = getClientColor(socketId, collaborator);
|
||||
|
||||
const statusClassNames = clsx({
|
||||
"is-followed": isBeingFollowed,
|
||||
"is-current-user": collaborator.isCurrentUser === true,
|
||||
"is-speaking": collaborator.isSpeaking,
|
||||
"is-in-call": collaborator.isInCall,
|
||||
"is-muted": collaborator.isMuted,
|
||||
});
|
||||
|
||||
const statusIconJSX = collaborator.isInCall ? (
|
||||
collaborator.isSpeaking ? (
|
||||
<div
|
||||
className="UserList__collaborator-status-icon-speaking-indicator"
|
||||
title={t("userList.hint.isSpeaking")}
|
||||
>
|
||||
<div />
|
||||
<div />
|
||||
<div />
|
||||
</div>
|
||||
) : collaborator.isMuted ? (
|
||||
<div
|
||||
className="UserList__collaborator-status-icon-microphone-muted"
|
||||
title={t("userList.hint.micMuted")}
|
||||
>
|
||||
{microphoneMutedIcon}
|
||||
</div>
|
||||
) : (
|
||||
<div title={t("userList.hint.inCall")}>{microphoneIcon}</div>
|
||||
)
|
||||
) : null;
|
||||
const background = getClientColor(clientId);
|
||||
|
||||
return withName ? (
|
||||
<div
|
||||
className={`dropdown-menu-item dropdown-menu-item-base UserList__collaborator ${statusClassNames}`}
|
||||
style={{ [`--avatar-size` as any]: "1.5rem" }}
|
||||
className="dropdown-menu-item dropdown-menu-item-base UserList__collaborator"
|
||||
onClick={() => updateData<Collaborator>(collaborator)}
|
||||
>
|
||||
<Avatar
|
||||
@@ -90,42 +54,32 @@ export const actionGoToCollaborator = register({
|
||||
onClick={() => {}}
|
||||
name={collaborator.username || ""}
|
||||
src={collaborator.avatarUrl}
|
||||
className={statusClassNames}
|
||||
isBeingFollowed={isBeingFollowed}
|
||||
isCurrentUser={collaborator.isCurrentUser === true}
|
||||
/>
|
||||
<div className="UserList__collaborator-name">
|
||||
{collaborator.username}
|
||||
</div>
|
||||
<div className="UserList__collaborator-status-icons" aria-hidden>
|
||||
{isBeingFollowed && (
|
||||
<div
|
||||
className="UserList__collaborator-status-icon-is-followed"
|
||||
title={t("userList.hint.followStatus")}
|
||||
>
|
||||
{eyeIcon}
|
||||
</div>
|
||||
)}
|
||||
{statusIconJSX}
|
||||
<div
|
||||
className="UserList__collaborator-follow-status-icon"
|
||||
style={{ visibility: isBeingFollowed ? "visible" : "hidden" }}
|
||||
title={isBeingFollowed ? t("userList.hint.followStatus") : undefined}
|
||||
aria-hidden
|
||||
>
|
||||
{eyeIcon}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={`UserList__collaborator UserList__collaborator--avatar-only ${statusClassNames}`}
|
||||
>
|
||||
<Avatar
|
||||
color={background}
|
||||
onClick={() => {
|
||||
updateData(collaborator);
|
||||
}}
|
||||
name={collaborator.username || ""}
|
||||
src={collaborator.avatarUrl}
|
||||
className={statusClassNames}
|
||||
/>
|
||||
{statusIconJSX && (
|
||||
<div className="UserList__collaborator-status-icon">
|
||||
{statusIconJSX}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Avatar
|
||||
color={background}
|
||||
onClick={() => {
|
||||
updateData(collaborator);
|
||||
}}
|
||||
name={collaborator.username || ""}
|
||||
src={collaborator.avatarUrl}
|
||||
isBeingFollowed={isBeingFollowed}
|
||||
isCurrentUser={collaborator.isCurrentUser === true}
|
||||
/>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -209,7 +209,6 @@ const changeFontSize = (
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
app.scene.getContainerElement(oldElement),
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
newElement = offsetElementAfterFontResize(oldElement, newElement);
|
||||
@@ -731,7 +730,6 @@ export const actionChangeFontFamily = register({
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
app.scene.getContainerElement(oldElement),
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
return newElement;
|
||||
}
|
||||
@@ -831,7 +829,6 @@ export const actionChangeTextAlign = register({
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
app.scene.getContainerElement(oldElement),
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
return newElement;
|
||||
}
|
||||
@@ -921,7 +918,6 @@ export const actionChangeVerticalAlign = register({
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
app.scene.getContainerElement(oldElement),
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
return newElement;
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ export const actionSelectAll = register({
|
||||
// single linear element selected
|
||||
Object.keys(selectedElementIds).length === 1 &&
|
||||
isLinearElement(elements[0])
|
||||
? new LinearElementEditor(elements[0])
|
||||
? new LinearElementEditor(elements[0], app.scene)
|
||||
: null,
|
||||
},
|
||||
commitToHistory: true,
|
||||
|
||||
@@ -128,11 +128,7 @@ export const actionPasteStyles = register({
|
||||
element.id === newElement.containerId,
|
||||
) || null;
|
||||
}
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
container,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
redrawTextBoundingBox(newElement, container);
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -83,6 +83,6 @@ export { actionToggleObjectsSnapMode } from "./actionToggleObjectsSnapMode";
|
||||
|
||||
export { actionToggleStats } from "./actionToggleStats";
|
||||
export { actionUnbindText, actionBindText } from "./actionBoundText";
|
||||
export { actionLink } from "./actionLink";
|
||||
export { actionLink } from "../element/Hyperlink";
|
||||
export { actionToggleElementLock } from "./actionElementLock";
|
||||
export { actionToggleLinearEditor } from "./actionLinearEditor";
|
||||
|
||||
@@ -63,7 +63,6 @@ export const getDefaultAppState = (): Omit<
|
||||
isRotating: false,
|
||||
lastPointerDownWith: "mouse",
|
||||
multiElement: null,
|
||||
name: null,
|
||||
contextMenu: null,
|
||||
openMenu: null,
|
||||
openPopup: null,
|
||||
@@ -173,7 +172,6 @@ const APP_STATE_STORAGE_CONF = (<
|
||||
isRotating: { browser: false, export: false, server: false },
|
||||
lastPointerDownWith: { browser: true, export: false, server: false },
|
||||
multiElement: { browser: false, export: false, server: false },
|
||||
name: { browser: true, export: false, server: false },
|
||||
offsetLeft: { browser: false, export: false, server: false },
|
||||
offsetTop: { browser: false, export: false, server: false },
|
||||
contextMenu: { browser: false, export: false, server: false },
|
||||
|
||||
@@ -1,18 +1,3 @@
|
||||
import {
|
||||
COLOR_CHARCOAL_BLACK,
|
||||
COLOR_VOICE_CALL,
|
||||
COLOR_WHITE,
|
||||
THEME,
|
||||
} from "./constants";
|
||||
import { roundRect } from "./renderer/roundRect";
|
||||
import { InteractiveCanvasRenderConfig } from "./scene/types";
|
||||
import {
|
||||
Collaborator,
|
||||
InteractiveCanvasAppState,
|
||||
SocketId,
|
||||
UserIdleState,
|
||||
} from "./types";
|
||||
|
||||
function hashToInteger(id: string) {
|
||||
let hash = 0;
|
||||
if (id.length === 0) {
|
||||
@@ -26,12 +11,14 @@ function hashToInteger(id: string) {
|
||||
}
|
||||
|
||||
export const getClientColor = (
|
||||
socketId: SocketId,
|
||||
collaborator: Collaborator | undefined,
|
||||
/**
|
||||
* any uniquely identifying key, such as user id or socket id
|
||||
*/
|
||||
id: string,
|
||||
) => {
|
||||
// to get more even distribution in case `id` is not uniformly distributed to
|
||||
// begin with, we hash it
|
||||
const hash = Math.abs(hashToInteger(collaborator?.id || socketId));
|
||||
const hash = Math.abs(hashToInteger(id));
|
||||
// we want to get a multiple of 10 number in the range of 0-360 (in other
|
||||
// words a hue value of step size 10). There are 37 such values including 0.
|
||||
const hue = (hash % 37) * 10;
|
||||
@@ -51,209 +38,3 @@ export const getNameInitial = (name?: string | null) => {
|
||||
firstCodePoint ? String.fromCodePoint(firstCodePoint) : "?"
|
||||
).toUpperCase();
|
||||
};
|
||||
|
||||
export const renderRemoteCursors = ({
|
||||
context,
|
||||
renderConfig,
|
||||
appState,
|
||||
normalizedWidth,
|
||||
normalizedHeight,
|
||||
}: {
|
||||
context: CanvasRenderingContext2D;
|
||||
renderConfig: InteractiveCanvasRenderConfig;
|
||||
appState: InteractiveCanvasAppState;
|
||||
normalizedWidth: number;
|
||||
normalizedHeight: number;
|
||||
}) => {
|
||||
// Paint remote pointers
|
||||
for (const [socketId, pointer] of renderConfig.remotePointerViewportCoords) {
|
||||
let { x, y } = pointer;
|
||||
|
||||
const collaborator = appState.collaborators.get(socketId);
|
||||
|
||||
x -= appState.offsetLeft;
|
||||
y -= appState.offsetTop;
|
||||
|
||||
const width = 11;
|
||||
const height = 14;
|
||||
|
||||
const isOutOfBounds =
|
||||
x < 0 ||
|
||||
x > normalizedWidth - width ||
|
||||
y < 0 ||
|
||||
y > normalizedHeight - height;
|
||||
|
||||
x = Math.max(x, 0);
|
||||
x = Math.min(x, normalizedWidth - width);
|
||||
y = Math.max(y, 0);
|
||||
y = Math.min(y, normalizedHeight - height);
|
||||
|
||||
const background = getClientColor(socketId, collaborator);
|
||||
|
||||
context.save();
|
||||
context.strokeStyle = background;
|
||||
context.fillStyle = background;
|
||||
|
||||
const userState = renderConfig.remotePointerUserStates.get(socketId);
|
||||
const isInactive =
|
||||
isOutOfBounds ||
|
||||
userState === UserIdleState.IDLE ||
|
||||
userState === UserIdleState.AWAY;
|
||||
|
||||
if (isInactive) {
|
||||
context.globalAlpha = 0.3;
|
||||
}
|
||||
|
||||
if (renderConfig.remotePointerButton.get(socketId) === "down") {
|
||||
context.beginPath();
|
||||
context.arc(x, y, 15, 0, 2 * Math.PI, false);
|
||||
context.lineWidth = 3;
|
||||
context.strokeStyle = "#ffffff88";
|
||||
context.stroke();
|
||||
context.closePath();
|
||||
|
||||
context.beginPath();
|
||||
context.arc(x, y, 15, 0, 2 * Math.PI, false);
|
||||
context.lineWidth = 1;
|
||||
context.strokeStyle = background;
|
||||
context.stroke();
|
||||
context.closePath();
|
||||
}
|
||||
|
||||
// TODO remove the dark theme color after we stop inverting canvas colors
|
||||
const IS_SPEAKING_COLOR =
|
||||
appState.theme === THEME.DARK ? "#2f6330" : COLOR_VOICE_CALL;
|
||||
|
||||
const isSpeaking = collaborator?.isSpeaking;
|
||||
|
||||
if (isSpeaking) {
|
||||
// cursor outline for currently speaking user
|
||||
context.fillStyle = IS_SPEAKING_COLOR;
|
||||
context.strokeStyle = IS_SPEAKING_COLOR;
|
||||
context.lineWidth = 10;
|
||||
context.lineJoin = "round";
|
||||
context.beginPath();
|
||||
context.moveTo(x, y);
|
||||
context.lineTo(x + 0, y + 14);
|
||||
context.lineTo(x + 4, y + 9);
|
||||
context.lineTo(x + 11, y + 8);
|
||||
context.closePath();
|
||||
context.stroke();
|
||||
context.fill();
|
||||
}
|
||||
|
||||
// Background (white outline) for arrow
|
||||
context.fillStyle = COLOR_WHITE;
|
||||
context.strokeStyle = COLOR_WHITE;
|
||||
context.lineWidth = 6;
|
||||
context.lineJoin = "round";
|
||||
context.beginPath();
|
||||
context.moveTo(x, y);
|
||||
context.lineTo(x + 0, y + 14);
|
||||
context.lineTo(x + 4, y + 9);
|
||||
context.lineTo(x + 11, y + 8);
|
||||
context.closePath();
|
||||
context.stroke();
|
||||
context.fill();
|
||||
|
||||
// Arrow
|
||||
context.fillStyle = background;
|
||||
context.strokeStyle = background;
|
||||
context.lineWidth = 2;
|
||||
context.lineJoin = "round";
|
||||
context.beginPath();
|
||||
if (isInactive) {
|
||||
context.moveTo(x - 1, y - 1);
|
||||
context.lineTo(x - 1, y + 15);
|
||||
context.lineTo(x + 5, y + 10);
|
||||
context.lineTo(x + 12, y + 9);
|
||||
context.closePath();
|
||||
context.fill();
|
||||
} else {
|
||||
context.moveTo(x, y);
|
||||
context.lineTo(x + 0, y + 14);
|
||||
context.lineTo(x + 4, y + 9);
|
||||
context.lineTo(x + 11, y + 8);
|
||||
context.closePath();
|
||||
context.fill();
|
||||
context.stroke();
|
||||
}
|
||||
|
||||
const username = renderConfig.remotePointerUsernames.get(socketId) || "";
|
||||
|
||||
if (!isOutOfBounds && username) {
|
||||
context.font = "600 12px sans-serif"; // font has to be set before context.measureText()
|
||||
|
||||
const offsetX = (isSpeaking ? x + 0 : x) + width / 2;
|
||||
const offsetY = (isSpeaking ? y + 0 : y) + height + 2;
|
||||
const paddingHorizontal = 5;
|
||||
const paddingVertical = 3;
|
||||
const measure = context.measureText(username);
|
||||
const measureHeight =
|
||||
measure.actualBoundingBoxDescent + measure.actualBoundingBoxAscent;
|
||||
const finalHeight = Math.max(measureHeight, 12);
|
||||
|
||||
const boxX = offsetX - 1;
|
||||
const boxY = offsetY - 1;
|
||||
const boxWidth = measure.width + 2 + paddingHorizontal * 2 + 2;
|
||||
const boxHeight = finalHeight + 2 + paddingVertical * 2 + 2;
|
||||
if (context.roundRect) {
|
||||
context.beginPath();
|
||||
context.roundRect(boxX, boxY, boxWidth, boxHeight, 8);
|
||||
context.fillStyle = background;
|
||||
context.fill();
|
||||
context.strokeStyle = COLOR_WHITE;
|
||||
context.stroke();
|
||||
|
||||
if (isSpeaking) {
|
||||
context.beginPath();
|
||||
context.roundRect(boxX - 2, boxY - 2, boxWidth + 4, boxHeight + 4, 8);
|
||||
context.strokeStyle = IS_SPEAKING_COLOR;
|
||||
context.stroke();
|
||||
}
|
||||
} else {
|
||||
roundRect(context, boxX, boxY, boxWidth, boxHeight, 8, COLOR_WHITE);
|
||||
}
|
||||
context.fillStyle = COLOR_CHARCOAL_BLACK;
|
||||
|
||||
context.fillText(
|
||||
username,
|
||||
offsetX + paddingHorizontal + 1,
|
||||
offsetY +
|
||||
paddingVertical +
|
||||
measure.actualBoundingBoxAscent +
|
||||
Math.floor((finalHeight - measureHeight) / 2) +
|
||||
2,
|
||||
);
|
||||
|
||||
// draw three vertical bars signalling someone is speaking
|
||||
if (isSpeaking) {
|
||||
context.fillStyle = IS_SPEAKING_COLOR;
|
||||
const barheight = 8;
|
||||
const margin = 8;
|
||||
const gap = 5;
|
||||
context.fillRect(
|
||||
boxX + boxWidth + margin,
|
||||
boxY + (boxHeight / 2 - barheight / 2),
|
||||
2,
|
||||
barheight,
|
||||
);
|
||||
context.fillRect(
|
||||
boxX + boxWidth + margin + gap,
|
||||
boxY + (boxHeight / 2 - (barheight * 2) / 2),
|
||||
2,
|
||||
barheight * 2,
|
||||
);
|
||||
context.fillRect(
|
||||
boxX + boxWidth + margin + gap * 2,
|
||||
boxY + (boxHeight / 2 - barheight / 2),
|
||||
2,
|
||||
barheight,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
context.restore();
|
||||
context.closePath();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -16,7 +16,8 @@ import {
|
||||
import { deepCopyElement } from "./element/newElement";
|
||||
import { mutateElement } from "./element/mutateElement";
|
||||
import { getContainingFrame } from "./frame";
|
||||
import { arrayToMap, isMemberOf, isPromiseLike } from "./utils";
|
||||
import { isMemberOf, isPromiseLike } from "./utils";
|
||||
import { t } from "./i18n";
|
||||
|
||||
type ElementsClipboard = {
|
||||
type: typeof EXPORT_DATA_TYPES.excalidrawClipboard;
|
||||
@@ -125,7 +126,6 @@ export const serializeAsClipboardJSON = ({
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
files: BinaryFiles | null;
|
||||
}) => {
|
||||
const elementsMap = arrayToMap(elements);
|
||||
const framesToCopy = new Set(
|
||||
elements.filter((element) => isFrameLikeElement(element)),
|
||||
);
|
||||
@@ -152,8 +152,8 @@ export const serializeAsClipboardJSON = ({
|
||||
type: EXPORT_DATA_TYPES.excalidrawClipboard,
|
||||
elements: elements.map((element) => {
|
||||
if (
|
||||
getContainingFrame(element, elementsMap) &&
|
||||
!framesToCopy.has(getContainingFrame(element, elementsMap)!)
|
||||
getContainingFrame(element) &&
|
||||
!framesToCopy.has(getContainingFrame(element)!)
|
||||
) {
|
||||
const copiedElement = deepCopyElement(element);
|
||||
mutateElement(copiedElement, {
|
||||
@@ -434,7 +434,7 @@ export const copyTextToSystemClipboard = async (
|
||||
|
||||
// (3) if that fails, use document.execCommand
|
||||
if (!copyTextViaExecCommand(text)) {
|
||||
throw new Error("Error copying to clipboard.");
|
||||
throw new Error(t("errors.copyToSystemClipboardFailed"));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -306,25 +306,6 @@ export const ShapesSwitcher = ({
|
||||
title={t("toolBar.extraTools")}
|
||||
>
|
||||
{extraToolsIcon}
|
||||
{app.props.aiEnabled !== false && (
|
||||
<div
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
marginLeft: "auto",
|
||||
padding: "2px 4px",
|
||||
borderRadius: 6,
|
||||
fontSize: 8,
|
||||
fontFamily: "Cascadia, monospace",
|
||||
position: "absolute",
|
||||
background: "pink",
|
||||
color: "black",
|
||||
bottom: 3,
|
||||
right: 4,
|
||||
}}
|
||||
>
|
||||
AI
|
||||
</div>
|
||||
)}
|
||||
</DropdownMenu.Trigger>
|
||||
<DropdownMenu.Content
|
||||
onClickOutside={() => setIsExtraToolsMenuOpen(false)}
|
||||
|
||||
@@ -89,7 +89,6 @@ import {
|
||||
TOOL_TYPE,
|
||||
EDITOR_LS_KEYS,
|
||||
isIOS,
|
||||
supportsResizeObserver,
|
||||
} from "../constants";
|
||||
import { ExportedElements, exportCanvas, loadFromBlob } from "../data";
|
||||
import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
|
||||
@@ -271,7 +270,6 @@ import {
|
||||
updateStable,
|
||||
addEventListener,
|
||||
normalizeEOL,
|
||||
getDateTime,
|
||||
} from "../utils";
|
||||
import {
|
||||
createSrcDoc,
|
||||
@@ -327,7 +325,9 @@ import {
|
||||
showHyperlinkTooltip,
|
||||
hideHyperlinkToolip,
|
||||
Hyperlink,
|
||||
} from "../components/hyperlink/Hyperlink";
|
||||
isPointHittingLink,
|
||||
isPointHittingLinkIcon,
|
||||
} from "../element/Hyperlink";
|
||||
import { isLocalLink, normalizeLink, toValidURL } from "../data/url";
|
||||
import { shouldShowBoundingBox } from "../element/transformHandles";
|
||||
import { actionUnlockAllElements } from "../actions/actionElementLock";
|
||||
@@ -409,10 +409,7 @@ import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
|
||||
import { getRenderOpacity } from "../renderer/renderElement";
|
||||
import { textWysiwyg } from "../element/textWysiwyg";
|
||||
import { isOverScrollBars } from "../scene/scrollbars";
|
||||
import {
|
||||
isPointHittingLink,
|
||||
isPointHittingLinkIcon,
|
||||
} from "./hyperlink/helpers";
|
||||
import { getFileName } from "../data/filename";
|
||||
|
||||
const AppContext = React.createContext<AppClassProperties>(null!);
|
||||
const AppPropsContext = React.createContext<AppProps>(null!);
|
||||
@@ -477,6 +474,9 @@ export const useExcalidrawSetAppState = () =>
|
||||
export const useExcalidrawActionManager = () =>
|
||||
useContext(ExcalidrawActionManagerContext);
|
||||
|
||||
const supportsResizeObserver =
|
||||
typeof window !== "undefined" && "ResizeObserver" in window;
|
||||
|
||||
let didTapTwice: boolean = false;
|
||||
let tappedTwiceTimer = 0;
|
||||
let isHoldingSpace: boolean = false;
|
||||
@@ -620,7 +620,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
gridModeEnabled = false,
|
||||
objectsSnapModeEnabled = false,
|
||||
theme = defaultAppState.theme,
|
||||
name = `${t("labels.untitled")}-${getDateTime()}`,
|
||||
} = props;
|
||||
this.state = {
|
||||
...defaultAppState,
|
||||
@@ -631,7 +630,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
zenModeEnabled,
|
||||
objectsSnapModeEnabled,
|
||||
gridSize: gridModeEnabled ? GRID_SIZE : null,
|
||||
name,
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight,
|
||||
};
|
||||
@@ -663,7 +661,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
getSceneElements: this.getSceneElements,
|
||||
getAppState: () => this.state,
|
||||
getFiles: () => this.files,
|
||||
getName: this.getName,
|
||||
registerAction: (action: Action) => {
|
||||
this.actionManager.registerAction(action);
|
||||
},
|
||||
@@ -953,7 +950,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
normalizedWidth,
|
||||
normalizedHeight,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
const hasBeenInitialized = this.initializedEmbeds.has(el.id);
|
||||
|
||||
@@ -1129,7 +1125,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
display: isVisible ? "block" : "none",
|
||||
opacity: getRenderOpacity(
|
||||
el,
|
||||
getContainingFrame(el, this.scene.getNonDeletedElementsMap()),
|
||||
getContainingFrame(el),
|
||||
this.elementsPendingErasure,
|
||||
),
|
||||
["--embeddable-radius" as string]: `${getCornerRadius(
|
||||
@@ -1288,7 +1284,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
scrollY: this.state.scrollY,
|
||||
zoom: this.state.zoom,
|
||||
},
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
)
|
||||
) {
|
||||
// if frame not visible, don't render its name
|
||||
@@ -1414,13 +1409,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
});
|
||||
};
|
||||
|
||||
private toggleOverscrollBehavior(event: React.PointerEvent) {
|
||||
// when pointer inside editor, disable overscroll behavior to prevent
|
||||
// panning to trigger history back/forward on MacOS Chrome
|
||||
document.documentElement.style.overscrollBehaviorX =
|
||||
event.type === "pointerenter" ? "none" : "auto";
|
||||
}
|
||||
|
||||
public render() {
|
||||
const selectedElements = this.scene.getSelectedElements(this.state);
|
||||
const { renderTopRightUI, renderCustomStats } = this.props;
|
||||
@@ -1474,8 +1462,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
onKeyDown={
|
||||
this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
|
||||
}
|
||||
onPointerEnter={this.toggleOverscrollBehavior}
|
||||
onPointerLeave={this.toggleOverscrollBehavior}
|
||||
>
|
||||
<AppContext.Provider value={this}>
|
||||
<AppPropsContext.Provider value={this.props}>
|
||||
@@ -1538,7 +1524,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
<Hyperlink
|
||||
key={firstSelectedElement.id}
|
||||
element={firstSelectedElement}
|
||||
elementsMap={allElementsMap}
|
||||
setAppState={this.setAppState}
|
||||
onLinkOpen={this.props.onLinkOpen}
|
||||
setToast={this.setToast}
|
||||
@@ -1552,7 +1537,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
isMagicFrameElement(firstSelectedElement) && (
|
||||
<ElementCanvasButtons
|
||||
element={firstSelectedElement}
|
||||
elementsMap={elementsMap}
|
||||
>
|
||||
<ElementCanvasButton
|
||||
title={t("labels.convertToCode")}
|
||||
@@ -1573,7 +1557,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
?.status === "done" && (
|
||||
<ElementCanvasButtons
|
||||
element={firstSelectedElement}
|
||||
elementsMap={elementsMap}
|
||||
>
|
||||
<ElementCanvasButton
|
||||
title={t("labels.copySource")}
|
||||
@@ -1741,7 +1724,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.files,
|
||||
{
|
||||
exportBackground: this.state.exportBackground,
|
||||
name: this.getName(),
|
||||
name: this.props.name || getFileName(),
|
||||
viewBackgroundColor: this.state.viewBackgroundColor,
|
||||
exportingFrame: opts.exportingFrame,
|
||||
},
|
||||
@@ -2140,7 +2123,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
let gridSize = actionResult?.appState?.gridSize || null;
|
||||
const theme =
|
||||
actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
|
||||
const name = actionResult?.appState?.name ?? this.state.name;
|
||||
|
||||
const errorMessage =
|
||||
actionResult?.appState?.errorMessage ?? this.state.errorMessage;
|
||||
if (typeof this.props.viewModeEnabled !== "undefined") {
|
||||
@@ -2177,7 +2160,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
zenModeEnabled,
|
||||
gridSize,
|
||||
theme,
|
||||
name,
|
||||
errorMessage,
|
||||
});
|
||||
},
|
||||
@@ -2467,7 +2449,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
isSomeElementSelected.clearCache();
|
||||
selectGroupsForSelectedElements.clearCache();
|
||||
touchTimeout = 0;
|
||||
document.documentElement.style.overscrollBehaviorX = "";
|
||||
}
|
||||
|
||||
private onResize = withBatchedUpdates(() => {
|
||||
@@ -2604,10 +2585,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
|
||||
componentDidUpdate(prevProps: AppProps, prevState: AppState) {
|
||||
this.updateEmbeddables();
|
||||
const elements = this.scene.getElementsIncludingDeleted();
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
|
||||
if (!this.state.showWelcomeScreen && !elements.length) {
|
||||
if (
|
||||
!this.state.showWelcomeScreen &&
|
||||
!this.scene.getElementsIncludingDeleted().length
|
||||
) {
|
||||
this.setState({ showWelcomeScreen: true });
|
||||
}
|
||||
|
||||
@@ -2761,21 +2742,27 @@ class App extends React.Component<AppProps, AppState> {
|
||||
LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
multiElement,
|
||||
-1,
|
||||
elementsMap,
|
||||
),
|
||||
),
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
this.history.record(this.state, elements);
|
||||
this.history.record(this.state, this.scene.getElementsIncludingDeleted());
|
||||
|
||||
// Do not notify consumers if we're still loading the scene. Among other
|
||||
// potential issues, this fixes a case where the tab isn't focused during
|
||||
// init, which would trigger onChange with empty elements, which would then
|
||||
// override whatever is in localStorage currently.
|
||||
if (!this.state.isLoading) {
|
||||
this.props.onChange?.(elements, this.state, this.files);
|
||||
this.onChangeEmitter.trigger(elements, this.state, this.files);
|
||||
this.props.onChange?.(
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
this.state,
|
||||
this.files,
|
||||
);
|
||||
this.onChangeEmitter.trigger(
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
this.state,
|
||||
this.files,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3125,11 +3112,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
newElement,
|
||||
this.scene.getElementsMapIncludingDeleted(),
|
||||
);
|
||||
redrawTextBoundingBox(
|
||||
newElement,
|
||||
container,
|
||||
this.scene.getElementsMapIncludingDeleted(),
|
||||
);
|
||||
redrawTextBoundingBox(newElement, container);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3212,13 +3195,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
try {
|
||||
return { file: await ImageURLToFile(url) };
|
||||
} catch (error: any) {
|
||||
let errorMessage = error.message;
|
||||
if (error.cause === "FETCH_ERROR") {
|
||||
errorMessage = t("errors.failedToFetchImage");
|
||||
} else if (error.cause === "UNSUPPORTED") {
|
||||
errorMessage = t("errors.unsupportedFileType");
|
||||
}
|
||||
return { errorMessage };
|
||||
return { errorMessage: error.message as string };
|
||||
}
|
||||
}),
|
||||
);
|
||||
@@ -3845,7 +3822,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
y: element.y + offsetY,
|
||||
});
|
||||
|
||||
updateBoundElements(element, this.scene.getNonDeletedElementsMap(), {
|
||||
updateBoundElements(element, {
|
||||
simultaneouslyUpdated: selectedElements,
|
||||
});
|
||||
});
|
||||
@@ -3868,6 +3845,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.setState({
|
||||
editingLinearElement: new LinearElementEditor(
|
||||
selectedElement,
|
||||
this.scene,
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -4018,14 +3996,9 @@ class App extends React.Component<AppProps, AppState> {
|
||||
}
|
||||
if (isArrowKey(event.key)) {
|
||||
const selectedElements = this.scene.getSelectedElements(this.state);
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
isBindingEnabled(this.state)
|
||||
? bindOrUnbindSelectedElements(
|
||||
selectedElements,
|
||||
this.scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
)
|
||||
: unbindLinearElements(selectedElements, elementsMap);
|
||||
? bindOrUnbindSelectedElements(selectedElements)
|
||||
: unbindLinearElements(selectedElements);
|
||||
this.setState({ suggestedBindings: [] });
|
||||
}
|
||||
});
|
||||
@@ -4127,14 +4100,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
return gesture.pointers.size >= 2;
|
||||
};
|
||||
|
||||
public getName = () => {
|
||||
return (
|
||||
this.state.name ||
|
||||
this.props.name ||
|
||||
`${t("labels.untitled")}-${getDateTime()}`
|
||||
);
|
||||
};
|
||||
|
||||
// fires only on Safari
|
||||
private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
|
||||
event.preventDefault();
|
||||
@@ -4206,21 +4171,20 @@ class App extends React.Component<AppProps, AppState> {
|
||||
isExistingElement?: boolean;
|
||||
},
|
||||
) {
|
||||
const elementsMap = this.scene.getElementsMapIncludingDeleted();
|
||||
|
||||
const updateElement = (
|
||||
text: string,
|
||||
originalText: string,
|
||||
isDeleted: boolean,
|
||||
) => {
|
||||
this.scene.replaceAllElements([
|
||||
// Not sure why we include deleted elements as well hence using deleted elements map
|
||||
...this.scene.getElementsIncludingDeleted().map((_element) => {
|
||||
if (_element.id === element.id && isTextElement(_element)) {
|
||||
return updateTextElement(
|
||||
_element,
|
||||
getContainerElement(_element, elementsMap),
|
||||
elementsMap,
|
||||
getContainerElement(
|
||||
_element,
|
||||
this.scene.getElementsMapIncludingDeleted(),
|
||||
),
|
||||
{
|
||||
text,
|
||||
isDeleted,
|
||||
@@ -4252,7 +4216,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
onChange: withBatchedUpdates((text) => {
|
||||
updateElement(text, text, false);
|
||||
if (isNonDeletedElement(element)) {
|
||||
updateBoundElements(element, elementsMap);
|
||||
updateBoundElements(element);
|
||||
}
|
||||
}),
|
||||
onSubmit: withBatchedUpdates(({ text, viaKeyboard, originalText }) => {
|
||||
@@ -4391,7 +4355,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
!(isTextElement(element) && element.containerId)),
|
||||
);
|
||||
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
return getElementsAtPosition(elements, (element) =>
|
||||
hitTest(
|
||||
element,
|
||||
@@ -4399,15 +4362,15 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.frameNameBoundsCache,
|
||||
x,
|
||||
y,
|
||||
elementsMap,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
),
|
||||
).filter((element) => {
|
||||
// hitting a frame's element from outside the frame is not considered a hit
|
||||
const containingFrame = getContainingFrame(element, elementsMap);
|
||||
const containingFrame = getContainingFrame(element);
|
||||
return containingFrame &&
|
||||
this.state.frameRendering.enabled &&
|
||||
this.state.frameRendering.clip
|
||||
? isCursorInFrame({ x, y }, containingFrame, elementsMap)
|
||||
? isCursorInFrame({ x, y }, containingFrame)
|
||||
: true;
|
||||
});
|
||||
}
|
||||
@@ -4589,7 +4552,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
) {
|
||||
this.history.resumeRecording();
|
||||
this.setState({
|
||||
editingLinearElement: new LinearElementEditor(selectedElements[0]),
|
||||
editingLinearElement: new LinearElementEditor(
|
||||
selectedElements[0],
|
||||
this.scene,
|
||||
),
|
||||
});
|
||||
return;
|
||||
} else if (
|
||||
@@ -4649,7 +4615,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state,
|
||||
sceneX,
|
||||
sceneY,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
if (container) {
|
||||
@@ -4661,7 +4626,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state,
|
||||
this.frameNameBoundsCache,
|
||||
[sceneX, sceneY],
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
)
|
||||
) {
|
||||
const midPoint = getContainerCenter(
|
||||
@@ -4702,7 +4666,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
index <= hitElementIndex &&
|
||||
isPointHittingLink(
|
||||
element,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.state,
|
||||
[scenePointer.x, scenePointer.y],
|
||||
this.device.editor.isMobile,
|
||||
@@ -4733,10 +4696,8 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.lastPointerDownEvent!,
|
||||
this.state,
|
||||
);
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
const lastPointerDownHittingLinkIcon = isPointHittingLink(
|
||||
this.hitLinkElement,
|
||||
elementsMap,
|
||||
this.state,
|
||||
[lastPointerDownCoords.x, lastPointerDownCoords.y],
|
||||
this.device.editor.isMobile,
|
||||
@@ -4747,7 +4708,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
);
|
||||
const lastPointerUpHittingLinkIcon = isPointHittingLink(
|
||||
this.hitLinkElement,
|
||||
elementsMap,
|
||||
this.state,
|
||||
[lastPointerUpCoords.x, lastPointerUpCoords.y],
|
||||
this.device.editor.isMobile,
|
||||
@@ -4784,11 +4744,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
x: number;
|
||||
y: number;
|
||||
}) => {
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
const frames = this.scene
|
||||
.getNonDeletedFramesLikes()
|
||||
.filter((frame): frame is ExcalidrawFrameLikeElement =>
|
||||
isCursorInFrame(sceneCoords, frame, elementsMap),
|
||||
isCursorInFrame(sceneCoords, frame),
|
||||
);
|
||||
|
||||
return frames.length ? frames[frames.length - 1] : null;
|
||||
@@ -4892,7 +4851,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
y: scenePointerY,
|
||||
},
|
||||
event,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
this.setState((prevState) => {
|
||||
@@ -4932,7 +4890,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
scenePointerX,
|
||||
scenePointerY,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -5083,7 +5040,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
scenePointerY,
|
||||
this.state.zoom,
|
||||
event.pointerType,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
if (
|
||||
elementWithTransformHandleType &&
|
||||
@@ -5131,11 +5087,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
!this.state.selectedElementIds[this.hitLinkElement.id]
|
||||
) {
|
||||
setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
|
||||
showHyperlinkTooltip(
|
||||
this.hitLinkElement,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
showHyperlinkTooltip(this.hitLinkElement, this.state);
|
||||
} else {
|
||||
hideHyperlinkToolip();
|
||||
if (
|
||||
@@ -5313,12 +5265,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
scenePointerX: number,
|
||||
scenePointerY: number,
|
||||
) {
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
|
||||
const element = LinearElementEditor.getElement(
|
||||
linearElementEditor.elementId,
|
||||
elementsMap,
|
||||
);
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
||||
|
||||
if (!element) {
|
||||
@@ -5333,12 +5283,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state,
|
||||
this.frameNameBoundsCache,
|
||||
[scenePointerX, scenePointerY],
|
||||
elementsMap,
|
||||
)
|
||||
) {
|
||||
hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
|
||||
element,
|
||||
elementsMap,
|
||||
this.state.zoom,
|
||||
scenePointerX,
|
||||
scenePointerY,
|
||||
@@ -5768,12 +5716,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
if (
|
||||
clicklength < 300 &&
|
||||
isIframeLikeElement(this.hitLinkElement) &&
|
||||
!isPointHittingLinkIcon(
|
||||
this.hitLinkElement,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.state,
|
||||
[scenePointer.x, scenePointer.y],
|
||||
)
|
||||
!isPointHittingLinkIcon(this.hitLinkElement, this.state, [
|
||||
scenePointer.x,
|
||||
scenePointer.y,
|
||||
])
|
||||
) {
|
||||
this.handleEmbeddableCenterClick(this.hitLinkElement);
|
||||
} else {
|
||||
@@ -6071,9 +6017,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
): boolean => {
|
||||
if (this.state.activeTool.type === "selection") {
|
||||
const elements = this.scene.getNonDeletedElements();
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
const selectedElements = this.scene.getSelectedElements(this.state);
|
||||
|
||||
if (selectedElements.length === 1 && !this.state.editingLinearElement) {
|
||||
const elementWithTransformHandleType =
|
||||
getElementWithTransformHandleType(
|
||||
@@ -6083,7 +6027,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
pointerDownState.origin.y,
|
||||
this.state.zoom,
|
||||
event.pointerType,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
if (elementWithTransformHandleType != null) {
|
||||
this.setState({
|
||||
@@ -6107,7 +6050,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
getResizeOffsetXY(
|
||||
pointerDownState.resize.handleType,
|
||||
selectedElements,
|
||||
elementsMap,
|
||||
pointerDownState.origin.x,
|
||||
pointerDownState.origin.y,
|
||||
),
|
||||
@@ -6132,8 +6074,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.history,
|
||||
pointerDownState.origin,
|
||||
linearElementEditor,
|
||||
this.scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
if (ret.hitElement) {
|
||||
pointerDownState.hit.element = ret.hitElement;
|
||||
@@ -6389,7 +6330,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state,
|
||||
sceneX,
|
||||
sceneY,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
if (hasBoundTextElement(element)) {
|
||||
@@ -6470,8 +6410,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
|
||||
const boundElement = getHoveredElementForBinding(
|
||||
pointerDownState.origin,
|
||||
this.scene.getNonDeletedElements(),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.scene,
|
||||
);
|
||||
this.scene.addNewElement(element);
|
||||
this.setState({
|
||||
@@ -6739,8 +6678,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
});
|
||||
const boundElement = getHoveredElementForBinding(
|
||||
pointerDownState.origin,
|
||||
this.scene.getNonDeletedElements(),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.scene,
|
||||
);
|
||||
|
||||
this.scene.addNewElement(element);
|
||||
@@ -6886,7 +6824,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.scene.getNonDeletedElements(),
|
||||
selectedElements,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -6910,7 +6847,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.scene.getNonDeletedElements(),
|
||||
selectedElements,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -7010,7 +6946,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
|
||||
if (this.state.selectedLinearElement) {
|
||||
const linearElementEditor =
|
||||
@@ -7021,7 +6956,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state.selectedLinearElement,
|
||||
pointerCoords,
|
||||
this.state,
|
||||
elementsMap,
|
||||
)
|
||||
) {
|
||||
const ret = LinearElementEditor.addMidpoint(
|
||||
@@ -7029,7 +6963,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
pointerCoords,
|
||||
this.state,
|
||||
!event[KEYS.CTRL_OR_CMD],
|
||||
elementsMap,
|
||||
);
|
||||
if (!ret) {
|
||||
return;
|
||||
@@ -7188,11 +7121,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.maybeCacheReferenceSnapPoints(event, selectedElements);
|
||||
|
||||
const { snapOffset, snapLines } = snapDraggedElements(
|
||||
originalElements,
|
||||
getSelectedElements(originalElements, this.state),
|
||||
dragOffset,
|
||||
this.state,
|
||||
event,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
this.setState({ snapLines });
|
||||
@@ -7376,7 +7308,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
event,
|
||||
this.state,
|
||||
this.setState.bind(this),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
// regular box-select
|
||||
} else {
|
||||
@@ -7407,7 +7338,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
const elementsWithinSelection = getElementsWithinSelection(
|
||||
elements,
|
||||
draggingElement,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
this.setState((prevState) => {
|
||||
@@ -7450,7 +7380,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
selectedLinearElement:
|
||||
elementsWithinSelection.length === 1 &&
|
||||
isLinearElement(elementsWithinSelection[0])
|
||||
? new LinearElementEditor(elementsWithinSelection[0])
|
||||
? new LinearElementEditor(
|
||||
elementsWithinSelection[0],
|
||||
this.scene,
|
||||
)
|
||||
: null,
|
||||
showHyperlinkPopup:
|
||||
elementsWithinSelection.length === 1 &&
|
||||
@@ -7536,7 +7469,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.setState({
|
||||
selectedElementsAreBeingDragged: false,
|
||||
});
|
||||
const elementsMap = this.scene.getNonDeletedElementsMap();
|
||||
|
||||
// Handle end of dragging a point of a linear element, might close a loop
|
||||
// and sets binding element
|
||||
if (this.state.editingLinearElement) {
|
||||
@@ -7551,8 +7484,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
childEvent,
|
||||
this.state.editingLinearElement,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
);
|
||||
if (editingLinearElement !== this.state.editingLinearElement) {
|
||||
this.setState({
|
||||
@@ -7576,8 +7507,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
childEvent,
|
||||
this.state.selectedLinearElement,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
const { startBindingElement, endBindingElement } =
|
||||
@@ -7588,7 +7517,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
element,
|
||||
startBindingElement,
|
||||
endBindingElement,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7728,7 +7656,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.state,
|
||||
this.scene,
|
||||
pointerCoords,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
this.setState({ suggestedBindings: [], startBoundElement: null });
|
||||
@@ -7746,7 +7673,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
},
|
||||
prevState,
|
||||
),
|
||||
selectedLinearElement: new LinearElementEditor(draggingElement),
|
||||
selectedLinearElement: new LinearElementEditor(
|
||||
draggingElement,
|
||||
this.scene,
|
||||
),
|
||||
}));
|
||||
} else {
|
||||
this.setState((prevState) => ({
|
||||
@@ -7793,16 +7723,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
);
|
||||
|
||||
if (linearElement?.frameId) {
|
||||
const frame = getContainingFrame(linearElement, elementsMap);
|
||||
const frame = getContainingFrame(linearElement);
|
||||
|
||||
if (frame && linearElement) {
|
||||
if (
|
||||
!elementOverlapsWithFrame(
|
||||
linearElement,
|
||||
frame,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
)
|
||||
) {
|
||||
if (!elementOverlapsWithFrame(linearElement, frame)) {
|
||||
// remove the linear element from all groups
|
||||
// before removing it from the frame as well
|
||||
mutateElement(linearElement, {
|
||||
@@ -7913,7 +7837,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
const elementsInsideFrame = getElementsInNewFrame(
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
draggingElement,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
this.scene.replaceAllElements(
|
||||
@@ -7964,7 +7887,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
frame,
|
||||
this.state,
|
||||
elementsMap,
|
||||
),
|
||||
frame,
|
||||
this,
|
||||
@@ -7986,7 +7908,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
// the one we've hit
|
||||
if (selectedELements.length === 1) {
|
||||
this.setState({
|
||||
selectedLinearElement: new LinearElementEditor(hitElement),
|
||||
selectedLinearElement: new LinearElementEditor(
|
||||
hitElement,
|
||||
this.scene,
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8099,7 +8024,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
selectedLinearElement:
|
||||
newSelectedElements.length === 1 &&
|
||||
isLinearElement(newSelectedElements[0])
|
||||
? new LinearElementEditor(newSelectedElements[0])
|
||||
? new LinearElementEditor(
|
||||
newSelectedElements[0],
|
||||
this.scene,
|
||||
)
|
||||
: prevState.selectedLinearElement,
|
||||
};
|
||||
});
|
||||
@@ -8173,7 +8101,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
// Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
|
||||
// Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
|
||||
prevState.selectedLinearElement?.elementId !== hitElement.id
|
||||
? new LinearElementEditor(hitElement)
|
||||
? new LinearElementEditor(hitElement, this.scene)
|
||||
: prevState.selectedLinearElement,
|
||||
}));
|
||||
}
|
||||
@@ -8237,16 +8165,9 @@ class App extends React.Component<AppProps, AppState> {
|
||||
}
|
||||
|
||||
if (pointerDownState.drag.hasOccurred || isResizing || isRotating) {
|
||||
isBindingEnabled(this.state)
|
||||
? bindOrUnbindSelectedElements(
|
||||
this.scene.getSelectedElements(this.state),
|
||||
this.scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
)
|
||||
: unbindLinearElements(
|
||||
this.scene.getSelectedElements(this.state),
|
||||
elementsMap,
|
||||
);
|
||||
(isBindingEnabled(this.state)
|
||||
? bindOrUnbindSelectedElements
|
||||
: unbindLinearElements)(this.scene.getSelectedElements(this.state));
|
||||
}
|
||||
|
||||
if (activeTool.type === "laser") {
|
||||
@@ -8482,18 +8403,10 @@ class App extends React.Component<AppProps, AppState> {
|
||||
// mustn't be larger than 128 px
|
||||
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
|
||||
const cursorImageSizePx = 96;
|
||||
let imagePreview;
|
||||
|
||||
try {
|
||||
imagePreview = await resizeImageFile(imageFile, {
|
||||
maxWidthOrHeight: cursorImageSizePx,
|
||||
});
|
||||
} catch (e: any) {
|
||||
if (e.cause === "UNSUPPORTED") {
|
||||
throw new Error(t("errors.unsupportedFileType"));
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const imagePreview = await resizeImageFile(imageFile, {
|
||||
maxWidthOrHeight: cursorImageSizePx,
|
||||
});
|
||||
|
||||
let previewDataURL = await getDataURL(imagePreview);
|
||||
|
||||
@@ -8731,8 +8644,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
}): void => {
|
||||
const hoveredBindableElement = getHoveredElementForBinding(
|
||||
pointerCoords,
|
||||
this.scene.getNonDeletedElements(),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.scene,
|
||||
);
|
||||
this.setState({
|
||||
suggestedBindings:
|
||||
@@ -8759,8 +8671,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
(acc: NonDeleted<ExcalidrawBindableElement>[], coords) => {
|
||||
const hoveredBindableElement = getHoveredElementForBinding(
|
||||
coords,
|
||||
this.scene.getNonDeletedElements(),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
this.scene,
|
||||
);
|
||||
if (
|
||||
hoveredBindableElement != null &&
|
||||
@@ -8786,11 +8697,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
if (selectedElements.length > 50) {
|
||||
return;
|
||||
}
|
||||
const suggestedBindings = getEligibleElementsForBinding(
|
||||
selectedElements,
|
||||
this.scene.getNonDeletedElements(),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
const suggestedBindings = getEligibleElementsForBinding(selectedElements);
|
||||
this.setState({ suggestedBindings });
|
||||
}
|
||||
|
||||
@@ -8882,9 +8789,8 @@ class App extends React.Component<AppProps, AppState> {
|
||||
});
|
||||
return;
|
||||
} catch (error: any) {
|
||||
// Don't throw for image scene daa
|
||||
if (error.name !== "EncodingError") {
|
||||
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8958,39 +8864,12 @@ class App extends React.Component<AppProps, AppState> {
|
||||
) => {
|
||||
file = await normalizeFile(file);
|
||||
try {
|
||||
let ret;
|
||||
try {
|
||||
ret = await loadSceneOrLibraryFromBlob(
|
||||
file,
|
||||
this.state,
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
fileHandle,
|
||||
);
|
||||
} catch (error: any) {
|
||||
const imageSceneDataError = error instanceof ImageSceneDataError;
|
||||
if (
|
||||
imageSceneDataError &&
|
||||
error.code === "IMAGE_NOT_CONTAINS_SCENE_DATA" &&
|
||||
!this.isToolSupported("image")
|
||||
) {
|
||||
this.setState({
|
||||
isLoading: false,
|
||||
errorMessage: t("errors.imageToolNotSupported"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const errorMessage = imageSceneDataError
|
||||
? t("alerts.cannotRestoreFromImage")
|
||||
: t("alerts.couldNotLoadInvalidFile");
|
||||
this.setState({
|
||||
isLoading: false,
|
||||
errorMessage,
|
||||
});
|
||||
}
|
||||
if (!ret) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ret = await loadSceneOrLibraryFromBlob(
|
||||
file,
|
||||
this.state,
|
||||
this.scene.getElementsIncludingDeleted(),
|
||||
fileHandle,
|
||||
);
|
||||
if (ret.type === MIME_TYPES.excalidraw) {
|
||||
this.setState({ isLoading: true });
|
||||
this.syncActionResult({
|
||||
@@ -9015,6 +8894,17 @@ class App extends React.Component<AppProps, AppState> {
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (
|
||||
error instanceof ImageSceneDataError &&
|
||||
error.code === "IMAGE_NOT_CONTAINS_SCENE_DATA" &&
|
||||
!this.isToolSupported("image")
|
||||
) {
|
||||
this.setState({
|
||||
isLoading: false,
|
||||
errorMessage: t("errors.imageToolNotSupported"),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.setState({ isLoading: false, errorMessage: error.message });
|
||||
}
|
||||
};
|
||||
@@ -9074,7 +8964,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this,
|
||||
),
|
||||
selectedLinearElement: isLinearElement(element)
|
||||
? new LinearElementEditor(element)
|
||||
? new LinearElementEditor(element, this.scene)
|
||||
: null,
|
||||
}
|
||||
: this.state),
|
||||
@@ -9146,7 +9036,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
x: gridX - pointerDownState.originInGrid.x,
|
||||
y: gridY - pointerDownState.originInGrid.y,
|
||||
},
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
|
||||
gridX += snapOffset.x;
|
||||
@@ -9185,7 +9074,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.scene.getNonDeletedElements(),
|
||||
draggingElement as ExcalidrawFrameLikeElement,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -9305,7 +9193,6 @@ class App extends React.Component<AppProps, AppState> {
|
||||
this.scene.getNonDeletedElements(),
|
||||
frame,
|
||||
this.state,
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
).forEach((element) => elementsToHighlight.add(element));
|
||||
});
|
||||
|
||||
@@ -9602,6 +9489,7 @@ class App extends React.Component<AppProps, AppState> {
|
||||
// -----------------------------------------------------------------------------
|
||||
// TEST HOOKS
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
h: {
|
||||
@@ -9614,23 +9502,20 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
export const createTestHook = () => {
|
||||
if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
|
||||
window.h = window.h || ({} as Window["h"]);
|
||||
if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
|
||||
window.h = window.h || ({} as Window["h"]);
|
||||
|
||||
Object.defineProperties(window.h, {
|
||||
elements: {
|
||||
configurable: true,
|
||||
get() {
|
||||
return this.app?.scene.getElementsIncludingDeleted();
|
||||
},
|
||||
set(elements: ExcalidrawElement[]) {
|
||||
return this.app?.scene.replaceAllElements(elements);
|
||||
},
|
||||
Object.defineProperties(window.h, {
|
||||
elements: {
|
||||
configurable: true,
|
||||
get() {
|
||||
return this.app?.scene.getElementsIncludingDeleted();
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
set(elements: ExcalidrawElement[]) {
|
||||
return this.app?.scene.replaceAllElements(elements);
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
createTestHook();
|
||||
export default App;
|
||||
|
||||
@@ -9,7 +9,8 @@ type AvatarProps = {
|
||||
color: string;
|
||||
name: string;
|
||||
src?: string;
|
||||
className?: string;
|
||||
isBeingFollowed?: boolean;
|
||||
isCurrentUser: boolean;
|
||||
};
|
||||
|
||||
export const Avatar = ({
|
||||
@@ -17,14 +18,22 @@ export const Avatar = ({
|
||||
onClick,
|
||||
name,
|
||||
src,
|
||||
className,
|
||||
isBeingFollowed,
|
||||
isCurrentUser,
|
||||
}: AvatarProps) => {
|
||||
const shortName = getNameInitial(name);
|
||||
const [error, setError] = useState(false);
|
||||
const loadImg = !error && src;
|
||||
const style = loadImg ? undefined : { background: color };
|
||||
return (
|
||||
<div className={clsx("Avatar", className)} style={style} onClick={onClick}>
|
||||
<div
|
||||
className={clsx("Avatar", {
|
||||
"Avatar--is-followed": isBeingFollowed,
|
||||
"Avatar--is-current-user": isCurrentUser,
|
||||
})}
|
||||
style={style}
|
||||
onClick={onClick}
|
||||
>
|
||||
{loadImg ? (
|
||||
<img
|
||||
className="Avatar-img"
|
||||
|
||||
@@ -32,9 +32,11 @@ import { Switch } from "./Switch";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
|
||||
import "./ImageExportDialog.scss";
|
||||
import { useAppProps } from "./App";
|
||||
import { FilledButton } from "./FilledButton";
|
||||
import { cloneJSON } from "../utils";
|
||||
import { prepareElementsForExport } from "../data";
|
||||
import { getFileName } from "../data/filename";
|
||||
|
||||
const supportsContextFilters =
|
||||
"filter" in document.createElement("canvas").getContext("2d")!;
|
||||
@@ -57,7 +59,6 @@ type ImageExportModalProps = {
|
||||
files: BinaryFiles;
|
||||
actionManager: ActionManager;
|
||||
onExportImage: AppClassProperties["onExportImage"];
|
||||
name: string;
|
||||
};
|
||||
|
||||
const ImageExportModal = ({
|
||||
@@ -66,14 +67,16 @@ const ImageExportModal = ({
|
||||
files,
|
||||
actionManager,
|
||||
onExportImage,
|
||||
name,
|
||||
}: ImageExportModalProps) => {
|
||||
const hasSelection = isSomeElementSelected(
|
||||
elementsSnapshot,
|
||||
appStateSnapshot,
|
||||
);
|
||||
|
||||
const [projectName, setProjectName] = useState(name);
|
||||
const appProps = useAppProps();
|
||||
const [projectName, setProjectName] = useState(
|
||||
appProps.name || getFileName(),
|
||||
);
|
||||
const [exportSelectionOnly, setExportSelectionOnly] = useState(hasSelection);
|
||||
const [exportWithBackground, setExportWithBackground] = useState(
|
||||
appStateSnapshot.exportBackground,
|
||||
@@ -109,7 +112,6 @@ const ImageExportModal = ({
|
||||
elements: exportedElements,
|
||||
appState: {
|
||||
...appStateSnapshot,
|
||||
name: projectName,
|
||||
exportBackground: exportWithBackground,
|
||||
exportWithDarkMode: exportDarkMode,
|
||||
exportScale,
|
||||
@@ -124,16 +126,9 @@ const ImageExportModal = ({
|
||||
setRenderError(null);
|
||||
// if converting to blob fails, there's some problem that will
|
||||
// likely prevent preview and export (e.g. canvas too big)
|
||||
return canvasToBlob(canvas)
|
||||
.then(() => {
|
||||
previewNode.replaceChildren(canvas);
|
||||
})
|
||||
.catch((e) => {
|
||||
if (e.name === "CANVAS_POSSIBLY_TOO_BIG") {
|
||||
throw new Error(t("canvasError.canvasTooBig"));
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
return canvasToBlob(canvas).then(() => {
|
||||
previewNode.replaceChildren(canvas);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
@@ -165,6 +160,10 @@ const ImageExportModal = ({
|
||||
className="TextInput"
|
||||
value={projectName}
|
||||
style={{ width: "30ch" }}
|
||||
disabled={
|
||||
typeof appProps.name !== "undefined" ||
|
||||
appStateSnapshot.viewModeEnabled
|
||||
}
|
||||
onChange={(event) => {
|
||||
setProjectName(event.target.value);
|
||||
actionManager.executeAction(
|
||||
@@ -350,7 +349,6 @@ export const ImageExportDialog = ({
|
||||
actionManager,
|
||||
onExportImage,
|
||||
onCloseRequest,
|
||||
name,
|
||||
}: {
|
||||
appState: UIAppState;
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
@@ -358,7 +356,6 @@ export const ImageExportDialog = ({
|
||||
actionManager: ActionManager;
|
||||
onExportImage: AppClassProperties["onExportImage"];
|
||||
onCloseRequest: () => void;
|
||||
name: string;
|
||||
}) => {
|
||||
// we need to take a snapshot so that the exported state can't be modified
|
||||
// while the dialog is open
|
||||
@@ -377,7 +374,6 @@ export const ImageExportDialog = ({
|
||||
files={files}
|
||||
actionManager={actionManager}
|
||||
onExportImage={onExportImage}
|
||||
name={name}
|
||||
/>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -19,14 +19,7 @@
|
||||
|
||||
&__top-right {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
pointer-events: none !important;
|
||||
|
||||
& > * {
|
||||
pointer-events: var(--ui-pointerEvents);
|
||||
}
|
||||
}
|
||||
|
||||
&__footer {
|
||||
|
||||
@@ -195,7 +195,6 @@ const LayerUI = ({
|
||||
actionManager={actionManager}
|
||||
onExportImage={onExportImage}
|
||||
onCloseRequest={() => setAppState({ openDialog: null })}
|
||||
name={app.getName()}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -6,19 +6,27 @@ import { focusNearestParent } from "../utils";
|
||||
import "./ProjectName.scss";
|
||||
import { useExcalidrawContainer } from "./App";
|
||||
import { KEYS } from "../keys";
|
||||
import { EditorLocalStorage } from "../data/EditorLocalStorage";
|
||||
import { EDITOR_LS_KEYS } from "../constants";
|
||||
import { getFileName } from "../data/filename";
|
||||
|
||||
type Props = {
|
||||
value: string;
|
||||
value?: string;
|
||||
onChange: (value: string) => void;
|
||||
label: string;
|
||||
isNameEditable: boolean;
|
||||
ignoreFocus?: boolean;
|
||||
};
|
||||
|
||||
export const ProjectName = (props: Props) => {
|
||||
const { id } = useExcalidrawContainer();
|
||||
const [fileName, setFileName] = useState<string>(props.value);
|
||||
const [fileName, setFileName] = useState<string>(
|
||||
props.value || getFileName(),
|
||||
);
|
||||
|
||||
const handleBlur = (event: any) => {
|
||||
EditorLocalStorage.set(EDITOR_LS_KEYS.EXCALIDRAW_FILE_NAME, fileName);
|
||||
|
||||
if (!props.ignoreFocus) {
|
||||
focusNearestParent(event.target);
|
||||
}
|
||||
@@ -41,17 +49,23 @@ export const ProjectName = (props: Props) => {
|
||||
return (
|
||||
<div className="ProjectName">
|
||||
<label className="ProjectName-label" htmlFor="filename">
|
||||
{`${props.label}:`}
|
||||
{`${props.label}${props.isNameEditable ? "" : ":"}`}
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="TextInput"
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
id={`${id}-filename`}
|
||||
value={fileName}
|
||||
onChange={(event) => setFileName(event.target.value)}
|
||||
/>
|
||||
{props.isNameEditable ? (
|
||||
<input
|
||||
type="text"
|
||||
className="TextInput"
|
||||
onBlur={handleBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
id={`${id}-filename`}
|
||||
value={fileName}
|
||||
onChange={(event) => setFileName(event.target.value)}
|
||||
/>
|
||||
) : (
|
||||
<span className="TextInput TextInput--readonly" id={`${id}-filename`}>
|
||||
{props.value}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -31,18 +31,19 @@ export const ShareableLinkDialog = ({
|
||||
const copyRoomLink = async () => {
|
||||
try {
|
||||
await copyTextToSystemClipboard(link);
|
||||
} catch (e) {
|
||||
setErrorMessage(t("errors.copyToSystemClipboardFailed"));
|
||||
}
|
||||
setJustCopied(true);
|
||||
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
setJustCopied(true);
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
if (timerRef.current) {
|
||||
window.clearTimeout(timerRef.current);
|
||||
}
|
||||
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
setJustCopied(false);
|
||||
}, 3000);
|
||||
} catch (error: any) {
|
||||
setErrorMessage(error.message);
|
||||
}
|
||||
|
||||
ref.current?.select();
|
||||
};
|
||||
|
||||
@@ -10,7 +10,6 @@ import { NonDeletedExcalidrawElement } from "../../element/types";
|
||||
import { AppClassProperties, BinaryFiles } from "../../types";
|
||||
import { canvasToBlob } from "../../data/blob";
|
||||
import { EditorLocalStorage } from "../../data/EditorLocalStorage";
|
||||
import { t } from "../../i18n";
|
||||
|
||||
const resetPreview = ({
|
||||
canvasRef,
|
||||
@@ -109,14 +108,7 @@ export const convertMermaidToExcalidraw = async ({
|
||||
});
|
||||
// if converting to blob fails, there's some problem that will
|
||||
// likely prevent preview and export (e.g. canvas too big)
|
||||
try {
|
||||
await canvasToBlob(canvas);
|
||||
} catch (e: any) {
|
||||
if (e.name === "CANVAS_POSSIBLY_TOO_BIG") {
|
||||
throw new Error(t("canvasError.canvasTooBig"));
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
await canvasToBlob(canvas);
|
||||
parent.style.background = "var(--default-bg-color)";
|
||||
canvasNode.replaceChildren(canvas);
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CSSProperties, useCallback, useEffect, useRef } from "react";
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { CloseIcon } from "./icons";
|
||||
import "./Toast.scss";
|
||||
import { ToolButton } from "./ToolButton";
|
||||
@@ -11,13 +11,11 @@ export const Toast = ({
|
||||
closable = false,
|
||||
// To prevent autoclose, pass duration as Infinity
|
||||
duration = DEFAULT_TOAST_TIMEOUT,
|
||||
style,
|
||||
}: {
|
||||
message: string;
|
||||
onClose: () => void;
|
||||
closable?: boolean;
|
||||
duration?: number;
|
||||
style?: CSSProperties;
|
||||
}) => {
|
||||
const timerRef = useRef<number>(0);
|
||||
const shouldAutoClose = duration !== Infinity;
|
||||
@@ -45,7 +43,6 @@ export const Toast = ({
|
||||
className="Toast"
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
style={style}
|
||||
>
|
||||
<p className="Toast__message">{message}</p>
|
||||
{closable && (
|
||||
|
||||
@@ -1,25 +1,16 @@
|
||||
@import "../css/variables.module";
|
||||
|
||||
.excalidraw {
|
||||
--avatar-size: 1.75rem;
|
||||
--avatarList-gap: 0.625rem;
|
||||
--userList-padding: var(--space-factor);
|
||||
|
||||
.UserList-wrapper {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: flex-end;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.UserList {
|
||||
pointer-events: none;
|
||||
padding: var(--userList-padding);
|
||||
/*github corner*/
|
||||
padding: var(--space-factor) var(--space-factor) var(--space-factor)
|
||||
var(--space-factor);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: var(--avatarList-gap);
|
||||
gap: 0.625rem;
|
||||
|
||||
&:empty {
|
||||
display: none;
|
||||
@@ -27,16 +18,15 @@
|
||||
|
||||
box-sizing: border-box;
|
||||
|
||||
--max-size: calc(
|
||||
var(--avatar-size) * var(--max-avatars, 2) + var(--avatarList-gap) *
|
||||
(var(--max-avatars, 2) - 1) + var(--userList-padding) * 2
|
||||
);
|
||||
// can fit max 4 avatars (3 avatars + show more) in a column
|
||||
max-height: 120px;
|
||||
|
||||
// max width & height set to fix the max-avatars
|
||||
max-height: var(--max-size);
|
||||
max-width: var(--max-size);
|
||||
// can fit max 4 avatars (3 avatars + show more) when there's enough space
|
||||
max-width: 120px;
|
||||
|
||||
// Tweak in 30px increments to fit more/fewer avatars in a row/column ^^
|
||||
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.UserList > * {
|
||||
@@ -55,11 +45,10 @@
|
||||
@include avatarStyles;
|
||||
background-color: var(--color-gray-20);
|
||||
border: 0 !important;
|
||||
font-size: 0.625rem;
|
||||
font-size: 0.5rem;
|
||||
font-weight: 400;
|
||||
flex-shrink: 0;
|
||||
color: var(--color-gray-100);
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.UserList__collaborator-name {
|
||||
@@ -68,80 +57,11 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.UserList__collaborator--avatar-only {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
.UserList__collaborator-status-icon {
|
||||
--size: 14px;
|
||||
position: absolute;
|
||||
display: flex;
|
||||
flex: 0 0 auto;
|
||||
bottom: -0.25rem;
|
||||
right: -0.25rem;
|
||||
width: var(--size);
|
||||
height: var(--size);
|
||||
svg {
|
||||
flex: 0 0 auto;
|
||||
width: var(--size);
|
||||
height: var(--size);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.UserList__collaborator-status-icons {
|
||||
.UserList__collaborator-follow-status-icon {
|
||||
margin-left: auto;
|
||||
flex: 0 0 auto;
|
||||
min-width: 2.25rem;
|
||||
gap: 0.25rem;
|
||||
justify-content: flex-end;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.UserList__collaborator.is-muted
|
||||
.UserList__collaborator-status-icon-microphone-muted {
|
||||
color: var(--color-danger);
|
||||
filter: drop-shadow(0px 0px 0px rgba(0, 0, 0, 0.5));
|
||||
}
|
||||
|
||||
.UserList__collaborator-status-icon-speaking-indicator {
|
||||
display: flex;
|
||||
flex-flow: row nowrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 1rem;
|
||||
padding: 0 3px;
|
||||
box-sizing: border-box;
|
||||
|
||||
div {
|
||||
width: 0.125rem;
|
||||
height: 0.4rem;
|
||||
// keep this in sync with constants.ts
|
||||
background-color: #a2f1a6;
|
||||
}
|
||||
|
||||
div:nth-of-type(1) {
|
||||
animation: speaking-indicator-anim 1s -0.45s ease-in-out infinite;
|
||||
}
|
||||
|
||||
div:nth-of-type(2) {
|
||||
animation: speaking-indicator-anim 1s -0.9s ease-in-out infinite;
|
||||
}
|
||||
|
||||
div:nth-of-type(3) {
|
||||
animation: speaking-indicator-anim 1s -0.15s ease-in-out infinite;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes speaking-indicator-anim {
|
||||
0%,
|
||||
100% {
|
||||
transform: scaleY(1);
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: scaleY(2);
|
||||
}
|
||||
display: flex;
|
||||
}
|
||||
|
||||
--userlist-hint-bg-color: var(--color-gray-10);
|
||||
@@ -160,7 +80,7 @@
|
||||
position: static;
|
||||
top: auto;
|
||||
margin-top: 0;
|
||||
max-height: 50vh;
|
||||
max-height: 12rem;
|
||||
overflow-y: auto;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-top: 1px solid var(--userlist-collaborators-border-color);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import "./UserList.scss";
|
||||
|
||||
import React, { useLayoutEffect } from "react";
|
||||
import React from "react";
|
||||
import clsx from "clsx";
|
||||
import { Collaborator, SocketId } from "../types";
|
||||
import { Tooltip } from "./Tooltip";
|
||||
@@ -12,11 +12,9 @@ import { Island } from "./Island";
|
||||
import { searchIcon } from "./icons";
|
||||
import { t } from "../i18n";
|
||||
import { isShallowEqual } from "../utils";
|
||||
import { supportsResizeObserver } from "../constants";
|
||||
import { MarkRequired } from "../utility-types";
|
||||
|
||||
export type GoToCollaboratorComponentProps = {
|
||||
socketId: SocketId;
|
||||
clientId: ClientId;
|
||||
collaborator: Collaborator;
|
||||
withName: boolean;
|
||||
isBeingFollowed: boolean;
|
||||
@@ -25,41 +23,45 @@ export type GoToCollaboratorComponentProps = {
|
||||
/** collaborator user id or socket id (fallback) */
|
||||
type ClientId = string & { _brand: "UserId" };
|
||||
|
||||
const DEFAULT_MAX_AVATARS = 4;
|
||||
const FIRST_N_AVATARS = 3;
|
||||
const SHOW_COLLABORATORS_FILTER_AT = 8;
|
||||
|
||||
const ConditionalTooltipWrapper = ({
|
||||
shouldWrap,
|
||||
children,
|
||||
clientId,
|
||||
username,
|
||||
}: {
|
||||
shouldWrap: boolean;
|
||||
children: React.ReactNode;
|
||||
username?: string | null;
|
||||
clientId: ClientId;
|
||||
}) =>
|
||||
shouldWrap ? (
|
||||
<Tooltip label={username || "Unknown user"}>{children}</Tooltip>
|
||||
<Tooltip label={username || "Unknown user"} key={clientId}>
|
||||
{children}
|
||||
</Tooltip>
|
||||
) : (
|
||||
<React.Fragment>{children}</React.Fragment>
|
||||
<React.Fragment key={clientId}>{children}</React.Fragment>
|
||||
);
|
||||
|
||||
const renderCollaborator = ({
|
||||
actionManager,
|
||||
collaborator,
|
||||
socketId,
|
||||
clientId,
|
||||
withName = false,
|
||||
shouldWrapWithTooltip = false,
|
||||
isBeingFollowed,
|
||||
}: {
|
||||
actionManager: ActionManager;
|
||||
collaborator: Collaborator;
|
||||
socketId: SocketId;
|
||||
clientId: ClientId;
|
||||
withName?: boolean;
|
||||
shouldWrapWithTooltip?: boolean;
|
||||
isBeingFollowed: boolean;
|
||||
}) => {
|
||||
const data: GoToCollaboratorComponentProps = {
|
||||
socketId,
|
||||
clientId,
|
||||
collaborator,
|
||||
withName,
|
||||
isBeingFollowed,
|
||||
@@ -68,7 +70,8 @@ const renderCollaborator = ({
|
||||
|
||||
return (
|
||||
<ConditionalTooltipWrapper
|
||||
key={socketId}
|
||||
key={clientId}
|
||||
clientId={clientId}
|
||||
username={collaborator.username}
|
||||
shouldWrap={shouldWrapWithTooltip}
|
||||
>
|
||||
@@ -79,13 +82,7 @@ const renderCollaborator = ({
|
||||
|
||||
type UserListUserObject = Pick<
|
||||
Collaborator,
|
||||
| "avatarUrl"
|
||||
| "id"
|
||||
| "socketId"
|
||||
| "username"
|
||||
| "isInCall"
|
||||
| "isSpeaking"
|
||||
| "isMuted"
|
||||
"avatarUrl" | "id" | "socketId" | "username"
|
||||
>;
|
||||
|
||||
type UserListProps = {
|
||||
@@ -100,19 +97,13 @@ const collaboratorComparatorKeys = [
|
||||
"id",
|
||||
"socketId",
|
||||
"username",
|
||||
"isInCall",
|
||||
"isSpeaking",
|
||||
"isMuted",
|
||||
] as const;
|
||||
|
||||
export const UserList = React.memo(
|
||||
({ className, mobile, collaborators, userToFollow }: UserListProps) => {
|
||||
const actionManager = useExcalidrawActionManager();
|
||||
|
||||
const uniqueCollaboratorsMap = new Map<
|
||||
ClientId,
|
||||
MarkRequired<Collaborator, "socketId">
|
||||
>();
|
||||
const uniqueCollaboratorsMap = new Map<ClientId, Collaborator>();
|
||||
|
||||
collaborators.forEach((collaborator, socketId) => {
|
||||
const userId = (collaborator.id || socketId) as ClientId;
|
||||
@@ -123,147 +114,115 @@ export const UserList = React.memo(
|
||||
);
|
||||
});
|
||||
|
||||
const uniqueCollaboratorsArray = Array.from(
|
||||
uniqueCollaboratorsMap.values(),
|
||||
).filter((collaborator) => collaborator.username?.trim());
|
||||
const uniqueCollaboratorsArray = Array.from(uniqueCollaboratorsMap).filter(
|
||||
([_, collaborator]) => collaborator.username?.trim(),
|
||||
);
|
||||
|
||||
const [searchTerm, setSearchTerm] = React.useState("");
|
||||
|
||||
const userListWrapper = React.useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (userListWrapper.current) {
|
||||
const updateMaxAvatars = (width: number) => {
|
||||
const maxAvatars = Math.max(1, Math.min(8, Math.floor(width / 38)));
|
||||
setMaxAvatars(maxAvatars);
|
||||
};
|
||||
|
||||
updateMaxAvatars(userListWrapper.current.clientWidth);
|
||||
|
||||
if (!supportsResizeObserver) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resizeObserver = new ResizeObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
const { width } = entry.contentRect;
|
||||
updateMaxAvatars(width);
|
||||
}
|
||||
});
|
||||
|
||||
resizeObserver.observe(userListWrapper.current);
|
||||
|
||||
return () => {
|
||||
resizeObserver.disconnect();
|
||||
};
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [maxAvatars, setMaxAvatars] = React.useState(DEFAULT_MAX_AVATARS);
|
||||
if (uniqueCollaboratorsArray.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const searchTermNormalized = searchTerm.trim().toLowerCase();
|
||||
|
||||
const filteredCollaborators = searchTermNormalized
|
||||
? uniqueCollaboratorsArray.filter((collaborator) =>
|
||||
? uniqueCollaboratorsArray.filter(([, collaborator]) =>
|
||||
collaborator.username?.toLowerCase().includes(searchTerm),
|
||||
)
|
||||
: uniqueCollaboratorsArray;
|
||||
|
||||
const firstNCollaborators = uniqueCollaboratorsArray.slice(
|
||||
0,
|
||||
maxAvatars - 1,
|
||||
FIRST_N_AVATARS,
|
||||
);
|
||||
|
||||
const firstNAvatarsJSX = firstNCollaborators.map((collaborator) =>
|
||||
renderCollaborator({
|
||||
actionManager,
|
||||
collaborator,
|
||||
socketId: collaborator.socketId,
|
||||
shouldWrapWithTooltip: true,
|
||||
isBeingFollowed: collaborator.socketId === userToFollow,
|
||||
}),
|
||||
const firstNAvatarsJSX = firstNCollaborators.map(
|
||||
([clientId, collaborator]) =>
|
||||
renderCollaborator({
|
||||
actionManager,
|
||||
collaborator,
|
||||
clientId,
|
||||
shouldWrapWithTooltip: true,
|
||||
isBeingFollowed: collaborator.socketId === userToFollow,
|
||||
}),
|
||||
);
|
||||
|
||||
return mobile ? (
|
||||
<div className={clsx("UserList UserList_mobile", className)}>
|
||||
{uniqueCollaboratorsArray.map((collaborator) =>
|
||||
{uniqueCollaboratorsArray.map(([clientId, collaborator]) =>
|
||||
renderCollaborator({
|
||||
actionManager,
|
||||
collaborator,
|
||||
socketId: collaborator.socketId,
|
||||
clientId,
|
||||
shouldWrapWithTooltip: true,
|
||||
isBeingFollowed: collaborator.socketId === userToFollow,
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="UserList-wrapper" ref={userListWrapper}>
|
||||
<div
|
||||
className={clsx("UserList", className)}
|
||||
style={{ [`--max-avatars` as any]: maxAvatars }}
|
||||
>
|
||||
{firstNAvatarsJSX}
|
||||
<div className={clsx("UserList", className)}>
|
||||
{firstNAvatarsJSX}
|
||||
|
||||
{uniqueCollaboratorsArray.length > maxAvatars - 1 && (
|
||||
<Popover.Root
|
||||
onOpenChange={(isOpen) => {
|
||||
if (!isOpen) {
|
||||
setSearchTerm("");
|
||||
}
|
||||
{uniqueCollaboratorsArray.length > FIRST_N_AVATARS && (
|
||||
<Popover.Root
|
||||
onOpenChange={(isOpen) => {
|
||||
if (!isOpen) {
|
||||
setSearchTerm("");
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Popover.Trigger className="UserList__more">
|
||||
+{uniqueCollaboratorsArray.length - FIRST_N_AVATARS}
|
||||
</Popover.Trigger>
|
||||
<Popover.Content
|
||||
style={{
|
||||
zIndex: 2,
|
||||
width: "13rem",
|
||||
textAlign: "left",
|
||||
}}
|
||||
align="end"
|
||||
sideOffset={10}
|
||||
>
|
||||
<Popover.Trigger className="UserList__more">
|
||||
+{uniqueCollaboratorsArray.length - maxAvatars + 1}
|
||||
</Popover.Trigger>
|
||||
<Popover.Content
|
||||
style={{
|
||||
zIndex: 2,
|
||||
width: "15rem",
|
||||
textAlign: "left",
|
||||
}}
|
||||
align="end"
|
||||
sideOffset={10}
|
||||
>
|
||||
<Island style={{ overflow: "hidden" }}>
|
||||
{uniqueCollaboratorsArray.length >=
|
||||
SHOW_COLLABORATORS_FILTER_AT && (
|
||||
<div className="UserList__search-wrapper">
|
||||
{searchIcon}
|
||||
<input
|
||||
className="UserList__search"
|
||||
type="text"
|
||||
placeholder={t("userList.search.placeholder")}
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<Island style={{ overflow: "hidden" }}>
|
||||
{uniqueCollaboratorsArray.length >=
|
||||
SHOW_COLLABORATORS_FILTER_AT && (
|
||||
<div className="UserList__search-wrapper">
|
||||
{searchIcon}
|
||||
<input
|
||||
className="UserList__search"
|
||||
type="text"
|
||||
placeholder={t("userList.search.placeholder")}
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="dropdown-menu UserList__collaborators">
|
||||
{filteredCollaborators.length === 0 && (
|
||||
<div className="UserList__collaborators__empty">
|
||||
{t("userList.search.empty")}
|
||||
</div>
|
||||
)}
|
||||
<div className="dropdown-menu UserList__collaborators">
|
||||
{filteredCollaborators.length === 0 && (
|
||||
<div className="UserList__collaborators__empty">
|
||||
{t("userList.search.empty")}
|
||||
</div>
|
||||
)}
|
||||
<div className="UserList__hint">
|
||||
{t("userList.hint.text")}
|
||||
</div>
|
||||
{filteredCollaborators.map((collaborator) =>
|
||||
renderCollaborator({
|
||||
actionManager,
|
||||
collaborator,
|
||||
socketId: collaborator.socketId,
|
||||
withName: true,
|
||||
isBeingFollowed: collaborator.socketId === userToFollow,
|
||||
}),
|
||||
)}
|
||||
<div className="UserList__hint">
|
||||
{t("userList.hint.text")}
|
||||
</div>
|
||||
</Island>
|
||||
</Popover.Content>
|
||||
</Popover.Root>
|
||||
)}
|
||||
</div>
|
||||
{filteredCollaborators.map(([clientId, collaborator]) =>
|
||||
renderCollaborator({
|
||||
actionManager,
|
||||
collaborator,
|
||||
clientId,
|
||||
withName: true,
|
||||
isBeingFollowed: collaborator.socketId === userToFollow,
|
||||
}),
|
||||
)}
|
||||
</div>
|
||||
</Island>
|
||||
</Popover.Content>
|
||||
</Popover.Root>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
@@ -277,15 +236,10 @@ export const UserList = React.memo(
|
||||
return false;
|
||||
}
|
||||
|
||||
const nextCollaboratorSocketIds = next.collaborators.keys();
|
||||
|
||||
for (const [socketId, collaborator] of prev.collaborators) {
|
||||
const nextCollaborator = next.collaborators.get(socketId);
|
||||
if (
|
||||
!nextCollaborator ||
|
||||
// this checks order of collaborators in the map is the same
|
||||
// as previous render
|
||||
socketId !== nextCollaboratorSocketIds.next().value ||
|
||||
!isShallowEqual(
|
||||
collaborator,
|
||||
nextCollaborator,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { renderInteractiveScene } from "../../renderer/renderScene";
|
||||
import { isShallowEqual, sceneCoordsToViewportCoords } from "../../utils";
|
||||
import { CURSOR_TYPE } from "../../constants";
|
||||
import { t } from "../../i18n";
|
||||
@@ -11,7 +12,6 @@ import type {
|
||||
} from "../../scene/types";
|
||||
import type { NonDeletedExcalidrawElement } from "../../element/types";
|
||||
import { isRenderThrottlingEnabled } from "../../reactUtils";
|
||||
import { renderInteractiveScene } from "../../renderer/interactiveScene";
|
||||
|
||||
type InteractiveCanvasProps = {
|
||||
containerRef: React.RefObject<HTMLDivElement>;
|
||||
@@ -66,46 +66,42 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const remotePointerButton: InteractiveCanvasRenderConfig["remotePointerButton"] =
|
||||
new Map();
|
||||
const remotePointerViewportCoords: InteractiveCanvasRenderConfig["remotePointerViewportCoords"] =
|
||||
new Map();
|
||||
const cursorButton: {
|
||||
[id: string]: string | undefined;
|
||||
} = {};
|
||||
const pointerViewportCoords: InteractiveCanvasRenderConfig["remotePointerViewportCoords"] =
|
||||
{};
|
||||
const remoteSelectedElementIds: InteractiveCanvasRenderConfig["remoteSelectedElementIds"] =
|
||||
new Map();
|
||||
const remotePointerUsernames: InteractiveCanvasRenderConfig["remotePointerUsernames"] =
|
||||
new Map();
|
||||
const remotePointerUserStates: InteractiveCanvasRenderConfig["remotePointerUserStates"] =
|
||||
new Map();
|
||||
{};
|
||||
const pointerUsernames: { [id: string]: string } = {};
|
||||
const pointerUserStates: { [id: string]: string } = {};
|
||||
|
||||
props.appState.collaborators.forEach((user, socketId) => {
|
||||
if (user.selectedElementIds) {
|
||||
for (const id of Object.keys(user.selectedElementIds)) {
|
||||
if (!remoteSelectedElementIds.has(id)) {
|
||||
remoteSelectedElementIds.set(id, []);
|
||||
if (!(id in remoteSelectedElementIds)) {
|
||||
remoteSelectedElementIds[id] = [];
|
||||
}
|
||||
remoteSelectedElementIds.get(id)!.push(socketId);
|
||||
remoteSelectedElementIds[id].push(socketId);
|
||||
}
|
||||
}
|
||||
if (!user.pointer || user.pointer.renderCursor === false) {
|
||||
if (!user.pointer) {
|
||||
return;
|
||||
}
|
||||
if (user.username) {
|
||||
remotePointerUsernames.set(socketId, user.username);
|
||||
pointerUsernames[socketId] = user.username;
|
||||
}
|
||||
if (user.userState) {
|
||||
remotePointerUserStates.set(socketId, user.userState);
|
||||
pointerUserStates[socketId] = user.userState;
|
||||
}
|
||||
remotePointerViewportCoords.set(
|
||||
socketId,
|
||||
sceneCoordsToViewportCoords(
|
||||
{
|
||||
sceneX: user.pointer.x,
|
||||
sceneY: user.pointer.y,
|
||||
},
|
||||
props.appState,
|
||||
),
|
||||
pointerViewportCoords[socketId] = sceneCoordsToViewportCoords(
|
||||
{
|
||||
sceneX: user.pointer.x,
|
||||
sceneY: user.pointer.y,
|
||||
},
|
||||
props.appState,
|
||||
);
|
||||
remotePointerButton.set(socketId, user.button);
|
||||
cursorButton[socketId] = user.button;
|
||||
});
|
||||
|
||||
const selectionColor =
|
||||
@@ -124,11 +120,11 @@ const InteractiveCanvas = (props: InteractiveCanvasProps) => {
|
||||
scale: window.devicePixelRatio,
|
||||
appState: props.appState,
|
||||
renderConfig: {
|
||||
remotePointerViewportCoords,
|
||||
remotePointerButton,
|
||||
remotePointerViewportCoords: pointerViewportCoords,
|
||||
remotePointerButton: cursorButton,
|
||||
remoteSelectedElementIds,
|
||||
remotePointerUsernames,
|
||||
remotePointerUserStates,
|
||||
remotePointerUsernames: pointerUsernames,
|
||||
remotePointerUserStates: pointerUserStates,
|
||||
selectionColor,
|
||||
renderScrollbars: false,
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import { renderStaticScene } from "../../renderer/staticScene";
|
||||
import { renderStaticScene } from "../../renderer/renderScene";
|
||||
import { isShallowEqual } from "../../utils";
|
||||
import type { AppState, StaticCanvasAppState } from "../../types";
|
||||
import type {
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { Excalidraw } from "../../index";
|
||||
import { KEYS } from "../../keys";
|
||||
import { Keyboard } from "../../tests/helpers/ui";
|
||||
import { render, waitFor, getByTestId } from "../../tests/test-utils";
|
||||
|
||||
describe("Test <DropdownMenu/>", () => {
|
||||
it("should", async () => {
|
||||
const { container } = await render(<Excalidraw />);
|
||||
|
||||
expect(window.h.state.openMenu).toBe(null);
|
||||
|
||||
getByTestId(container, "main-menu-trigger").click();
|
||||
expect(window.h.state.openMenu).toBe("canvas");
|
||||
|
||||
await waitFor(() => {
|
||||
Keyboard.keyDown(KEYS.ESCAPE);
|
||||
expect(window.h.state.openMenu).toBe(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,9 @@ import { Island } from "../Island";
|
||||
import { useDevice } from "../App";
|
||||
import clsx from "clsx";
|
||||
import Stack from "../Stack";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import React, { useRef } from "react";
|
||||
import { DropdownMenuContentPropsContext } from "./common";
|
||||
import { useOutsideClick } from "../../hooks/useOutsideClick";
|
||||
import { KEYS } from "../../keys";
|
||||
import { EVENT } from "../../constants";
|
||||
import { useStable } from "../../hooks/useStable";
|
||||
|
||||
const MenuContent = ({
|
||||
children,
|
||||
@@ -28,30 +25,10 @@ const MenuContent = ({
|
||||
const device = useDevice();
|
||||
const menuRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const callbacksRef = useStable({ onClickOutside });
|
||||
|
||||
useOutsideClick(menuRef, () => {
|
||||
callbacksRef.onClickOutside?.();
|
||||
onClickOutside?.();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === KEYS.ESCAPE) {
|
||||
event.stopImmediatePropagation();
|
||||
callbacksRef.onClickOutside?.();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener(EVENT.KEYDOWN, onKeyDown, {
|
||||
// so that we can stop propagation of the event before it reaches
|
||||
// event handlers that were bound before this one
|
||||
capture: true,
|
||||
});
|
||||
return () => {
|
||||
document.removeEventListener(EVENT.KEYDOWN, onKeyDown);
|
||||
};
|
||||
}, [callbacksRef]);
|
||||
|
||||
const classNames = clsx(`dropdown-menu ${className}`, {
|
||||
"dropdown-menu--mobile": device.editor.isMobile,
|
||||
}).trim();
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
import { MIME_TYPES } from "../../constants";
|
||||
import { Bounds, getElementAbsoluteCoords } from "../../element/bounds";
|
||||
import { isPointHittingElementBoundingBox } from "../../element/collision";
|
||||
import { ElementsMap, NonDeletedExcalidrawElement } from "../../element/types";
|
||||
import { rotate } from "../../math";
|
||||
import { DEFAULT_LINK_SIZE } from "../../renderer/renderElement";
|
||||
import { AppState, Point, UIAppState } from "../../types";
|
||||
|
||||
export const EXTERNAL_LINK_IMG = document.createElement("img");
|
||||
EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-external-link"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
|
||||
)}`;
|
||||
|
||||
export const getLinkHandleFromCoords = (
|
||||
[x1, y1, x2, y2]: Bounds,
|
||||
angle: number,
|
||||
appState: Pick<UIAppState, "zoom">,
|
||||
): Bounds => {
|
||||
const size = DEFAULT_LINK_SIZE;
|
||||
const linkWidth = size / appState.zoom.value;
|
||||
const linkHeight = size / appState.zoom.value;
|
||||
const linkMarginY = size / appState.zoom.value;
|
||||
const centerX = (x1 + x2) / 2;
|
||||
const centerY = (y1 + y2) / 2;
|
||||
const centeringOffset = (size - 8) / (2 * appState.zoom.value);
|
||||
const dashedLineMargin = 4 / appState.zoom.value;
|
||||
|
||||
// Same as `ne` resize handle
|
||||
const x = x2 + dashedLineMargin - centeringOffset;
|
||||
const y = y1 - dashedLineMargin - linkMarginY + centeringOffset;
|
||||
|
||||
const [rotatedX, rotatedY] = rotate(
|
||||
x + linkWidth / 2,
|
||||
y + linkHeight / 2,
|
||||
centerX,
|
||||
centerY,
|
||||
angle,
|
||||
);
|
||||
return [
|
||||
rotatedX - linkWidth / 2,
|
||||
rotatedY - linkHeight / 2,
|
||||
linkWidth,
|
||||
linkHeight,
|
||||
];
|
||||
};
|
||||
|
||||
export const isPointHittingLinkIcon = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
appState: AppState,
|
||||
[x, y]: Point,
|
||||
) => {
|
||||
const threshold = 4 / appState.zoom.value;
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
|
||||
[x1, y1, x2, y2],
|
||||
element.angle,
|
||||
appState,
|
||||
);
|
||||
const hitLink =
|
||||
x > linkX - threshold &&
|
||||
x < linkX + threshold + linkWidth &&
|
||||
y > linkY - threshold &&
|
||||
y < linkY + linkHeight + threshold;
|
||||
return hitLink;
|
||||
};
|
||||
|
||||
export const isPointHittingLink = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
appState: AppState,
|
||||
[x, y]: Point,
|
||||
isMobile: boolean,
|
||||
) => {
|
||||
if (!element.link || appState.selectedElementIds[element.id]) {
|
||||
return false;
|
||||
}
|
||||
const threshold = 4 / appState.zoom.value;
|
||||
if (
|
||||
!isMobile &&
|
||||
appState.viewModeEnabled &&
|
||||
isPointHittingElementBoundingBox(
|
||||
element,
|
||||
elementsMap,
|
||||
[x, y],
|
||||
threshold,
|
||||
null,
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return isPointHittingLinkIcon(element, elementsMap, appState, [x, y]);
|
||||
};
|
||||
@@ -604,10 +604,6 @@ export const share = createIcon(
|
||||
modifiedTablerIconProps,
|
||||
);
|
||||
|
||||
export const warning = createIcon(
|
||||
"M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z",
|
||||
);
|
||||
|
||||
export const shareIOS = createIcon(
|
||||
"M16 5l-1.42 1.42-1.59-1.59V16h-1.98V4.83L9.42 6.42 8 5l4-4 4 4zm4 5v11c0 1.1-.9 2-2 2H6c-1.11 0-2-.9-2-2V10c0-1.11.89-2 2-2h3v2H6v11h12V10h-3V8h3c1.1 0 2 .89 2 2z",
|
||||
{ width: 24, height: 24 },
|
||||
@@ -1798,7 +1794,7 @@ export const fullscreenIcon = createIcon(
|
||||
);
|
||||
|
||||
export const eyeIcon = createIcon(
|
||||
<g stroke="currentColor" fill="none" strokeWidth={1.5}>
|
||||
<g stroke="currentColor" fill="none">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0" />
|
||||
<path d="M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6" />
|
||||
@@ -1837,26 +1833,3 @@ export const searchIcon = createIcon(
|
||||
</g>,
|
||||
tablerIconProps,
|
||||
);
|
||||
|
||||
export const microphoneIcon = createIcon(
|
||||
<g strokeWidth={1.5}>
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z" />
|
||||
<path d="M5 10a7 7 0 0 0 14 0" />
|
||||
<path d="M8 21l8 0" />
|
||||
<path d="M12 17l0 4" />
|
||||
</g>,
|
||||
tablerIconProps,
|
||||
);
|
||||
|
||||
export const microphoneMutedIcon = createIcon(
|
||||
<g strokeWidth={1.5}>
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
|
||||
<path d="M3 3l18 18" />
|
||||
<path d="M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1" />
|
||||
<path d="M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85" />
|
||||
<path d="M8 21l8 0" />
|
||||
<path d="M12 17l0 4" />
|
||||
</g>,
|
||||
tablerIconProps,
|
||||
);
|
||||
|
||||
@@ -20,9 +20,6 @@ export const isIOS =
|
||||
export const isBrave = () =>
|
||||
(navigator as any).brave?.isBrave?.name === "isBrave";
|
||||
|
||||
export const supportsResizeObserver =
|
||||
typeof window !== "undefined" && "ResizeObserver" in window;
|
||||
|
||||
export const APP_NAME = "Excalidraw";
|
||||
|
||||
export const DRAGGING_THRESHOLD = 10; // px
|
||||
@@ -31,7 +28,6 @@ export const ELEMENT_SHIFT_TRANSLATE_AMOUNT = 5;
|
||||
export const ELEMENT_TRANSLATE_AMOUNT = 1;
|
||||
export const TEXT_TO_CENTER_SNAP_THRESHOLD = 30;
|
||||
export const SHIFT_LOCKING_ANGLE = Math.PI / 12;
|
||||
export const DEFAULT_LASER_COLOR = "red";
|
||||
export const CURSOR_TYPE = {
|
||||
TEXT: "text",
|
||||
CROSSHAIR: "crosshair",
|
||||
@@ -148,11 +144,6 @@ export const DEFAULT_VERTICAL_ALIGN = "top";
|
||||
export const DEFAULT_VERSION = "{version}";
|
||||
export const DEFAULT_TRANSFORM_HANDLE_SPACING = 2;
|
||||
|
||||
export const COLOR_WHITE = "#ffffff";
|
||||
export const COLOR_CHARCOAL_BLACK = "#1e1e1e";
|
||||
// keep this in sync with CSS
|
||||
export const COLOR_VOICE_CALL = "#a2f1a6";
|
||||
|
||||
export const CANVAS_ONLY_ACTIONS = ["selectAll"];
|
||||
|
||||
export const GRID_SIZE = 20; // TODO make it configurable?
|
||||
@@ -389,10 +380,5 @@ export const EDITOR_LS_KEYS = {
|
||||
// legacy naming (non)scheme
|
||||
MERMAID_TO_EXCALIDRAW: "mermaid-to-excalidraw",
|
||||
PUBLISH_LIBRARY: "publish-library-data",
|
||||
EXCALIDRAW_FILE_NAME: "excalidraw-file-name",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* not translated as this is used only in public, stateless API as default value
|
||||
* where filename is optional and we can't retrieve name from app state
|
||||
*/
|
||||
export const DEFAULT_FILENAME = "Untitled";
|
||||
|
||||
@@ -116,8 +116,8 @@
|
||||
}
|
||||
|
||||
@mixin avatarStyles {
|
||||
width: var(--avatar-size, 1.5rem);
|
||||
height: var(--avatar-size, 1.5rem);
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
position: relative;
|
||||
border-radius: 100%;
|
||||
outline-offset: 2px;
|
||||
@@ -131,10 +131,6 @@
|
||||
color: var(--color-gray-90);
|
||||
flex: 0 0 auto;
|
||||
|
||||
&:active {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
|
||||
&-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -148,14 +144,14 @@
|
||||
right: -3px;
|
||||
bottom: -3px;
|
||||
left: -3px;
|
||||
border: 1px solid var(--avatar-border-color);
|
||||
border-radius: 100%;
|
||||
}
|
||||
|
||||
&.is-followed::before {
|
||||
&--is-followed::before {
|
||||
border-color: var(--color-primary-hover);
|
||||
box-shadow: 0 0 0 1px var(--color-primary-hover);
|
||||
}
|
||||
&.is-current-user {
|
||||
&--is-current-user {
|
||||
cursor: auto;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
|
||||
"type": "arrow",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -50,7 +49,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
|
||||
"type": "arrow",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -81,7 +79,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": {
|
||||
"elementId": "ellipse-1",
|
||||
@@ -135,7 +132,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": {
|
||||
"elementId": "ellipse-1",
|
||||
@@ -194,7 +190,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing s
|
||||
"type": "arrow",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -224,6 +219,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": [
|
||||
{
|
||||
"id": "id48",
|
||||
@@ -231,7 +227,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
},
|
||||
],
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -268,6 +263,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": [
|
||||
{
|
||||
"id": "id48",
|
||||
@@ -275,7 +271,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
},
|
||||
],
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -318,7 +313,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": {
|
||||
"elementId": "text-2",
|
||||
@@ -371,9 +365,9 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to existing t
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id48",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -416,7 +410,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": {
|
||||
"elementId": "id40",
|
||||
@@ -469,9 +462,9 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id37",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -514,7 +507,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
|
||||
"type": "arrow",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -550,7 +542,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to shapes whe
|
||||
"type": "arrow",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -586,7 +577,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": {
|
||||
"elementId": "id44",
|
||||
@@ -639,9 +629,9 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id41",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -678,6 +668,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": [
|
||||
{
|
||||
"id": "id41",
|
||||
@@ -685,7 +676,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
},
|
||||
],
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -722,6 +712,7 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": [
|
||||
{
|
||||
"id": "id41",
|
||||
@@ -729,7 +720,6 @@ exports[`Test Transform > Test arrow bindings > should bind arrows to text when
|
||||
},
|
||||
],
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -767,7 +757,6 @@ exports[`Test Transform > should not allow duplicate ids 1`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -798,7 +787,6 @@ exports[`Test Transform > should transform linear elements 1`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -844,7 +832,6 @@ exports[`Test Transform > should transform linear elements 2`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": "triangle",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -890,7 +877,6 @@ exports[`Test Transform > should transform linear elements 3`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": null,
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -936,7 +922,6 @@ exports[`Test Transform > should transform linear elements 4`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"endArrowhead": null,
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -982,7 +967,6 @@ exports[`Test Transform > should transform regular shapes 1`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1013,7 +997,6 @@ exports[`Test Transform > should transform regular shapes 2`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1044,7 +1027,6 @@ exports[`Test Transform > should transform regular shapes 3`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1075,7 +1057,6 @@ exports[`Test Transform > should transform regular shapes 4`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "#c0eb75",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1106,7 +1087,6 @@ exports[`Test Transform > should transform regular shapes 5`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "#ffc9c9",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1137,7 +1117,6 @@ exports[`Test Transform > should transform regular shapes 6`] = `
|
||||
"angle": 0,
|
||||
"backgroundColor": "#a5d8ff",
|
||||
"boundElements": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "cross-hatch",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1167,9 +1146,9 @@ exports[`Test Transform > should transform text element 1`] = `
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1206,9 +1185,9 @@ exports[`Test Transform > should transform text element 2`] = `
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": null,
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1251,7 +1230,6 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -1302,7 +1280,6 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -1353,7 +1330,6 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -1404,7 +1380,6 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"endArrowhead": "arrow",
|
||||
"endBinding": null,
|
||||
"fillStyle": "solid",
|
||||
@@ -1449,9 +1424,9 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id25",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1488,9 +1463,9 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id26",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1527,9 +1502,9 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id27",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1567,9 +1542,9 @@ exports[`Test Transform > should transform to labelled arrows when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id28",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1613,7 +1588,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1649,7 +1623,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1685,7 +1658,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1721,7 +1693,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1757,7 +1728,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1793,7 +1763,6 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
"type": "text",
|
||||
},
|
||||
],
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"frameId": null,
|
||||
"groupIds": [],
|
||||
@@ -1823,9 +1792,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id13",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1862,9 +1831,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id14",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1902,9 +1871,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id15",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1944,9 +1913,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id16",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -1984,9 +1953,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id17",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
@@ -2025,9 +1994,9 @@ exports[`Test Transform > should transform to text containers when label provide
|
||||
{
|
||||
"angle": 0,
|
||||
"backgroundColor": "transparent",
|
||||
"baseline": 0,
|
||||
"boundElements": null,
|
||||
"containerId": "id18",
|
||||
"customData": undefined,
|
||||
"fillStyle": "solid",
|
||||
"fontFamily": 1,
|
||||
"fontSize": 20,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { IMAGE_MIME_TYPES, MIME_TYPES } from "../constants";
|
||||
import { clearElementsForExport } from "../element";
|
||||
import { ExcalidrawElement, FileId } from "../element/types";
|
||||
import { CanvasError, ImageSceneDataError } from "../errors";
|
||||
import { t } from "../i18n";
|
||||
import { calculateScrollCenter } from "../scene";
|
||||
import { AppState, DataURL, LibraryItem } from "../types";
|
||||
import { ValueOf } from "../utility-types";
|
||||
@@ -22,11 +23,11 @@ const parseFileContents = async (blob: Blob | File) => {
|
||||
} catch (error: any) {
|
||||
if (error.message === "INVALID") {
|
||||
throw new ImageSceneDataError(
|
||||
"Image doesn't contain scene",
|
||||
t("alerts.imageDoesNotContainScene"),
|
||||
"IMAGE_NOT_CONTAINS_SCENE_DATA",
|
||||
);
|
||||
} else {
|
||||
throw new ImageSceneDataError("Error: cannot restore image");
|
||||
throw new ImageSceneDataError(t("alerts.cannotRestoreFromImage"));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -53,11 +54,11 @@ const parseFileContents = async (blob: Blob | File) => {
|
||||
} catch (error: any) {
|
||||
if (error.message === "INVALID") {
|
||||
throw new ImageSceneDataError(
|
||||
"Image doesn't contain scene",
|
||||
t("alerts.imageDoesNotContainScene"),
|
||||
"IMAGE_NOT_CONTAINS_SCENE_DATA",
|
||||
);
|
||||
} else {
|
||||
throw new ImageSceneDataError("Error: cannot restore image");
|
||||
throw new ImageSceneDataError(t("alerts.cannotRestoreFromImage"));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,7 +130,7 @@ export const loadSceneOrLibraryFromBlob = async (
|
||||
} catch (error: any) {
|
||||
if (isSupportedImageFile(blob)) {
|
||||
throw new ImageSceneDataError(
|
||||
"Image doesn't contain scene",
|
||||
t("alerts.imageDoesNotContainScene"),
|
||||
"IMAGE_NOT_CONTAINS_SCENE_DATA",
|
||||
);
|
||||
}
|
||||
@@ -162,12 +163,12 @@ export const loadSceneOrLibraryFromBlob = async (
|
||||
data,
|
||||
};
|
||||
}
|
||||
throw new Error("Error: invalid file");
|
||||
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
||||
} catch (error: any) {
|
||||
if (error instanceof ImageSceneDataError) {
|
||||
throw error;
|
||||
}
|
||||
throw new Error("Error: invalid file");
|
||||
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -186,7 +187,7 @@ export const loadFromBlob = async (
|
||||
fileHandle,
|
||||
);
|
||||
if (ret.type !== MIME_TYPES.excalidraw) {
|
||||
throw new Error("Error: invalid file");
|
||||
throw new Error(t("alerts.couldNotLoadInvalidFile"));
|
||||
}
|
||||
return ret.data;
|
||||
};
|
||||
@@ -221,7 +222,10 @@ export const canvasToBlob = async (
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) {
|
||||
return reject(
|
||||
new CanvasError("Error: Canvas too big", "CANVAS_POSSIBLY_TOO_BIG"),
|
||||
new CanvasError(
|
||||
t("canvasError.canvasTooBig"),
|
||||
"CANVAS_POSSIBLY_TOO_BIG",
|
||||
),
|
||||
);
|
||||
}
|
||||
resolve(blob);
|
||||
@@ -310,7 +314,7 @@ export const resizeImageFile = async (
|
||||
}
|
||||
|
||||
if (!isSupportedImageFile(file)) {
|
||||
throw new Error("Error: unsupported file type", { cause: "UNSUPPORTED" });
|
||||
throw new Error(t("errors.unsupportedFileType"));
|
||||
}
|
||||
|
||||
return new File(
|
||||
@@ -336,11 +340,11 @@ export const ImageURLToFile = async (
|
||||
try {
|
||||
response = await fetch(imageUrl);
|
||||
} catch (error: any) {
|
||||
throw new Error("Error: failed to fetch image", { cause: "FETCH_ERROR" });
|
||||
throw new Error(t("errors.failedToFetchImage"));
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Error: failed to fetch image", { cause: "FETCH_ERROR" });
|
||||
throw new Error(t("errors.failedToFetchImage"));
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
@@ -350,7 +354,7 @@ export const ImageURLToFile = async (
|
||||
return new File([blob], name, { type: blob.type });
|
||||
}
|
||||
|
||||
throw new Error("Error: unsupported file type", { cause: "UNSUPPORTED" });
|
||||
throw new Error(t("errors.unsupportedFileType"));
|
||||
};
|
||||
|
||||
export const getFileFromEvent = async (
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { EDITOR_LS_KEYS } from "../constants";
|
||||
import { t } from "../i18n";
|
||||
import { getDateTime } from "../utils";
|
||||
import { EditorLocalStorage } from "./EditorLocalStorage";
|
||||
|
||||
export const getFileName = () => {
|
||||
return (
|
||||
EditorLocalStorage.get<string>(EDITOR_LS_KEYS.EXCALIDRAW_FILE_NAME) ||
|
||||
`${t("labels.untitled")}-${getDateTime()}`
|
||||
);
|
||||
};
|
||||
@@ -2,12 +2,7 @@ import {
|
||||
copyBlobToClipboardAsPng,
|
||||
copyTextToSystemClipboard,
|
||||
} from "../clipboard";
|
||||
import {
|
||||
DEFAULT_EXPORT_PADDING,
|
||||
DEFAULT_FILENAME,
|
||||
isFirefox,
|
||||
MIME_TYPES,
|
||||
} from "../constants";
|
||||
import { DEFAULT_EXPORT_PADDING, isFirefox, MIME_TYPES } from "../constants";
|
||||
import { getNonDeletedElements } from "../element";
|
||||
import { isFrameLikeElement } from "../element/typeChecks";
|
||||
import {
|
||||
@@ -89,15 +84,14 @@ export const exportCanvas = async (
|
||||
exportBackground,
|
||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
||||
viewBackgroundColor,
|
||||
name = appState.name || DEFAULT_FILENAME,
|
||||
name,
|
||||
fileHandle = null,
|
||||
exportingFrame = null,
|
||||
}: {
|
||||
exportBackground: boolean;
|
||||
exportPadding?: number;
|
||||
viewBackgroundColor: string;
|
||||
/** filename, if applicable */
|
||||
name?: string;
|
||||
name: string;
|
||||
fileHandle?: FileSystemHandle | null;
|
||||
exportingFrame: ExcalidrawFrameLikeElement | null;
|
||||
},
|
||||
@@ -133,12 +127,9 @@ export const exportCanvas = async (
|
||||
},
|
||||
);
|
||||
} else if (type === "clipboard-svg") {
|
||||
const svg = await svgPromise.then((svg) => svg.outerHTML);
|
||||
try {
|
||||
await copyTextToSystemClipboard(svg);
|
||||
} catch (e) {
|
||||
throw new Error(t("errors.copyToSystemClipboardFailed"));
|
||||
}
|
||||
await copyTextToSystemClipboard(
|
||||
await svgPromise.then((svg) => svg.outerHTML),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -179,7 +170,7 @@ export const exportCanvas = async (
|
||||
} catch (error: any) {
|
||||
console.warn(error);
|
||||
if (error.name === "CANVAS_POSSIBLY_TOO_BIG") {
|
||||
throw new Error(t("canvasError.canvasTooBig"));
|
||||
throw error;
|
||||
}
|
||||
// TypeError *probably* suggests ClipboardItem not defined, which
|
||||
// people on Firefox can enable through a flag, so let's tell them.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { fileOpen, fileSave } from "./filesystem";
|
||||
import { cleanAppStateForExport, clearAppStateForDatabase } from "../appState";
|
||||
import {
|
||||
DEFAULT_FILENAME,
|
||||
EXPORT_DATA_TYPES,
|
||||
EXPORT_SOURCE,
|
||||
MIME_TYPES,
|
||||
@@ -72,8 +71,7 @@ export const saveAsJSON = async (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
appState: AppState,
|
||||
files: BinaryFiles,
|
||||
/** filename */
|
||||
name: string = appState.name || DEFAULT_FILENAME,
|
||||
name: string,
|
||||
) => {
|
||||
const serialized = serializeAsJSON(elements, appState, files, "local");
|
||||
const blob = new Blob([serialized], {
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
LibraryItem,
|
||||
ExcalidrawImperativeAPI,
|
||||
LibraryItemsSource,
|
||||
LibraryItems_anyVersion,
|
||||
} from "../types";
|
||||
import { restoreLibraryItems } from "./restore";
|
||||
import type App from "../components/App";
|
||||
@@ -24,72 +23,13 @@ import {
|
||||
LIBRARY_SIDEBAR_TAB,
|
||||
} from "../constants";
|
||||
import { libraryItemSvgsCache } from "../hooks/useLibraryItemSvg";
|
||||
import {
|
||||
arrayToMap,
|
||||
cloneJSON,
|
||||
preventUnload,
|
||||
promiseTry,
|
||||
resolvablePromise,
|
||||
} from "../utils";
|
||||
import { MaybePromise } from "../utility-types";
|
||||
import { Emitter } from "../emitter";
|
||||
import { Queue } from "../queue";
|
||||
import { hashElementsVersion, hashString } from "../element";
|
||||
|
||||
type LibraryUpdate = {
|
||||
/** deleted library items since last onLibraryChange event */
|
||||
deletedItems: Map<LibraryItem["id"], LibraryItem>;
|
||||
/** newly added items in the library */
|
||||
addedItems: Map<LibraryItem["id"], LibraryItem>;
|
||||
};
|
||||
|
||||
// an object so that we can later add more properties to it without breaking,
|
||||
// such as schema version
|
||||
export type LibraryPersistedData = { libraryItems: LibraryItems };
|
||||
|
||||
const onLibraryUpdateEmitter = new Emitter<
|
||||
[update: LibraryUpdate, libraryItems: LibraryItems]
|
||||
>();
|
||||
|
||||
export type LibraryAdatapterSource = "load" | "save";
|
||||
|
||||
export interface LibraryPersistenceAdapter {
|
||||
/**
|
||||
* Should load data that were previously saved into the database using the
|
||||
* `save` method. Should throw if saving fails.
|
||||
*
|
||||
* Will be used internally in multiple places, such as during save to
|
||||
* in order to reconcile changes with latest store data.
|
||||
*/
|
||||
load(metadata: {
|
||||
/**
|
||||
* Indicates whether we're loading data for save purposes, or reading
|
||||
* purposes, in which case host app can implement more aggressive caching.
|
||||
*/
|
||||
source: LibraryAdatapterSource;
|
||||
}): MaybePromise<{ libraryItems: LibraryItems_anyVersion } | null>;
|
||||
/** Should persist to the database as is (do no change the data structure). */
|
||||
save(libraryData: LibraryPersistedData): MaybePromise<void>;
|
||||
}
|
||||
|
||||
export interface LibraryMigrationAdapter {
|
||||
/**
|
||||
* loads data from legacy data source. Returns `null` if no data is
|
||||
* to be migrated.
|
||||
*/
|
||||
load(): MaybePromise<{ libraryItems: LibraryItems_anyVersion } | null>;
|
||||
|
||||
/** clears entire storage afterwards */
|
||||
clear(): MaybePromise<void>;
|
||||
}
|
||||
import { cloneJSON } from "../utils";
|
||||
|
||||
export const libraryItemsAtom = atom<{
|
||||
status: "loading" | "loaded";
|
||||
/** indicates whether library is initialized with library items (has gone
|
||||
* through at least one update). Used in UI. Specific to this atom only. */
|
||||
isInitialized: boolean;
|
||||
libraryItems: LibraryItems;
|
||||
}>({ status: "loaded", isInitialized: false, libraryItems: [] });
|
||||
}>({ status: "loaded", isInitialized: true, libraryItems: [] });
|
||||
|
||||
const cloneLibraryItems = (libraryItems: LibraryItems): LibraryItems =>
|
||||
cloneJSON(libraryItems);
|
||||
@@ -134,45 +74,12 @@ export const mergeLibraryItems = (
|
||||
return [...newItems, ...localItems];
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns { deletedItems, addedItems } maps of all added and deleted items
|
||||
* since last onLibraryChange event.
|
||||
*
|
||||
* Host apps are recommended to diff with the latest state they have.
|
||||
*/
|
||||
const createLibraryUpdate = (
|
||||
prevLibraryItems: LibraryItems,
|
||||
nextLibraryItems: LibraryItems,
|
||||
): LibraryUpdate => {
|
||||
const nextItemsMap = arrayToMap(nextLibraryItems);
|
||||
|
||||
const update: LibraryUpdate = {
|
||||
deletedItems: new Map<LibraryItem["id"], LibraryItem>(),
|
||||
addedItems: new Map<LibraryItem["id"], LibraryItem>(),
|
||||
};
|
||||
|
||||
for (const item of prevLibraryItems) {
|
||||
if (!nextItemsMap.has(item.id)) {
|
||||
update.deletedItems.set(item.id, item);
|
||||
}
|
||||
}
|
||||
|
||||
const prevItemsMap = arrayToMap(prevLibraryItems);
|
||||
|
||||
for (const item of nextLibraryItems) {
|
||||
if (!prevItemsMap.has(item.id)) {
|
||||
update.addedItems.set(item.id, item);
|
||||
}
|
||||
}
|
||||
|
||||
return update;
|
||||
};
|
||||
|
||||
class Library {
|
||||
/** latest libraryItems */
|
||||
private currLibraryItems: LibraryItems = [];
|
||||
/** snapshot of library items since last onLibraryChange call */
|
||||
private prevLibraryItems = cloneLibraryItems(this.currLibraryItems);
|
||||
private lastLibraryItems: LibraryItems = [];
|
||||
/** indicates whether library is initialized with library items (has gone
|
||||
* though at least one update) */
|
||||
private isInitialized = false;
|
||||
|
||||
private app: App;
|
||||
|
||||
@@ -188,29 +95,21 @@ class Library {
|
||||
|
||||
private notifyListeners = () => {
|
||||
if (this.updateQueue.length > 0) {
|
||||
jotaiStore.set(libraryItemsAtom, (s) => ({
|
||||
jotaiStore.set(libraryItemsAtom, {
|
||||
status: "loading",
|
||||
libraryItems: this.currLibraryItems,
|
||||
isInitialized: s.isInitialized,
|
||||
}));
|
||||
libraryItems: this.lastLibraryItems,
|
||||
isInitialized: this.isInitialized,
|
||||
});
|
||||
} else {
|
||||
this.isInitialized = true;
|
||||
jotaiStore.set(libraryItemsAtom, {
|
||||
status: "loaded",
|
||||
libraryItems: this.currLibraryItems,
|
||||
isInitialized: true,
|
||||
libraryItems: this.lastLibraryItems,
|
||||
isInitialized: this.isInitialized,
|
||||
});
|
||||
try {
|
||||
const prevLibraryItems = this.prevLibraryItems;
|
||||
this.prevLibraryItems = cloneLibraryItems(this.currLibraryItems);
|
||||
|
||||
const nextLibraryItems = cloneLibraryItems(this.currLibraryItems);
|
||||
|
||||
this.app.props.onLibraryChange?.(nextLibraryItems);
|
||||
|
||||
// for internal use in `useHandleLibrary` hook
|
||||
onLibraryUpdateEmitter.trigger(
|
||||
createLibraryUpdate(prevLibraryItems, nextLibraryItems),
|
||||
nextLibraryItems,
|
||||
this.app.props.onLibraryChange?.(
|
||||
cloneLibraryItems(this.lastLibraryItems),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
@@ -220,8 +119,9 @@ class Library {
|
||||
|
||||
/** call on excalidraw instance unmount */
|
||||
destroy = () => {
|
||||
this.isInitialized = false;
|
||||
this.updateQueue = [];
|
||||
this.currLibraryItems = [];
|
||||
this.lastLibraryItems = [];
|
||||
jotaiStore.set(libraryItemSvgsCache, new Map());
|
||||
// TODO uncomment after/if we make jotai store scoped to each excal instance
|
||||
// jotaiStore.set(libraryItemsAtom, {
|
||||
@@ -242,14 +142,14 @@ class Library {
|
||||
return new Promise(async (resolve) => {
|
||||
try {
|
||||
const libraryItems = await (this.getLastUpdateTask() ||
|
||||
this.currLibraryItems);
|
||||
this.lastLibraryItems);
|
||||
if (this.updateQueue.length > 0) {
|
||||
resolve(this.getLatestLibrary());
|
||||
} else {
|
||||
resolve(cloneLibraryItems(libraryItems));
|
||||
}
|
||||
} catch (error) {
|
||||
return resolve(this.currLibraryItems);
|
||||
return resolve(this.lastLibraryItems);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -281,7 +181,7 @@ class Library {
|
||||
try {
|
||||
const source = await (typeof libraryItems === "function" &&
|
||||
!(libraryItems instanceof Blob)
|
||||
? libraryItems(this.currLibraryItems)
|
||||
? libraryItems(this.lastLibraryItems)
|
||||
: libraryItems);
|
||||
|
||||
let nextItems;
|
||||
@@ -307,7 +207,7 @@ class Library {
|
||||
}
|
||||
|
||||
if (merge) {
|
||||
resolve(mergeLibraryItems(this.currLibraryItems, nextItems));
|
||||
resolve(mergeLibraryItems(this.lastLibraryItems, nextItems));
|
||||
} else {
|
||||
resolve(nextItems);
|
||||
}
|
||||
@@ -344,12 +244,12 @@ class Library {
|
||||
await this.getLastUpdateTask();
|
||||
|
||||
if (typeof libraryItems === "function") {
|
||||
libraryItems = libraryItems(this.currLibraryItems);
|
||||
libraryItems = libraryItems(this.lastLibraryItems);
|
||||
}
|
||||
|
||||
this.currLibraryItems = cloneLibraryItems(await libraryItems);
|
||||
this.lastLibraryItems = cloneLibraryItems(await libraryItems);
|
||||
|
||||
resolve(this.currLibraryItems);
|
||||
resolve(this.lastLibraryItems);
|
||||
} catch (error: any) {
|
||||
reject(error);
|
||||
}
|
||||
@@ -357,7 +257,7 @@ class Library {
|
||||
.catch((error) => {
|
||||
if (error.name === "AbortError") {
|
||||
console.warn("Library update aborted by user");
|
||||
return this.currLibraryItems;
|
||||
return this.lastLibraryItems;
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
@@ -482,165 +382,20 @@ export const parseLibraryTokensFromUrl = () => {
|
||||
return libraryUrl ? { libraryUrl, idToken } : null;
|
||||
};
|
||||
|
||||
class AdapterTransaction {
|
||||
static queue = new Queue();
|
||||
|
||||
static async getLibraryItems(
|
||||
adapter: LibraryPersistenceAdapter,
|
||||
source: LibraryAdatapterSource,
|
||||
_queue = true,
|
||||
): Promise<LibraryItems> {
|
||||
const task = () =>
|
||||
new Promise<LibraryItems>(async (resolve, reject) => {
|
||||
try {
|
||||
const data = await adapter.load({ source });
|
||||
resolve(restoreLibraryItems(data?.libraryItems || [], "published"));
|
||||
} catch (error: any) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
if (_queue) {
|
||||
return AdapterTransaction.queue.push(task);
|
||||
}
|
||||
|
||||
return task();
|
||||
}
|
||||
|
||||
static run = async <T>(
|
||||
adapter: LibraryPersistenceAdapter,
|
||||
fn: (transaction: AdapterTransaction) => Promise<T>,
|
||||
) => {
|
||||
const transaction = new AdapterTransaction(adapter);
|
||||
return AdapterTransaction.queue.push(() => fn(transaction));
|
||||
};
|
||||
|
||||
// ------------------
|
||||
|
||||
private adapter: LibraryPersistenceAdapter;
|
||||
|
||||
constructor(adapter: LibraryPersistenceAdapter) {
|
||||
this.adapter = adapter;
|
||||
}
|
||||
|
||||
getLibraryItems(source: LibraryAdatapterSource) {
|
||||
return AdapterTransaction.getLibraryItems(this.adapter, source, false);
|
||||
}
|
||||
}
|
||||
|
||||
let lastSavedLibraryItemsHash = 0;
|
||||
let librarySaveCounter = 0;
|
||||
|
||||
export const getLibraryItemsHash = (items: LibraryItems) => {
|
||||
return hashString(
|
||||
items
|
||||
.map((item) => {
|
||||
return `${item.id}:${hashElementsVersion(item.elements)}`;
|
||||
})
|
||||
.sort()
|
||||
.join(),
|
||||
);
|
||||
};
|
||||
|
||||
const persistLibraryUpdate = async (
|
||||
adapter: LibraryPersistenceAdapter,
|
||||
update: LibraryUpdate,
|
||||
): Promise<LibraryItems> => {
|
||||
try {
|
||||
librarySaveCounter++;
|
||||
|
||||
return await AdapterTransaction.run(adapter, async (transaction) => {
|
||||
const nextLibraryItemsMap = arrayToMap(
|
||||
await transaction.getLibraryItems("save"),
|
||||
);
|
||||
|
||||
for (const [id] of update.deletedItems) {
|
||||
nextLibraryItemsMap.delete(id);
|
||||
}
|
||||
|
||||
const addedItems: LibraryItem[] = [];
|
||||
|
||||
// we want to merge current library items with the ones stored in the
|
||||
// DB so that we don't lose any elements that for some reason aren't
|
||||
// in the current editor library, which could happen when:
|
||||
//
|
||||
// 1. we haven't received an update deleting some elements
|
||||
// (in which case it's still better to keep them in the DB lest
|
||||
// it was due to a different reason)
|
||||
// 2. we keep a single DB for all active editors, but the editors'
|
||||
// libraries aren't synced or there's a race conditions during
|
||||
// syncing
|
||||
// 3. some other race condition, e.g. during init where emit updates
|
||||
// for partial updates (e.g. you install a 3rd party library and
|
||||
// init from DB only after — we emit events for both updates)
|
||||
for (const [id, item] of update.addedItems) {
|
||||
if (nextLibraryItemsMap.has(id)) {
|
||||
// replace item with latest version
|
||||
// TODO we could prefer the newer item instead
|
||||
nextLibraryItemsMap.set(id, item);
|
||||
} else {
|
||||
// we want to prepend the new items with the ones that are already
|
||||
// in DB to preserve the ordering we do in editor (newly added
|
||||
// items are added to the beginning)
|
||||
addedItems.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const nextLibraryItems = addedItems.concat(
|
||||
Array.from(nextLibraryItemsMap.values()),
|
||||
);
|
||||
|
||||
const version = getLibraryItemsHash(nextLibraryItems);
|
||||
|
||||
if (version !== lastSavedLibraryItemsHash) {
|
||||
await adapter.save({ libraryItems: nextLibraryItems });
|
||||
}
|
||||
|
||||
lastSavedLibraryItemsHash = version;
|
||||
|
||||
return nextLibraryItems;
|
||||
});
|
||||
} finally {
|
||||
librarySaveCounter--;
|
||||
}
|
||||
};
|
||||
|
||||
export const useHandleLibrary = (
|
||||
opts: {
|
||||
excalidrawAPI: ExcalidrawImperativeAPI | null;
|
||||
} & (
|
||||
| {
|
||||
/** @deprecated we recommend using `opts.adapter` instead */
|
||||
getInitialLibraryItems?: () => MaybePromise<LibraryItemsSource>;
|
||||
}
|
||||
| {
|
||||
adapter: LibraryPersistenceAdapter;
|
||||
/**
|
||||
* Adapter that takes care of loading data from legacy data store.
|
||||
* Supply this if you want to migrate data on initial load from legacy
|
||||
* data store.
|
||||
*
|
||||
* Can be a different LibraryPersistenceAdapter.
|
||||
*/
|
||||
migrationAdapter?: LibraryMigrationAdapter;
|
||||
}
|
||||
),
|
||||
) => {
|
||||
const { excalidrawAPI } = opts;
|
||||
|
||||
const optsRef = useRef(opts);
|
||||
optsRef.current = opts;
|
||||
|
||||
const isLibraryLoadedRef = useRef(false);
|
||||
export const useHandleLibrary = ({
|
||||
excalidrawAPI,
|
||||
getInitialLibraryItems,
|
||||
}: {
|
||||
excalidrawAPI: ExcalidrawImperativeAPI | null;
|
||||
getInitialLibraryItems?: () => LibraryItemsSource;
|
||||
}) => {
|
||||
const getInitialLibraryRef = useRef(getInitialLibraryItems);
|
||||
|
||||
useEffect(() => {
|
||||
if (!excalidrawAPI) {
|
||||
return;
|
||||
}
|
||||
|
||||
// reset on editor remount (excalidrawAPI changed)
|
||||
isLibraryLoadedRef.current = false;
|
||||
|
||||
const importLibraryFromURL = async ({
|
||||
libraryUrl,
|
||||
idToken,
|
||||
@@ -708,209 +463,23 @@ export const useHandleLibrary = (
|
||||
};
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// ---------------------------------- init ---------------------------------
|
||||
// -------------------------------------------------------------------------
|
||||
// ------ init load --------------------------------------------------------
|
||||
if (getInitialLibraryRef.current) {
|
||||
excalidrawAPI.updateLibrary({
|
||||
libraryItems: getInitialLibraryRef.current(),
|
||||
});
|
||||
}
|
||||
|
||||
const libraryUrlTokens = parseLibraryTokensFromUrl();
|
||||
|
||||
if (libraryUrlTokens) {
|
||||
importLibraryFromURL(libraryUrlTokens);
|
||||
}
|
||||
|
||||
// ------ (A) init load (legacy) -------------------------------------------
|
||||
if (
|
||||
"getInitialLibraryItems" in optsRef.current &&
|
||||
optsRef.current.getInitialLibraryItems
|
||||
) {
|
||||
console.warn(
|
||||
"useHandleLibrar `opts.getInitialLibraryItems` is deprecated. Use `opts.adapter` instead.",
|
||||
);
|
||||
|
||||
Promise.resolve(optsRef.current.getInitialLibraryItems())
|
||||
.then((libraryItems) => {
|
||||
excalidrawAPI.updateLibrary({
|
||||
libraryItems,
|
||||
// merge with current library items because we may have already
|
||||
// populated it (e.g. by installing 3rd party library which can
|
||||
// happen before the DB data is loaded)
|
||||
merge: true,
|
||||
});
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error(
|
||||
`UseHandeLibrary getInitialLibraryItems failed: ${error?.message}`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// --------------------------------------------------------- init load -----
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
// ------ (B) data source adapter ------------------------------------------
|
||||
|
||||
if ("adapter" in optsRef.current && optsRef.current.adapter) {
|
||||
const adapter = optsRef.current.adapter;
|
||||
const migrationAdapter = optsRef.current.migrationAdapter;
|
||||
|
||||
const initDataPromise = resolvablePromise<LibraryItems | null>();
|
||||
|
||||
// migrate from old data source if needed
|
||||
// (note, if `migrate` function is defined, we always migrate even
|
||||
// if the data has already been migrated. In that case it'll be a no-op,
|
||||
// though with several unnecessary steps — we will still load latest
|
||||
// DB data during the `persistLibraryChange()` step)
|
||||
// -----------------------------------------------------------------------
|
||||
if (migrationAdapter) {
|
||||
initDataPromise.resolve(
|
||||
promiseTry(migrationAdapter.load)
|
||||
.then(async (libraryData) => {
|
||||
let restoredData: LibraryItems | null = null;
|
||||
try {
|
||||
// if no library data to migrate, assume no migration needed
|
||||
// and skip persisting to new data store, as well as well
|
||||
// clearing the old store via `migrationAdapter.clear()`
|
||||
if (!libraryData) {
|
||||
return AdapterTransaction.getLibraryItems(adapter, "load");
|
||||
}
|
||||
|
||||
restoredData = restoreLibraryItems(
|
||||
libraryData.libraryItems || [],
|
||||
"published",
|
||||
);
|
||||
|
||||
// we don't queue this operation because it's running inside
|
||||
// a promise that's running inside Library update queue itself
|
||||
const nextItems = await persistLibraryUpdate(
|
||||
adapter,
|
||||
createLibraryUpdate([], restoredData),
|
||||
);
|
||||
try {
|
||||
await migrationAdapter.clear();
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
`couldn't delete legacy library data: ${error.message}`,
|
||||
);
|
||||
}
|
||||
// migration suceeded, load migrated data
|
||||
return nextItems;
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
`couldn't migrate legacy library data: ${error.message}`,
|
||||
);
|
||||
// migration failed, load data from previous store, if any
|
||||
return restoredData;
|
||||
}
|
||||
})
|
||||
// errors caught during `migrationAdapter.load()`
|
||||
.catch((error: any) => {
|
||||
console.error(`error during library migration: ${error.message}`);
|
||||
// as a default, load latest library from current data source
|
||||
return AdapterTransaction.getLibraryItems(adapter, "load");
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
initDataPromise.resolve(
|
||||
promiseTry(AdapterTransaction.getLibraryItems, adapter, "load"),
|
||||
);
|
||||
}
|
||||
|
||||
// load initial (or migrated) library
|
||||
excalidrawAPI
|
||||
.updateLibrary({
|
||||
libraryItems: initDataPromise.then((libraryItems) => {
|
||||
const _libraryItems = libraryItems || [];
|
||||
lastSavedLibraryItemsHash = getLibraryItemsHash(_libraryItems);
|
||||
return _libraryItems;
|
||||
}),
|
||||
// merge with current library items because we may have already
|
||||
// populated it (e.g. by installing 3rd party library which can
|
||||
// happen before the DB data is loaded)
|
||||
merge: true,
|
||||
})
|
||||
.finally(() => {
|
||||
isLibraryLoadedRef.current = true;
|
||||
});
|
||||
}
|
||||
// ---------------------------------------------- data source datapter -----
|
||||
|
||||
window.addEventListener(EVENT.HASHCHANGE, onHashChange);
|
||||
return () => {
|
||||
window.removeEventListener(EVENT.HASHCHANGE, onHashChange);
|
||||
};
|
||||
}, [
|
||||
// important this useEffect only depends on excalidrawAPI so it only reruns
|
||||
// on editor remounts (the excalidrawAPI changes)
|
||||
excalidrawAPI,
|
||||
]);
|
||||
|
||||
// This effect is run without excalidrawAPI dependency so that host apps
|
||||
// can run this hook outside of an active editor instance and the library
|
||||
// update queue/loop survives editor remounts
|
||||
//
|
||||
// This effect is still only meant to be run if host apps supply an persitence
|
||||
// adapter. If we don't have access to it, it the update listener doesn't
|
||||
// do anything.
|
||||
useEffect(
|
||||
() => {
|
||||
// on update, merge with current library items and persist
|
||||
// -----------------------------------------------------------------------
|
||||
const unsubOnLibraryUpdate = onLibraryUpdateEmitter.on(
|
||||
async (update, nextLibraryItems) => {
|
||||
const isLoaded = isLibraryLoadedRef.current;
|
||||
// we want to operate with the latest adapter, but we don't want this
|
||||
// effect to rerun on every adapter change in case host apps' adapter
|
||||
// isn't stable
|
||||
const adapter =
|
||||
("adapter" in optsRef.current && optsRef.current.adapter) || null;
|
||||
try {
|
||||
if (adapter) {
|
||||
if (
|
||||
// if nextLibraryItems hash identical to previously saved hash,
|
||||
// exit early, even if actual upstream state ends up being
|
||||
// different (e.g. has more data than we have locally), as it'd
|
||||
// be low-impact scenario.
|
||||
lastSavedLibraryItemsHash !==
|
||||
getLibraryItemsHash(nextLibraryItems)
|
||||
) {
|
||||
await persistLibraryUpdate(adapter, update);
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
`couldn't persist library update: ${error.message}`,
|
||||
update,
|
||||
);
|
||||
|
||||
// currently we only show error if an editor is loaded
|
||||
if (isLoaded && optsRef.current.excalidrawAPI) {
|
||||
optsRef.current.excalidrawAPI.updateScene({
|
||||
appState: {
|
||||
errorMessage: t("errors.saveLibraryError"),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const onUnload = (event: Event) => {
|
||||
if (librarySaveCounter) {
|
||||
preventUnload(event);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener(EVENT.BEFORE_UNLOAD, onUnload);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener(EVENT.BEFORE_UNLOAD, onUnload);
|
||||
unsubOnLibraryUpdate();
|
||||
lastSavedLibraryItemsHash = 0;
|
||||
librarySaveCounter = 0;
|
||||
};
|
||||
},
|
||||
[
|
||||
// this effect must not have any deps so it doesn't rerun
|
||||
],
|
||||
);
|
||||
}, [excalidrawAPI]);
|
||||
};
|
||||
|
||||
@@ -35,13 +35,14 @@ import {
|
||||
import { getDefaultAppState } from "../appState";
|
||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||
import { bumpVersion } from "../element/mutateElement";
|
||||
import { getUpdatedTimestamp, updateActiveTool } from "../utils";
|
||||
import { getFontString, getUpdatedTimestamp, updateActiveTool } from "../utils";
|
||||
import { arrayToMap } from "../utils";
|
||||
import { MarkOptional, Mutable } from "../utility-types";
|
||||
import {
|
||||
detectLineHeight,
|
||||
getContainerElement,
|
||||
getDefaultLineHeight,
|
||||
measureBaseline,
|
||||
} from "../element/textElement";
|
||||
import { normalizeLink } from "./url";
|
||||
|
||||
@@ -206,6 +207,11 @@ const restoreElement = (
|
||||
: // no element height likely means programmatic use, so default
|
||||
// to a fixed line height
|
||||
getDefaultLineHeight(element.fontFamily));
|
||||
const baseline = measureBaseline(
|
||||
element.text,
|
||||
getFontString(element),
|
||||
lineHeight,
|
||||
);
|
||||
element = restoreElementWithProperties(element, {
|
||||
fontSize,
|
||||
fontFamily,
|
||||
@@ -216,6 +222,7 @@ const restoreElement = (
|
||||
originalText: element.originalText || text,
|
||||
|
||||
lineHeight,
|
||||
baseline,
|
||||
});
|
||||
|
||||
// if empty text, mark as deleted. We keep in array
|
||||
@@ -455,7 +462,6 @@ export const restoreElements = (
|
||||
refreshTextDimensions(
|
||||
element,
|
||||
getContainerElement(element, restoredElementsMap),
|
||||
restoredElementsMap,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -822,22 +822,4 @@ describe("Test Transform", () => {
|
||||
"Duplicate id found for rect-1",
|
||||
);
|
||||
});
|
||||
|
||||
it("should contains customData if provided", () => {
|
||||
const rawData = [
|
||||
{
|
||||
type: "rectangle",
|
||||
x: 100,
|
||||
y: 100,
|
||||
customData: { createdBy: "user01" },
|
||||
},
|
||||
];
|
||||
const convertedElements = convertToExcalidrawElements(
|
||||
rawData as ExcalidrawElementSkeleton[],
|
||||
opts,
|
||||
);
|
||||
expect(convertedElements[0].customData).toStrictEqual({
|
||||
createdBy: "user01",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -39,12 +39,11 @@ import {
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
FontFamilyValues,
|
||||
NonDeletedSceneElementsMap,
|
||||
TextAlign,
|
||||
VerticalAlign,
|
||||
} from "../element/types";
|
||||
import { MarkOptional } from "../utility-types";
|
||||
import { assertNever, cloneJSON, getFontString, toBrandedType } from "../utils";
|
||||
import { arrayToMap, assertNever, cloneJSON, getFontString } from "../utils";
|
||||
import { getSizeFromPoints } from "../points";
|
||||
import { randomId } from "../random";
|
||||
|
||||
@@ -223,7 +222,7 @@ const bindTextToContainer = (
|
||||
}),
|
||||
});
|
||||
|
||||
redrawTextBoundingBox(textElement, container, elementsMap);
|
||||
redrawTextBoundingBox(textElement, container);
|
||||
return [container, textElement] as const;
|
||||
};
|
||||
|
||||
@@ -232,7 +231,6 @@ const bindLinearElementToElement = (
|
||||
start: ValidLinearElement["start"],
|
||||
end: ValidLinearElement["end"],
|
||||
elementStore: ElementStore,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): {
|
||||
linearElement: ExcalidrawLinearElement;
|
||||
startBoundElement?: ExcalidrawElement;
|
||||
@@ -318,7 +316,6 @@ const bindLinearElementToElement = (
|
||||
linearElement,
|
||||
startBoundElement as ExcalidrawBindableElement,
|
||||
"start",
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -393,7 +390,6 @@ const bindLinearElementToElement = (
|
||||
linearElement,
|
||||
endBoundElement as ExcalidrawBindableElement,
|
||||
"end",
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -461,10 +457,6 @@ class ElementStore {
|
||||
return Array.from(this.excalidrawElements.values());
|
||||
};
|
||||
|
||||
getElementsMap = () => {
|
||||
return toBrandedType<NonDeletedSceneElementsMap>(this.excalidrawElements);
|
||||
};
|
||||
|
||||
getElement = (id: string) => {
|
||||
return this.excalidrawElements.get(id);
|
||||
};
|
||||
@@ -620,7 +612,6 @@ export const convertToExcalidrawElements = (
|
||||
}
|
||||
}
|
||||
|
||||
const elementsMap = elementStore.getElementsMap();
|
||||
// Add labels and arrow bindings
|
||||
for (const [id, element] of elementsWithIds) {
|
||||
const excalidrawElement = elementStore.getElement(id)!;
|
||||
@@ -634,7 +625,7 @@ export const convertToExcalidrawElements = (
|
||||
let [container, text] = bindTextToContainer(
|
||||
excalidrawElement,
|
||||
element?.label,
|
||||
elementsMap,
|
||||
arrayToMap(elementStore.getElements()),
|
||||
);
|
||||
elementStore.add(container);
|
||||
elementStore.add(text);
|
||||
@@ -662,7 +653,6 @@ export const convertToExcalidrawElements = (
|
||||
originalStart,
|
||||
originalEnd,
|
||||
elementStore,
|
||||
elementsMap,
|
||||
);
|
||||
container = linearElement;
|
||||
elementStore.add(linearElement);
|
||||
@@ -687,7 +677,6 @@ export const convertToExcalidrawElements = (
|
||||
start,
|
||||
end,
|
||||
elementStore,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
elementStore.add(linearElement);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { AppState } from "../types";
|
||||
import { sceneCoordsToViewportCoords } from "../utils";
|
||||
import { ElementsMap, NonDeletedExcalidrawElement } from "./types";
|
||||
import { NonDeletedExcalidrawElement } from "./types";
|
||||
import { getElementAbsoluteCoords } from ".";
|
||||
import { useExcalidrawAppState } from "../components/App";
|
||||
|
||||
@@ -11,9 +11,8 @@ const CONTAINER_PADDING = 5;
|
||||
const getContainerCoords = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const [x1, y1] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1] = getElementAbsoluteCoords(element);
|
||||
const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
|
||||
{ sceneX: x1 + element.width, sceneY: y1 },
|
||||
appState,
|
||||
@@ -26,11 +25,9 @@ const getContainerCoords = (
|
||||
export const ElementCanvasButtons = ({
|
||||
children,
|
||||
element,
|
||||
elementsMap,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
element: NonDeletedExcalidrawElement;
|
||||
elementsMap: ElementsMap;
|
||||
}) => {
|
||||
const appState = useExcalidrawAppState();
|
||||
|
||||
@@ -45,7 +42,7 @@ export const ElementCanvasButtons = ({
|
||||
return null;
|
||||
}
|
||||
|
||||
const { x, y } = getContainerCoords(element, appState, elementsMap);
|
||||
const { x, y } = getContainerCoords(element, appState);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
@import "../../css/variables.module.scss";
|
||||
@import "../css/variables.module.scss";
|
||||
|
||||
.excalidraw-hyperlinkContainer {
|
||||
display: flex;
|
||||
+156
-46
@@ -1,20 +1,21 @@
|
||||
import { AppState, ExcalidrawProps, Point } from "../../types";
|
||||
import { AppState, ExcalidrawProps, Point, UIAppState } from "../types";
|
||||
import {
|
||||
getShortcutKey,
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
wrapEvent,
|
||||
} from "../../utils";
|
||||
import { getEmbedLink, embeddableURLValidator } from "../../element/embeddable";
|
||||
import { mutateElement } from "../../element/mutateElement";
|
||||
} from "../utils";
|
||||
import { getEmbedLink, embeddableURLValidator } from "./embeddable";
|
||||
import { mutateElement } from "./mutateElement";
|
||||
import {
|
||||
ElementsMap,
|
||||
ExcalidrawEmbeddableElement,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "../../element/types";
|
||||
} from "./types";
|
||||
|
||||
import { ToolButton } from "../ToolButton";
|
||||
import { FreedrawIcon, TrashIcon } from "../icons";
|
||||
import { t } from "../../i18n";
|
||||
import { register } from "../actions/register";
|
||||
import { ToolButton } from "../components/ToolButton";
|
||||
import { FreedrawIcon, LinkIcon, TrashIcon } from "../components/icons";
|
||||
import { t } from "../i18n";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -23,19 +24,21 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import clsx from "clsx";
|
||||
import { KEYS } from "../../keys";
|
||||
import { EVENT, HYPERLINK_TOOLTIP_DELAY } from "../../constants";
|
||||
import { getElementAbsoluteCoords } from "../../element/bounds";
|
||||
import { getTooltipDiv, updateTooltipPosition } from "../Tooltip";
|
||||
import { getSelectedElements } from "../../scene";
|
||||
import { isPointHittingElementBoundingBox } from "../../element/collision";
|
||||
import { isLocalLink, normalizeLink } from "../../data/url";
|
||||
import { KEYS } from "../keys";
|
||||
import { DEFAULT_LINK_SIZE } from "../renderer/renderElement";
|
||||
import { rotate } from "../math";
|
||||
import { EVENT, HYPERLINK_TOOLTIP_DELAY, MIME_TYPES } from "../constants";
|
||||
import { Bounds } from "./bounds";
|
||||
import { getTooltipDiv, updateTooltipPosition } from "../components/Tooltip";
|
||||
import { getSelectedElements } from "../scene";
|
||||
import { isPointHittingElementBoundingBox } from "./collision";
|
||||
import { getElementAbsoluteCoords } from ".";
|
||||
import { isLocalLink, normalizeLink } from "../data/url";
|
||||
|
||||
import "./Hyperlink.scss";
|
||||
import { trackEvent } from "../../analytics";
|
||||
import { useAppProps, useExcalidrawAppState } from "../App";
|
||||
import { isEmbeddableElement } from "../../element/typeChecks";
|
||||
import { getLinkHandleFromCoords } from "./helpers";
|
||||
import { trackEvent } from "../analytics";
|
||||
import { useAppProps, useExcalidrawAppState } from "../components/App";
|
||||
import { isEmbeddableElement } from "./typeChecks";
|
||||
|
||||
const CONTAINER_WIDTH = 320;
|
||||
const SPACE_BOTTOM = 85;
|
||||
@@ -43,6 +46,11 @@ const CONTAINER_PADDING = 5;
|
||||
const CONTAINER_HEIGHT = 42;
|
||||
const AUTO_HIDE_TIMEOUT = 500;
|
||||
|
||||
export const EXTERNAL_LINK_IMG = document.createElement("img");
|
||||
EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#1971c2" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-external-link"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>`,
|
||||
)}`;
|
||||
|
||||
let IS_HYPERLINK_TOOLTIP_VISIBLE = false;
|
||||
|
||||
const embeddableLinkCache = new Map<
|
||||
@@ -52,14 +60,12 @@ const embeddableLinkCache = new Map<
|
||||
|
||||
export const Hyperlink = ({
|
||||
element,
|
||||
elementsMap,
|
||||
setAppState,
|
||||
onLinkOpen,
|
||||
setToast,
|
||||
updateEmbedValidationStatus,
|
||||
}: {
|
||||
element: NonDeletedExcalidrawElement;
|
||||
elementsMap: ElementsMap;
|
||||
setAppState: React.Component<any, AppState>["setState"];
|
||||
onLinkOpen: ExcalidrawProps["onLinkOpen"];
|
||||
setToast: (
|
||||
@@ -176,7 +182,7 @@ export const Hyperlink = ({
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
const shouldHide = shouldHideLinkPopup(element, elementsMap, appState, [
|
||||
const shouldHide = shouldHideLinkPopup(element, appState, [
|
||||
event.clientX,
|
||||
event.clientY,
|
||||
]) as boolean;
|
||||
@@ -193,7 +199,7 @@ export const Hyperlink = ({
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
}, [appState, element, isEditing, setAppState, elementsMap]);
|
||||
}, [appState, element, isEditing, setAppState]);
|
||||
|
||||
const handleRemove = useCallback(() => {
|
||||
trackEvent("hyperlink", "delete");
|
||||
@@ -208,7 +214,7 @@ export const Hyperlink = ({
|
||||
trackEvent("hyperlink", "edit", "popup-ui");
|
||||
setAppState({ showHyperlinkPopup: "editor" });
|
||||
};
|
||||
const { x, y } = getCoordsForPopover(element, appState, elementsMap);
|
||||
const { x, y } = getCoordsForPopover(element, appState);
|
||||
if (
|
||||
appState.contextMenu ||
|
||||
appState.draggingElement ||
|
||||
@@ -318,9 +324,8 @@ export const Hyperlink = ({
|
||||
const getCoordsForPopover = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const [x1, y1] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1] = getElementAbsoluteCoords(element);
|
||||
const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
|
||||
{ sceneX: x1 + element.width / 2, sceneY: y1 },
|
||||
appState,
|
||||
@@ -330,6 +335,51 @@ const getCoordsForPopover = (
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
export const actionLink = register({
|
||||
name: "hyperlink",
|
||||
perform: (elements, appState) => {
|
||||
if (appState.showHyperlinkPopup === "editor") {
|
||||
return false;
|
||||
}
|
||||
|
||||
return {
|
||||
elements,
|
||||
appState: {
|
||||
...appState,
|
||||
showHyperlinkPopup: "editor",
|
||||
openMenu: null,
|
||||
},
|
||||
commitToHistory: true,
|
||||
};
|
||||
},
|
||||
trackEvent: { category: "hyperlink", action: "click" },
|
||||
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.K,
|
||||
contextItemLabel: (elements, appState) =>
|
||||
getContextMenuLabel(elements, appState),
|
||||
predicate: (elements, appState) => {
|
||||
const selectedElements = getSelectedElements(elements, appState);
|
||||
return selectedElements.length === 1;
|
||||
},
|
||||
PanelComponent: ({ elements, appState, updateData }) => {
|
||||
const selectedElements = getSelectedElements(elements, appState);
|
||||
|
||||
return (
|
||||
<ToolButton
|
||||
type="button"
|
||||
icon={LinkIcon}
|
||||
aria-label={t(getContextMenuLabel(elements, appState))}
|
||||
title={`${
|
||||
isEmbeddableElement(elements[0])
|
||||
? t("labels.link.labelEmbed")
|
||||
: t("labels.link.label")
|
||||
} - ${getShortcutKey("CtrlOrCmd+K")}`}
|
||||
onClick={() => updateData(null)}
|
||||
selected={selectedElements.length === 1 && !!selectedElements[0].link}
|
||||
/>
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
export const getContextMenuLabel = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
appState: AppState,
|
||||
@@ -345,17 +395,89 @@ export const getContextMenuLabel = (
|
||||
return label;
|
||||
};
|
||||
|
||||
export const getLinkHandleFromCoords = (
|
||||
[x1, y1, x2, y2]: Bounds,
|
||||
angle: number,
|
||||
appState: Pick<UIAppState, "zoom">,
|
||||
): Bounds => {
|
||||
const size = DEFAULT_LINK_SIZE;
|
||||
const linkWidth = size / appState.zoom.value;
|
||||
const linkHeight = size / appState.zoom.value;
|
||||
const linkMarginY = size / appState.zoom.value;
|
||||
const centerX = (x1 + x2) / 2;
|
||||
const centerY = (y1 + y2) / 2;
|
||||
const centeringOffset = (size - 8) / (2 * appState.zoom.value);
|
||||
const dashedLineMargin = 4 / appState.zoom.value;
|
||||
|
||||
// Same as `ne` resize handle
|
||||
const x = x2 + dashedLineMargin - centeringOffset;
|
||||
const y = y1 - dashedLineMargin - linkMarginY + centeringOffset;
|
||||
|
||||
const [rotatedX, rotatedY] = rotate(
|
||||
x + linkWidth / 2,
|
||||
y + linkHeight / 2,
|
||||
centerX,
|
||||
centerY,
|
||||
angle,
|
||||
);
|
||||
return [
|
||||
rotatedX - linkWidth / 2,
|
||||
rotatedY - linkHeight / 2,
|
||||
linkWidth,
|
||||
linkHeight,
|
||||
];
|
||||
};
|
||||
|
||||
export const isPointHittingLinkIcon = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
[x, y]: Point,
|
||||
) => {
|
||||
const threshold = 4 / appState.zoom.value;
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
|
||||
[x1, y1, x2, y2],
|
||||
element.angle,
|
||||
appState,
|
||||
);
|
||||
const hitLink =
|
||||
x > linkX - threshold &&
|
||||
x < linkX + threshold + linkWidth &&
|
||||
y > linkY - threshold &&
|
||||
y < linkY + linkHeight + threshold;
|
||||
return hitLink;
|
||||
};
|
||||
|
||||
export const isPointHittingLink = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
[x, y]: Point,
|
||||
isMobile: boolean,
|
||||
) => {
|
||||
if (!element.link || appState.selectedElementIds[element.id]) {
|
||||
return false;
|
||||
}
|
||||
const threshold = 4 / appState.zoom.value;
|
||||
if (
|
||||
!isMobile &&
|
||||
appState.viewModeEnabled &&
|
||||
isPointHittingElementBoundingBox(element, [x, y], threshold, null)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return isPointHittingLinkIcon(element, appState, [x, y]);
|
||||
};
|
||||
|
||||
let HYPERLINK_TOOLTIP_TIMEOUT_ID: number | null = null;
|
||||
export const showHyperlinkTooltip = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
if (HYPERLINK_TOOLTIP_TIMEOUT_ID) {
|
||||
clearTimeout(HYPERLINK_TOOLTIP_TIMEOUT_ID);
|
||||
}
|
||||
HYPERLINK_TOOLTIP_TIMEOUT_ID = window.setTimeout(
|
||||
() => renderTooltip(element, appState, elementsMap),
|
||||
() => renderTooltip(element, appState),
|
||||
HYPERLINK_TOOLTIP_DELAY,
|
||||
);
|
||||
};
|
||||
@@ -363,7 +485,6 @@ export const showHyperlinkTooltip = (
|
||||
const renderTooltip = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
if (!element.link) {
|
||||
return;
|
||||
@@ -375,7 +496,7 @@ const renderTooltip = (
|
||||
tooltipDiv.style.maxWidth = "20rem";
|
||||
tooltipDiv.textContent = element.link;
|
||||
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
|
||||
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
|
||||
[x1, y1, x2, y2],
|
||||
@@ -412,9 +533,8 @@ export const hideHyperlinkToolip = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const shouldHideLinkPopup = (
|
||||
export const shouldHideLinkPopup = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
appState: AppState,
|
||||
[clientX, clientY]: Point,
|
||||
): Boolean => {
|
||||
@@ -426,17 +546,11 @@ const shouldHideLinkPopup = (
|
||||
const threshold = 15 / appState.zoom.value;
|
||||
// hitbox to prevent hiding when hovered in element bounding box
|
||||
if (
|
||||
isPointHittingElementBoundingBox(
|
||||
element,
|
||||
elementsMap,
|
||||
[sceneX, sceneY],
|
||||
threshold,
|
||||
null,
|
||||
)
|
||||
isPointHittingElementBoundingBox(element, [sceneX, sceneY], threshold, null)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const [x1, y1, x2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2] = getElementAbsoluteCoords(element);
|
||||
// hit box to prevent hiding when hovered in the vertical area between element and popover
|
||||
if (
|
||||
sceneX >= x1 &&
|
||||
@@ -447,11 +561,7 @@ const shouldHideLinkPopup = (
|
||||
return false;
|
||||
}
|
||||
// hit box to prevent hiding when hovered around popover within threshold
|
||||
const { x: popoverX, y: popoverY } = getCoordsForPopover(
|
||||
element,
|
||||
appState,
|
||||
elementsMap,
|
||||
);
|
||||
const { x: popoverX, y: popoverY } = getCoordsForPopover(element, appState);
|
||||
|
||||
if (
|
||||
clientX >= popoverX - threshold &&
|
||||
@@ -5,8 +5,6 @@ import {
|
||||
NonDeletedExcalidrawElement,
|
||||
PointBinding,
|
||||
ExcalidrawElement,
|
||||
ElementsMap,
|
||||
NonDeletedSceneElementsMap,
|
||||
} from "./types";
|
||||
import { getElementAtPosition } from "../scene";
|
||||
import { AppState } from "../types";
|
||||
@@ -68,7 +66,6 @@ export const bindOrUnbindLinearElement = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
startBindingElement: ExcalidrawBindableElement | null | "keep",
|
||||
endBindingElement: ExcalidrawBindableElement | null | "keep",
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
const boundToElementIds: Set<ExcalidrawBindableElement["id"]> = new Set();
|
||||
const unboundFromElementIds: Set<ExcalidrawBindableElement["id"]> = new Set();
|
||||
@@ -79,7 +76,6 @@ export const bindOrUnbindLinearElement = (
|
||||
"start",
|
||||
boundToElementIds,
|
||||
unboundFromElementIds,
|
||||
elementsMap,
|
||||
);
|
||||
bindOrUnbindLinearElementEdge(
|
||||
linearElement,
|
||||
@@ -88,7 +84,6 @@ export const bindOrUnbindLinearElement = (
|
||||
"end",
|
||||
boundToElementIds,
|
||||
unboundFromElementIds,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
const onlyUnbound = Array.from(unboundFromElementIds).filter(
|
||||
@@ -116,7 +111,6 @@ const bindOrUnbindLinearElementEdge = (
|
||||
boundToElementIds: Set<ExcalidrawBindableElement["id"]>,
|
||||
// Is mutated
|
||||
unboundFromElementIds: Set<ExcalidrawBindableElement["id"]>,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
if (bindableElement !== "keep") {
|
||||
if (bindableElement != null) {
|
||||
@@ -133,12 +127,7 @@ const bindOrUnbindLinearElementEdge = (
|
||||
: startOrEnd === "start" ||
|
||||
otherEdgeBindableElement.id !== bindableElement.id)
|
||||
) {
|
||||
bindLinearElement(
|
||||
linearElement,
|
||||
bindableElement,
|
||||
startOrEnd,
|
||||
elementsMap,
|
||||
);
|
||||
bindLinearElement(linearElement, bindableElement, startOrEnd);
|
||||
boundToElementIds.add(bindableElement.id);
|
||||
}
|
||||
} else {
|
||||
@@ -151,48 +140,31 @@ const bindOrUnbindLinearElementEdge = (
|
||||
};
|
||||
|
||||
export const bindOrUnbindSelectedElements = (
|
||||
selectedElements: NonDeleted<ExcalidrawElement>[],
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elements: NonDeleted<ExcalidrawElement>[],
|
||||
): void => {
|
||||
selectedElements.forEach((selectedElement) => {
|
||||
if (isBindingElement(selectedElement)) {
|
||||
elements.forEach((element) => {
|
||||
if (isBindingElement(element)) {
|
||||
bindOrUnbindLinearElement(
|
||||
selectedElement,
|
||||
getElligibleElementForBindingElement(
|
||||
selectedElement,
|
||||
"start",
|
||||
elements,
|
||||
elementsMap,
|
||||
),
|
||||
getElligibleElementForBindingElement(
|
||||
selectedElement,
|
||||
"end",
|
||||
elements,
|
||||
elementsMap,
|
||||
),
|
||||
elementsMap,
|
||||
element,
|
||||
getElligibleElementForBindingElement(element, "start"),
|
||||
getElligibleElementForBindingElement(element, "end"),
|
||||
);
|
||||
} else if (isBindableElement(selectedElement)) {
|
||||
maybeBindBindableElement(selectedElement, elementsMap);
|
||||
} else if (isBindableElement(element)) {
|
||||
maybeBindBindableElement(element);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const maybeBindBindableElement = (
|
||||
bindableElement: NonDeleted<ExcalidrawBindableElement>,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
getElligibleElementsForBindableElementAndWhere(
|
||||
bindableElement,
|
||||
elementsMap,
|
||||
).forEach(([linearElement, where]) =>
|
||||
bindOrUnbindLinearElement(
|
||||
linearElement,
|
||||
where === "end" ? "keep" : bindableElement,
|
||||
where === "start" ? "keep" : bindableElement,
|
||||
elementsMap,
|
||||
),
|
||||
getElligibleElementsForBindableElementAndWhere(bindableElement).forEach(
|
||||
([linearElement, where]) =>
|
||||
bindOrUnbindLinearElement(
|
||||
linearElement,
|
||||
where === "end" ? "keep" : bindableElement,
|
||||
where === "start" ? "keep" : bindableElement,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -201,21 +173,11 @@ export const maybeBindLinearElement = (
|
||||
appState: AppState,
|
||||
scene: Scene,
|
||||
pointerCoords: { x: number; y: number },
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
if (appState.startBoundElement != null) {
|
||||
bindLinearElement(
|
||||
linearElement,
|
||||
appState.startBoundElement,
|
||||
"start",
|
||||
elementsMap,
|
||||
);
|
||||
bindLinearElement(linearElement, appState.startBoundElement, "start");
|
||||
}
|
||||
const hoveredElement = getHoveredElementForBinding(
|
||||
pointerCoords,
|
||||
scene.getNonDeletedElements(),
|
||||
elementsMap,
|
||||
);
|
||||
const hoveredElement = getHoveredElementForBinding(pointerCoords, scene);
|
||||
if (
|
||||
hoveredElement != null &&
|
||||
!isLinearElementSimpleAndAlreadyBoundOnOppositeEdge(
|
||||
@@ -224,7 +186,7 @@ export const maybeBindLinearElement = (
|
||||
"end",
|
||||
)
|
||||
) {
|
||||
bindLinearElement(linearElement, hoveredElement, "end", elementsMap);
|
||||
bindLinearElement(linearElement, hoveredElement, "end");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -232,17 +194,11 @@ export const bindLinearElement = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
hoveredElement: ExcalidrawBindableElement,
|
||||
startOrEnd: "start" | "end",
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
mutateElement(linearElement, {
|
||||
[startOrEnd === "start" ? "startBinding" : "endBinding"]: {
|
||||
elementId: hoveredElement.id,
|
||||
...calculateFocusAndGap(
|
||||
linearElement,
|
||||
hoveredElement,
|
||||
startOrEnd,
|
||||
elementsMap,
|
||||
),
|
||||
...calculateFocusAndGap(linearElement, hoveredElement, startOrEnd),
|
||||
} as PointBinding,
|
||||
});
|
||||
|
||||
@@ -284,11 +240,10 @@ export const isLinearElementSimpleAndAlreadyBound = (
|
||||
|
||||
export const unbindLinearElements = (
|
||||
elements: NonDeleted<ExcalidrawElement>[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): void => {
|
||||
elements.forEach((element) => {
|
||||
if (isBindingElement(element)) {
|
||||
bindOrUnbindLinearElement(element, null, null, elementsMap);
|
||||
bindOrUnbindLinearElement(element, null, null);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -311,14 +266,13 @@ export const getHoveredElementForBinding = (
|
||||
x: number;
|
||||
y: number;
|
||||
},
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
scene: Scene,
|
||||
): NonDeleted<ExcalidrawBindableElement> | null => {
|
||||
const hoveredElement = getElementAtPosition(
|
||||
elements,
|
||||
scene.getNonDeletedElements(),
|
||||
(element) =>
|
||||
isBindableElement(element, false) &&
|
||||
bindingBorderTest(element, pointerCoords, elementsMap),
|
||||
bindingBorderTest(element, pointerCoords),
|
||||
);
|
||||
return hoveredElement as NonDeleted<ExcalidrawBindableElement> | null;
|
||||
};
|
||||
@@ -327,33 +281,21 @@ const calculateFocusAndGap = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
hoveredElement: ExcalidrawBindableElement,
|
||||
startOrEnd: "start" | "end",
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): { focus: number; gap: number } => {
|
||||
const direction = startOrEnd === "start" ? -1 : 1;
|
||||
const edgePointIndex = direction === -1 ? 0 : linearElement.points.length - 1;
|
||||
const adjacentPointIndex = edgePointIndex - direction;
|
||||
|
||||
const edgePoint = LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
linearElement,
|
||||
edgePointIndex,
|
||||
elementsMap,
|
||||
);
|
||||
const adjacentPoint = LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
linearElement,
|
||||
adjacentPointIndex,
|
||||
elementsMap,
|
||||
);
|
||||
return {
|
||||
focus: determineFocusDistance(
|
||||
hoveredElement,
|
||||
adjacentPoint,
|
||||
edgePoint,
|
||||
elementsMap,
|
||||
),
|
||||
gap: Math.max(
|
||||
1,
|
||||
distanceToBindableElement(hoveredElement, edgePoint, elementsMap),
|
||||
),
|
||||
focus: determineFocusDistance(hoveredElement, adjacentPoint, edgePoint),
|
||||
gap: Math.max(1, distanceToBindableElement(hoveredElement, edgePoint)),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -364,8 +306,6 @@ const calculateFocusAndGap = (
|
||||
// in explicitly.
|
||||
export const updateBoundElements = (
|
||||
changedElement: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
|
||||
options?: {
|
||||
simultaneouslyUpdated?: readonly ExcalidrawElement[];
|
||||
newSize?: { width: number; height: number };
|
||||
@@ -415,14 +355,12 @@ export const updateBoundElements = (
|
||||
"start",
|
||||
startBinding,
|
||||
changedElement as ExcalidrawBindableElement,
|
||||
elementsMap,
|
||||
);
|
||||
updateBoundPoint(
|
||||
element,
|
||||
"end",
|
||||
endBinding,
|
||||
changedElement as ExcalidrawBindableElement,
|
||||
elementsMap,
|
||||
);
|
||||
const boundText = getBoundTextElement(
|
||||
element,
|
||||
@@ -455,7 +393,6 @@ const updateBoundPoint = (
|
||||
startOrEnd: "start" | "end",
|
||||
binding: PointBinding | null | undefined,
|
||||
changedElement: ExcalidrawBindableElement,
|
||||
elementsMap: ElementsMap,
|
||||
): void => {
|
||||
if (
|
||||
binding == null ||
|
||||
@@ -477,13 +414,11 @@ const updateBoundPoint = (
|
||||
const adjacentPoint = LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
linearElement,
|
||||
adjacentPointIndex,
|
||||
elementsMap,
|
||||
);
|
||||
const focusPointAbsolute = determineFocusPoint(
|
||||
bindingElement,
|
||||
binding.focus,
|
||||
adjacentPoint,
|
||||
elementsMap,
|
||||
);
|
||||
let newEdgePoint;
|
||||
// The linear element was not originally pointing inside the bound shape,
|
||||
@@ -496,7 +431,6 @@ const updateBoundPoint = (
|
||||
adjacentPoint,
|
||||
focusPointAbsolute,
|
||||
binding.gap,
|
||||
elementsMap,
|
||||
);
|
||||
if (intersections.length === 0) {
|
||||
// This should never happen, since focusPoint should always be
|
||||
@@ -515,7 +449,6 @@ const updateBoundPoint = (
|
||||
point: LinearElementEditor.pointFromAbsoluteCoords(
|
||||
linearElement,
|
||||
newEdgePoint,
|
||||
elementsMap,
|
||||
),
|
||||
},
|
||||
],
|
||||
@@ -546,47 +479,30 @@ const maybeCalculateNewGapWhenScaling = (
|
||||
|
||||
// TODO: this is a bottleneck, optimise
|
||||
export const getEligibleElementsForBinding = (
|
||||
selectedElements: NonDeleted<ExcalidrawElement>[],
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elements: NonDeleted<ExcalidrawElement>[],
|
||||
): SuggestedBinding[] => {
|
||||
const includedElementIds = new Set(selectedElements.map(({ id }) => id));
|
||||
return selectedElements.flatMap((selectedElement) =>
|
||||
isBindingElement(selectedElement, false)
|
||||
const includedElementIds = new Set(elements.map(({ id }) => id));
|
||||
return elements.flatMap((element) =>
|
||||
isBindingElement(element, false)
|
||||
? (getElligibleElementsForBindingElement(
|
||||
selectedElement as NonDeleted<ExcalidrawLinearElement>,
|
||||
elements,
|
||||
elementsMap,
|
||||
element as NonDeleted<ExcalidrawLinearElement>,
|
||||
).filter(
|
||||
(element) => !includedElementIds.has(element.id),
|
||||
) as SuggestedBinding[])
|
||||
: isBindableElement(selectedElement, false)
|
||||
? getElligibleElementsForBindableElementAndWhere(
|
||||
selectedElement,
|
||||
elementsMap,
|
||||
).filter((binding) => !includedElementIds.has(binding[0].id))
|
||||
: isBindableElement(element, false)
|
||||
? getElligibleElementsForBindableElementAndWhere(element).filter(
|
||||
(binding) => !includedElementIds.has(binding[0].id),
|
||||
)
|
||||
: [],
|
||||
);
|
||||
};
|
||||
|
||||
const getElligibleElementsForBindingElement = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): NonDeleted<ExcalidrawBindableElement>[] => {
|
||||
return [
|
||||
getElligibleElementForBindingElement(
|
||||
linearElement,
|
||||
"start",
|
||||
elements,
|
||||
elementsMap,
|
||||
),
|
||||
getElligibleElementForBindingElement(
|
||||
linearElement,
|
||||
"end",
|
||||
elements,
|
||||
elementsMap,
|
||||
),
|
||||
getElligibleElementForBindingElement(linearElement, "start"),
|
||||
getElligibleElementForBindingElement(linearElement, "end"),
|
||||
].filter(
|
||||
(element): element is NonDeleted<ExcalidrawBindableElement> =>
|
||||
element != null,
|
||||
@@ -596,37 +512,27 @@ const getElligibleElementsForBindingElement = (
|
||||
const getElligibleElementForBindingElement = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
startOrEnd: "start" | "end",
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): NonDeleted<ExcalidrawBindableElement> | null => {
|
||||
return getHoveredElementForBinding(
|
||||
getLinearElementEdgeCoors(linearElement, startOrEnd, elementsMap),
|
||||
elements,
|
||||
elementsMap,
|
||||
getLinearElementEdgeCoors(linearElement, startOrEnd),
|
||||
Scene.getScene(linearElement)!,
|
||||
);
|
||||
};
|
||||
|
||||
const getLinearElementEdgeCoors = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
startOrEnd: "start" | "end",
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): { x: number; y: number } => {
|
||||
const index = startOrEnd === "start" ? 0 : -1;
|
||||
return tupleToCoors(
|
||||
LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
linearElement,
|
||||
index,
|
||||
elementsMap,
|
||||
),
|
||||
LinearElementEditor.getPointAtIndexGlobalCoordinates(linearElement, index),
|
||||
);
|
||||
};
|
||||
|
||||
const getElligibleElementsForBindableElementAndWhere = (
|
||||
bindableElement: NonDeleted<ExcalidrawBindableElement>,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): SuggestedPointBinding[] => {
|
||||
const scene = Scene.getScene(bindableElement)!;
|
||||
return scene
|
||||
return Scene.getScene(bindableElement)!
|
||||
.getNonDeletedElements()
|
||||
.map((element) => {
|
||||
if (!isBindingElement(element, false)) {
|
||||
@@ -636,13 +542,11 @@ const getElligibleElementsForBindableElementAndWhere = (
|
||||
element,
|
||||
"start",
|
||||
bindableElement,
|
||||
elementsMap,
|
||||
);
|
||||
const canBindEnd = isLinearElementEligibleForNewBindingByBindable(
|
||||
element,
|
||||
"end",
|
||||
bindableElement,
|
||||
elementsMap,
|
||||
);
|
||||
if (!canBindStart && !canBindEnd) {
|
||||
return null;
|
||||
@@ -660,7 +564,6 @@ const isLinearElementEligibleForNewBindingByBindable = (
|
||||
linearElement: NonDeleted<ExcalidrawLinearElement>,
|
||||
startOrEnd: "start" | "end",
|
||||
bindableElement: NonDeleted<ExcalidrawBindableElement>,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): boolean => {
|
||||
const existingBinding =
|
||||
linearElement[startOrEnd === "start" ? "startBinding" : "endBinding"];
|
||||
@@ -673,8 +576,7 @@ const isLinearElementEligibleForNewBindingByBindable = (
|
||||
) &&
|
||||
bindingBorderTest(
|
||||
bindableElement,
|
||||
getLinearElementEdgeCoors(linearElement, startOrEnd, elementsMap),
|
||||
elementsMap,
|
||||
getLinearElementEdgeCoors(linearElement, startOrEnd),
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { ROUNDNESS } from "../constants";
|
||||
import { arrayToMap } from "../utils";
|
||||
import { getElementAbsoluteCoords, getElementBounds } from "./bounds";
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement } from "./types";
|
||||
|
||||
@@ -36,41 +35,35 @@ const _ce = ({
|
||||
|
||||
describe("getElementAbsoluteCoords", () => {
|
||||
it("test x1 coordinate", () => {
|
||||
const element = _ce({ x: 10, y: 20, w: 10, h: 0 });
|
||||
const [x1] = getElementAbsoluteCoords(element, arrayToMap([element]));
|
||||
const [x1] = getElementAbsoluteCoords(_ce({ x: 10, y: 0, w: 10, h: 0 }));
|
||||
expect(x1).toEqual(10);
|
||||
});
|
||||
|
||||
it("test x2 coordinate", () => {
|
||||
const element = _ce({ x: 10, y: 20, w: 10, h: 0 });
|
||||
const [, , x2] = getElementAbsoluteCoords(element, arrayToMap([element]));
|
||||
const [, , x2] = getElementAbsoluteCoords(
|
||||
_ce({ x: 10, y: 0, w: 10, h: 0 }),
|
||||
);
|
||||
expect(x2).toEqual(20);
|
||||
});
|
||||
|
||||
it("test y1 coordinate", () => {
|
||||
const element = _ce({ x: 0, y: 10, w: 0, h: 10 });
|
||||
const [, y1] = getElementAbsoluteCoords(element, arrayToMap([element]));
|
||||
const [, y1] = getElementAbsoluteCoords(_ce({ x: 0, y: 10, w: 0, h: 10 }));
|
||||
expect(y1).toEqual(10);
|
||||
});
|
||||
|
||||
it("test y2 coordinate", () => {
|
||||
const element = _ce({ x: 0, y: 10, w: 0, h: 10 });
|
||||
const [, , , y2] = getElementAbsoluteCoords(element, arrayToMap([element]));
|
||||
const [, , , y2] = getElementAbsoluteCoords(
|
||||
_ce({ x: 0, y: 10, w: 0, h: 10 }),
|
||||
);
|
||||
expect(y2).toEqual(20);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getElementBounds", () => {
|
||||
it("rectangle", () => {
|
||||
const element = _ce({
|
||||
x: 40,
|
||||
y: 30,
|
||||
w: 20,
|
||||
h: 10,
|
||||
a: Math.PI / 4,
|
||||
t: "rectangle",
|
||||
});
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
|
||||
const [x1, y1, x2, y2] = getElementBounds(
|
||||
_ce({ x: 40, y: 30, w: 20, h: 10, a: Math.PI / 4, t: "rectangle" }),
|
||||
);
|
||||
expect(x1).toEqual(39.39339828220179);
|
||||
expect(y1).toEqual(24.393398282201787);
|
||||
expect(x2).toEqual(60.60660171779821);
|
||||
@@ -78,17 +71,9 @@ describe("getElementBounds", () => {
|
||||
});
|
||||
|
||||
it("diamond", () => {
|
||||
const element = _ce({
|
||||
x: 40,
|
||||
y: 30,
|
||||
w: 20,
|
||||
h: 10,
|
||||
a: Math.PI / 4,
|
||||
t: "diamond",
|
||||
});
|
||||
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
|
||||
|
||||
const [x1, y1, x2, y2] = getElementBounds(
|
||||
_ce({ x: 40, y: 30, w: 20, h: 10, a: Math.PI / 4, t: "diamond" }),
|
||||
);
|
||||
expect(x1).toEqual(42.928932188134524);
|
||||
expect(y1).toEqual(27.928932188134524);
|
||||
expect(x2).toEqual(57.071067811865476);
|
||||
@@ -96,16 +81,9 @@ describe("getElementBounds", () => {
|
||||
});
|
||||
|
||||
it("ellipse", () => {
|
||||
const element = _ce({
|
||||
x: 40,
|
||||
y: 30,
|
||||
w: 20,
|
||||
h: 10,
|
||||
a: Math.PI / 4,
|
||||
t: "ellipse",
|
||||
});
|
||||
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
|
||||
const [x1, y1, x2, y2] = getElementBounds(
|
||||
_ce({ x: 40, y: 30, w: 20, h: 10, a: Math.PI / 4, t: "ellipse" }),
|
||||
);
|
||||
expect(x1).toEqual(42.09430584957905);
|
||||
expect(y1).toEqual(27.09430584957905);
|
||||
expect(x2).toEqual(57.90569415042095);
|
||||
@@ -113,7 +91,7 @@ describe("getElementBounds", () => {
|
||||
});
|
||||
|
||||
it("curved line", () => {
|
||||
const element = {
|
||||
const [x1, y1, x2, y2] = getElementBounds({
|
||||
..._ce({
|
||||
t: "line",
|
||||
x: 449.58203125,
|
||||
@@ -127,9 +105,7 @@ describe("getElementBounds", () => {
|
||||
[67.33984375, 92.48828125] as [number, number],
|
||||
[-102.7890625, 52.15625] as [number, number],
|
||||
],
|
||||
} as ExcalidrawLinearElement;
|
||||
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, arrayToMap([element]));
|
||||
} as ExcalidrawLinearElement);
|
||||
expect(x1).toEqual(360.3176068760539);
|
||||
expect(y1).toEqual(185.90654264413516);
|
||||
expect(x2).toEqual(480.87005902729743);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
ExcalidrawFreeDrawElement,
|
||||
NonDeleted,
|
||||
ExcalidrawTextElementWithContainer,
|
||||
ElementsMapOrArray,
|
||||
ElementsMap,
|
||||
} from "./types";
|
||||
import { distance2d, rotate, rotatePoint } from "../math";
|
||||
@@ -24,7 +25,7 @@ import { getBoundTextElement, getContainerElement } from "./textElement";
|
||||
import { LinearElementEditor } from "./linearElementEditor";
|
||||
import { Mutable } from "../utility-types";
|
||||
import { ShapeCache } from "../scene/ShapeCache";
|
||||
import { arrayToMap } from "../utils";
|
||||
import Scene from "../scene/Scene";
|
||||
|
||||
export type RectangleBox = {
|
||||
x: number;
|
||||
@@ -62,7 +63,7 @@ export class ElementBounds {
|
||||
}
|
||||
>();
|
||||
|
||||
static getBounds(element: ExcalidrawElement, elementsMap: ElementsMap) {
|
||||
static getBounds(element: ExcalidrawElement) {
|
||||
const cachedBounds = ElementBounds.boundsCache.get(element);
|
||||
|
||||
if (
|
||||
@@ -74,12 +75,23 @@ export class ElementBounds {
|
||||
) {
|
||||
return cachedBounds.bounds;
|
||||
}
|
||||
const bounds = ElementBounds.calculateBounds(element, elementsMap);
|
||||
const scene = Scene.getScene(element);
|
||||
const bounds = ElementBounds.calculateBounds(
|
||||
element,
|
||||
scene?.getNonDeletedElementsMap() || new Map(),
|
||||
);
|
||||
|
||||
ElementBounds.boundsCache.set(element, {
|
||||
version: element.version,
|
||||
bounds,
|
||||
});
|
||||
// hack to ensure that downstream checks could retrieve element Scene
|
||||
// so as to have correctly calculated bounds
|
||||
// FIXME remove when we get rid of all the id:Scene / element:Scene mapping
|
||||
const shouldCache = !!scene;
|
||||
|
||||
if (shouldCache) {
|
||||
ElementBounds.boundsCache.set(element, {
|
||||
version: element.version,
|
||||
bounds,
|
||||
});
|
||||
}
|
||||
|
||||
return bounds;
|
||||
}
|
||||
@@ -90,10 +102,8 @@ export class ElementBounds {
|
||||
): Bounds {
|
||||
let bounds: Bounds;
|
||||
|
||||
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(element);
|
||||
|
||||
if (isFreeDrawElement(element)) {
|
||||
const [minX, minY, maxX, maxY] = getBoundsFromPoints(
|
||||
element.points.map(([x, y]) =>
|
||||
@@ -149,9 +159,10 @@ export class ElementBounds {
|
||||
// This set of functions retrieves the absolute position of the 4 points.
|
||||
export const getElementAbsoluteCoords = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
includeBoundText: boolean = false,
|
||||
): [number, number, number, number, number, number] => {
|
||||
const elementsMap =
|
||||
Scene.getScene(element)?.getElementsMapIncludingDeleted() || new Map();
|
||||
if (isFreeDrawElement(element)) {
|
||||
return getFreeDrawElementAbsoluteCoords(element);
|
||||
} else if (isLinearElement(element)) {
|
||||
@@ -168,7 +179,6 @@ export const getElementAbsoluteCoords = (
|
||||
const coords = LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
element as ExcalidrawTextElementWithContainer,
|
||||
elementsMap,
|
||||
);
|
||||
return [
|
||||
coords.x,
|
||||
@@ -197,12 +207,8 @@ export const getElementAbsoluteCoords = (
|
||||
*/
|
||||
export const getElementLineSegments = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
): [Point, Point][] => {
|
||||
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(element);
|
||||
|
||||
const center: Point = [cx, cy];
|
||||
|
||||
@@ -697,7 +703,6 @@ const getLinearElementRotatedBounds = (
|
||||
if (boundTextElement) {
|
||||
const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText(
|
||||
element,
|
||||
elementsMap,
|
||||
[x, y, x, y],
|
||||
boundTextElement,
|
||||
);
|
||||
@@ -722,7 +727,6 @@ const getLinearElementRotatedBounds = (
|
||||
if (boundTextElement) {
|
||||
const coordsWithBoundText = LinearElementEditor.getMinMaxXYWithBoundText(
|
||||
element,
|
||||
elementsMap,
|
||||
coords,
|
||||
boundTextElement,
|
||||
);
|
||||
@@ -736,17 +740,11 @@ const getLinearElementRotatedBounds = (
|
||||
return coords;
|
||||
};
|
||||
|
||||
export const getElementBounds = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
): Bounds => {
|
||||
return ElementBounds.getBounds(element, elementsMap);
|
||||
export const getElementBounds = (element: ExcalidrawElement): Bounds => {
|
||||
return ElementBounds.getBounds(element);
|
||||
};
|
||||
|
||||
export const getCommonBounds = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
): Bounds => {
|
||||
if (!elements.length) {
|
||||
export const getCommonBounds = (elements: ElementsMapOrArray): Bounds => {
|
||||
if ("size" in elements ? !elements.size : !elements.length) {
|
||||
return [0, 0, 0, 0];
|
||||
}
|
||||
|
||||
@@ -755,10 +753,8 @@ export const getCommonBounds = (
|
||||
let minY = Infinity;
|
||||
let maxY = -Infinity;
|
||||
|
||||
const elementsMap = arrayToMap(elements);
|
||||
|
||||
elements.forEach((element) => {
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementBounds(element);
|
||||
minX = Math.min(minX, x1);
|
||||
minY = Math.min(minY, y1);
|
||||
maxX = Math.max(maxX, x2);
|
||||
@@ -864,9 +860,9 @@ export const getClosestElementBounds = (
|
||||
|
||||
let minDistance = Infinity;
|
||||
let closestElement = elements[0];
|
||||
const elementsMap = arrayToMap(elements);
|
||||
|
||||
elements.forEach((element) => {
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementBounds(element);
|
||||
const distance = distance2d((x1 + x2) / 2, (y1 + y2) / 2, from.x, from.y);
|
||||
|
||||
if (distance < minDistance) {
|
||||
@@ -875,7 +871,7 @@ export const getClosestElementBounds = (
|
||||
}
|
||||
});
|
||||
|
||||
return getElementBounds(closestElement, elementsMap);
|
||||
return getElementBounds(closestElement);
|
||||
};
|
||||
|
||||
export interface BoundingBox {
|
||||
|
||||
@@ -91,7 +91,6 @@ export const hitTest = (
|
||||
) {
|
||||
return isPointHittingElementBoundingBox(
|
||||
element,
|
||||
elementsMap,
|
||||
point,
|
||||
threshold,
|
||||
frameNameBoundsCache,
|
||||
@@ -117,7 +116,6 @@ export const hitTest = (
|
||||
appState,
|
||||
frameNameBoundsCache,
|
||||
point,
|
||||
elementsMap,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -147,11 +145,9 @@ export const isHittingElementBoundingBoxWithoutHittingElement = (
|
||||
appState,
|
||||
frameNameBoundsCache,
|
||||
[x, y],
|
||||
elementsMap,
|
||||
) &&
|
||||
isPointHittingElementBoundingBox(
|
||||
element,
|
||||
elementsMap,
|
||||
[x, y],
|
||||
threshold,
|
||||
frameNameBoundsCache,
|
||||
@@ -164,7 +160,6 @@ export const isHittingElementNotConsideringBoundingBox = (
|
||||
appState: AppState,
|
||||
frameNameBoundsCache: FrameNameBoundsCache | null,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): boolean => {
|
||||
const threshold = 10 / appState.zoom.value;
|
||||
const check = isTextElement(element)
|
||||
@@ -174,7 +169,6 @@ export const isHittingElementNotConsideringBoundingBox = (
|
||||
: isNearCheck;
|
||||
return hitTestPointAgainstElement({
|
||||
element,
|
||||
elementsMap,
|
||||
point,
|
||||
threshold,
|
||||
check,
|
||||
@@ -189,7 +183,6 @@ const isElementSelected = (
|
||||
|
||||
export const isPointHittingElementBoundingBox = (
|
||||
element: NonDeleted<ExcalidrawElement>,
|
||||
elementsMap: ElementsMap,
|
||||
[x, y]: Point,
|
||||
threshold: number,
|
||||
frameNameBoundsCache: FrameNameBoundsCache | null,
|
||||
@@ -201,7 +194,6 @@ export const isPointHittingElementBoundingBox = (
|
||||
if (isFrameLikeElement(element)) {
|
||||
return hitTestPointAgainstElement({
|
||||
element,
|
||||
elementsMap,
|
||||
point: [x, y],
|
||||
threshold,
|
||||
check: isInsideCheck,
|
||||
@@ -209,7 +201,7 @@ export const isPointHittingElementBoundingBox = (
|
||||
});
|
||||
}
|
||||
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const elementCenterX = (x1 + x2) / 2;
|
||||
const elementCenterY = (y1 + y2) / 2;
|
||||
// reverse rotate to take element's angle into account.
|
||||
@@ -232,14 +224,12 @@ export const isPointHittingElementBoundingBox = (
|
||||
export const bindingBorderTest = (
|
||||
element: NonDeleted<ExcalidrawBindableElement>,
|
||||
{ x, y }: { x: number; y: number },
|
||||
elementsMap: ElementsMap,
|
||||
): boolean => {
|
||||
const threshold = maxBindingGap(element, element.width, element.height);
|
||||
const check = isOutsideCheck;
|
||||
const point: Point = [x, y];
|
||||
return hitTestPointAgainstElement({
|
||||
element,
|
||||
elementsMap,
|
||||
point,
|
||||
threshold,
|
||||
check,
|
||||
@@ -261,7 +251,6 @@ export const maxBindingGap = (
|
||||
|
||||
type HitTestArgs = {
|
||||
element: NonDeletedExcalidrawElement;
|
||||
elementsMap: ElementsMap;
|
||||
point: Point;
|
||||
threshold: number;
|
||||
check: (distance: number, threshold: number) => boolean;
|
||||
@@ -277,28 +266,19 @@ const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
|
||||
case "text":
|
||||
case "diamond":
|
||||
case "ellipse":
|
||||
const distance = distanceToBindableElement(
|
||||
args.element,
|
||||
args.point,
|
||||
args.elementsMap,
|
||||
);
|
||||
const distance = distanceToBindableElement(args.element, args.point);
|
||||
return args.check(distance, args.threshold);
|
||||
case "freedraw": {
|
||||
if (
|
||||
!args.check(
|
||||
distanceToRectangle(args.element, args.point, args.elementsMap),
|
||||
distanceToRectangle(args.element, args.point),
|
||||
args.threshold,
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hitTestFreeDrawElement(
|
||||
args.element,
|
||||
args.point,
|
||||
args.threshold,
|
||||
args.elementsMap,
|
||||
);
|
||||
return hitTestFreeDrawElement(args.element, args.point, args.threshold);
|
||||
}
|
||||
case "arrow":
|
||||
case "line":
|
||||
@@ -313,7 +293,7 @@ const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
|
||||
// check distance to frame element first
|
||||
if (
|
||||
args.check(
|
||||
distanceToBindableElement(args.element, args.point, args.elementsMap),
|
||||
distanceToBindableElement(args.element, args.point),
|
||||
args.threshold,
|
||||
)
|
||||
) {
|
||||
@@ -336,7 +316,6 @@ const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
|
||||
export const distanceToBindableElement = (
|
||||
element: ExcalidrawBindableElement,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): number => {
|
||||
switch (element.type) {
|
||||
case "rectangle":
|
||||
@@ -346,11 +325,11 @@ export const distanceToBindableElement = (
|
||||
case "embeddable":
|
||||
case "frame":
|
||||
case "magicframe":
|
||||
return distanceToRectangle(element, point, elementsMap);
|
||||
return distanceToRectangle(element, point);
|
||||
case "diamond":
|
||||
return distanceToDiamond(element, point, elementsMap);
|
||||
return distanceToDiamond(element, point);
|
||||
case "ellipse":
|
||||
return distanceToEllipse(element, point, elementsMap);
|
||||
return distanceToEllipse(element, point);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -379,13 +358,8 @@ const distanceToRectangle = (
|
||||
| ExcalidrawIframeLikeElement
|
||||
| ExcalidrawFrameLikeElement,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): number => {
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(
|
||||
element,
|
||||
point,
|
||||
elementsMap,
|
||||
);
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
|
||||
return Math.max(
|
||||
GAPoint.distanceToLine(pointRel, GALine.equation(0, 1, -hheight)),
|
||||
GAPoint.distanceToLine(pointRel, GALine.equation(1, 0, -hwidth)),
|
||||
@@ -403,13 +377,8 @@ const distanceToRectangleBox = (box: RectangleBox, point: Point): number => {
|
||||
const distanceToDiamond = (
|
||||
element: ExcalidrawDiamondElement,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): number => {
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(
|
||||
element,
|
||||
point,
|
||||
elementsMap,
|
||||
);
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
|
||||
const side = GALine.equation(hheight, hwidth, -hheight * hwidth);
|
||||
return GAPoint.distanceToLine(pointRel, side);
|
||||
};
|
||||
@@ -417,22 +386,16 @@ const distanceToDiamond = (
|
||||
const distanceToEllipse = (
|
||||
element: ExcalidrawEllipseElement,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): number => {
|
||||
const [pointRel, tangent] = ellipseParamsForTest(element, point, elementsMap);
|
||||
const [pointRel, tangent] = ellipseParamsForTest(element, point);
|
||||
return -GALine.sign(tangent) * GAPoint.distanceToLine(pointRel, tangent);
|
||||
};
|
||||
|
||||
const ellipseParamsForTest = (
|
||||
element: ExcalidrawEllipseElement,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): [GA.Point, GA.Line] => {
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(
|
||||
element,
|
||||
point,
|
||||
elementsMap,
|
||||
);
|
||||
const [, pointRel, hwidth, hheight] = pointRelativeToElement(element, point);
|
||||
const [px, py] = GAPoint.toTuple(pointRel);
|
||||
|
||||
// We're working in positive quadrant, so start with `t = 45deg`, `tx=cos(t)`
|
||||
@@ -477,7 +440,6 @@ const hitTestFreeDrawElement = (
|
||||
element: ExcalidrawFreeDrawElement,
|
||||
point: Point,
|
||||
threshold: number,
|
||||
elementsMap: ElementsMap,
|
||||
): boolean => {
|
||||
// Check point-distance-to-line-segment for every segment in the
|
||||
// element's points (its input points, not its outline points).
|
||||
@@ -492,10 +454,7 @@ const hitTestFreeDrawElement = (
|
||||
y = point[1] - element.y;
|
||||
} else {
|
||||
// Counter-rotate the point around center before testing
|
||||
const [minX, minY, maxX, maxY] = getElementAbsoluteCoords(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const [minX, minY, maxX, maxY] = getElementAbsoluteCoords(element);
|
||||
const rotatedPoint = rotatePoint(
|
||||
point,
|
||||
[minX + (maxX - minX) / 2, minY + (maxY - minY) / 2],
|
||||
@@ -561,7 +520,6 @@ const hitTestLinear = (args: HitTestArgs): boolean => {
|
||||
const [point, pointAbs, hwidth, hheight] = pointRelativeToElement(
|
||||
args.element,
|
||||
args.point,
|
||||
args.elementsMap,
|
||||
);
|
||||
const side1 = GALine.equation(0, 1, -hheight);
|
||||
const side2 = GALine.equation(1, 0, -hwidth);
|
||||
@@ -614,10 +572,9 @@ const hitTestLinear = (args: HitTestArgs): boolean => {
|
||||
const pointRelativeToElement = (
|
||||
element: ExcalidrawElement,
|
||||
pointTuple: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): [GA.Point, GA.Point, number, number] => {
|
||||
const point = GAPoint.from(pointTuple);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const center = coordsCenter(x1, y1, x2, y2);
|
||||
// GA has angle orientation opposite to `rotate`
|
||||
const rotate = GATransform.rotation(center, element.angle);
|
||||
@@ -652,12 +609,11 @@ const pointRelativeToDivElement = (
|
||||
// Returns point in absolute coordinates
|
||||
export const pointInAbsoluteCoords = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
// Point relative to the element position
|
||||
point: Point,
|
||||
): Point => {
|
||||
const [x, y] = point;
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x2 - x1) / 2;
|
||||
const cy = (y2 - y1) / 2;
|
||||
const [rotatedX, rotatedY] = rotate(x, y, cx, cy, element.angle);
|
||||
@@ -666,9 +622,8 @@ export const pointInAbsoluteCoords = (
|
||||
|
||||
const relativizationToElementCenter = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
): GA.Transform => {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const center = coordsCenter(x1, y1, x2, y2);
|
||||
// GA has angle orientation opposite to `rotate`
|
||||
const rotate = GATransform.rotation(center, element.angle);
|
||||
@@ -694,14 +649,12 @@ const coordsCenter = (
|
||||
// of the element.
|
||||
export const determineFocusDistance = (
|
||||
element: ExcalidrawBindableElement,
|
||||
|
||||
// Point on the line, in absolute coordinates
|
||||
a: Point,
|
||||
// Another point on the line, in absolute coordinates (closer to element)
|
||||
b: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): number => {
|
||||
const relateToCenter = relativizationToElementCenter(element, elementsMap);
|
||||
const relateToCenter = relativizationToElementCenter(element);
|
||||
const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
|
||||
const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
|
||||
const line = GALine.through(aRel, bRel);
|
||||
@@ -740,14 +693,13 @@ export const determineFocusPoint = (
|
||||
// returned focusPoint
|
||||
focus: number,
|
||||
adjecentPoint: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): Point => {
|
||||
if (focus === 0) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const center = coordsCenter(x1, y1, x2, y2);
|
||||
return GAPoint.toTuple(center);
|
||||
}
|
||||
const relateToCenter = relativizationToElementCenter(element, elementsMap);
|
||||
const relateToCenter = relativizationToElementCenter(element);
|
||||
const adjecentPointRel = GATransform.apply(
|
||||
relateToCenter,
|
||||
GAPoint.from(adjecentPoint),
|
||||
@@ -776,16 +728,14 @@ export const determineFocusPoint = (
|
||||
// and the `element`, in ascending order of distance from `a`.
|
||||
export const intersectElementWithLine = (
|
||||
element: ExcalidrawBindableElement,
|
||||
|
||||
// Point on the line, in absolute coordinates
|
||||
a: Point,
|
||||
// Another point on the line, in absolute coordinates
|
||||
b: Point,
|
||||
// If given, the element is inflated by this value
|
||||
gap: number = 0,
|
||||
elementsMap: ElementsMap,
|
||||
): Point[] => {
|
||||
const relateToCenter = relativizationToElementCenter(element, elementsMap);
|
||||
const relateToCenter = relativizationToElementCenter(element);
|
||||
const aRel = GATransform.apply(relateToCenter, GAPoint.from(a));
|
||||
const bRel = GATransform.apply(relateToCenter, GAPoint.from(b));
|
||||
const line = GALine.through(aRel, bRel);
|
||||
|
||||
@@ -65,7 +65,7 @@ export const dragSelectedElements = (
|
||||
updateElementCoords(pointerDownState, textElement, adjustedOffset);
|
||||
}
|
||||
}
|
||||
updateBoundElements(element, scene.getElementsMapIncludingDeleted(), {
|
||||
updateBoundElements(element, {
|
||||
simultaneouslyUpdated: Array.from(elementsToUpdate),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
import { MIME_TYPES, SVG_NS } from "../constants";
|
||||
import { t } from "../i18n";
|
||||
import { AppClassProperties, DataURL, BinaryFiles } from "../types";
|
||||
import { isInitializedImageElement } from "./typeChecks";
|
||||
import {
|
||||
@@ -99,7 +100,7 @@ export const normalizeSVG = async (SVGString: string) => {
|
||||
const svg = doc.querySelector("svg");
|
||||
const errorNode = doc.querySelector("parsererror");
|
||||
if (errorNode || !isHTMLSVGElement(svg)) {
|
||||
throw new Error("Invalid SVG");
|
||||
throw new Error(t("errors.invalidSVGString"));
|
||||
} else {
|
||||
if (!svg.hasAttribute("xmlns")) {
|
||||
svg.setAttribute("xmlns", SVG_NS);
|
||||
|
||||
@@ -60,36 +60,9 @@ export {
|
||||
} from "./sizeHelpers";
|
||||
export { showSelectedShapeActions } from "./showSelectedShapeActions";
|
||||
|
||||
/**
|
||||
* @deprecated unsafe, use hashElementsVersion instead
|
||||
*/
|
||||
export const getSceneVersion = (elements: readonly ExcalidrawElement[]) =>
|
||||
elements.reduce((acc, el) => acc + el.version, 0);
|
||||
|
||||
/**
|
||||
* Hashes elements' versionNonce (using djb2 algo). Order of elements matters.
|
||||
*/
|
||||
export const hashElementsVersion = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
): number => {
|
||||
let hash = 5381;
|
||||
for (let i = 0; i < elements.length; i++) {
|
||||
hash = (hash << 5) + hash + elements[i].versionNonce;
|
||||
}
|
||||
return hash >>> 0; // Ensure unsigned 32-bit integer
|
||||
};
|
||||
|
||||
// string hash function (using djb2). Not cryptographically secure, use only
|
||||
// for versioning and such.
|
||||
export const hashString = (s: string): number => {
|
||||
let hash: number = 5381;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const char: number = s.charCodeAt(i);
|
||||
hash = (hash << 5) + hash + char;
|
||||
}
|
||||
return hash >>> 0; // Ensure unsigned 32-bit integer
|
||||
};
|
||||
|
||||
export const getVisibleElements = (elements: readonly ExcalidrawElement[]) =>
|
||||
elements.filter(
|
||||
(el) => !el.isDeleted && !isInvisiblySmallElement(el),
|
||||
|
||||
@@ -6,8 +6,6 @@ import {
|
||||
ExcalidrawBindableElement,
|
||||
ExcalidrawTextElementWithContainer,
|
||||
ElementsMap,
|
||||
NonDeletedExcalidrawElement,
|
||||
NonDeletedSceneElementsMap,
|
||||
} from "./types";
|
||||
import {
|
||||
distance2d,
|
||||
@@ -38,6 +36,7 @@ import {
|
||||
import { mutateElement } from "./mutateElement";
|
||||
import History from "../history";
|
||||
|
||||
import Scene from "../scene/Scene";
|
||||
import {
|
||||
bindOrUnbindLinearElement,
|
||||
getHoveredElementForBinding,
|
||||
@@ -87,10 +86,11 @@ export class LinearElementEditor {
|
||||
public readonly hoverPointIndex: number;
|
||||
public readonly segmentMidPointHoveredCoords: Point | null;
|
||||
|
||||
constructor(element: NonDeleted<ExcalidrawLinearElement>) {
|
||||
constructor(element: NonDeleted<ExcalidrawLinearElement>, scene: Scene) {
|
||||
this.elementId = element.id as string & {
|
||||
_brand: "excalidrawLinearElementId";
|
||||
};
|
||||
Scene.mapElementToScene(this.elementId, scene);
|
||||
LinearElementEditor.normalizePoints(element);
|
||||
|
||||
this.selectedPointsIndices = null;
|
||||
@@ -123,11 +123,8 @@ export class LinearElementEditor {
|
||||
* @param id the `elementId` from the instance of this class (so that we can
|
||||
* statically guarantee this method returns an ExcalidrawLinearElement)
|
||||
*/
|
||||
static getElement(
|
||||
id: InstanceType<typeof LinearElementEditor>["elementId"],
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
const element = elementsMap.get(id);
|
||||
static getElement(id: InstanceType<typeof LinearElementEditor>["elementId"]) {
|
||||
const element = Scene.getScene(id)?.getNonDeletedElement(id);
|
||||
if (element) {
|
||||
return element as NonDeleted<ExcalidrawLinearElement>;
|
||||
}
|
||||
@@ -138,7 +135,6 @@ export class LinearElementEditor {
|
||||
event: PointerEvent,
|
||||
appState: AppState,
|
||||
setState: React.Component<any, AppState>["setState"],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
) {
|
||||
if (
|
||||
!appState.editingLinearElement ||
|
||||
@@ -149,18 +145,16 @@ export class LinearElementEditor {
|
||||
const { editingLinearElement } = appState;
|
||||
const { selectedPointsIndices, elementId } = editingLinearElement;
|
||||
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const [selectionX1, selectionY1, selectionX2, selectionY2] =
|
||||
getElementAbsoluteCoords(appState.draggingElement, elementsMap);
|
||||
getElementAbsoluteCoords(appState.draggingElement);
|
||||
|
||||
const pointsSceneCoords = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const pointsSceneCoords =
|
||||
LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||
|
||||
const nextSelectedPoints = pointsSceneCoords.reduce(
|
||||
(acc: number[], point, index) => {
|
||||
@@ -200,13 +194,13 @@ export class LinearElementEditor {
|
||||
pointSceneCoords: { x: number; y: number }[],
|
||||
) => void,
|
||||
linearElementEditor: LinearElementEditor,
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elementsMap: ElementsMap,
|
||||
): boolean {
|
||||
if (!linearElementEditor) {
|
||||
return false;
|
||||
}
|
||||
const { selectedPointsIndices, elementId } = linearElementEditor;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return false;
|
||||
}
|
||||
@@ -228,7 +222,6 @@ export class LinearElementEditor {
|
||||
|
||||
const [width, height] = LinearElementEditor._getShiftLockedDelta(
|
||||
element,
|
||||
elementsMap,
|
||||
referencePoint,
|
||||
[scenePointerX, scenePointerY],
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -246,7 +239,6 @@ export class LinearElementEditor {
|
||||
} else {
|
||||
const newDraggingPointPosition = LinearElementEditor.createPointAt(
|
||||
element,
|
||||
elementsMap,
|
||||
scenePointerX - linearElementEditor.pointerOffset.x,
|
||||
scenePointerY - linearElementEditor.pointerOffset.y,
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -263,7 +255,6 @@ export class LinearElementEditor {
|
||||
linearElementEditor.pointerDownState.lastClickedPoint
|
||||
? LinearElementEditor.createPointAt(
|
||||
element,
|
||||
elementsMap,
|
||||
scenePointerX - linearElementEditor.pointerOffset.x,
|
||||
scenePointerY - linearElementEditor.pointerOffset.y,
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -299,7 +290,6 @@ export class LinearElementEditor {
|
||||
LinearElementEditor.getPointGlobalCoordinates(
|
||||
element,
|
||||
element.points[0],
|
||||
elementsMap,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -313,7 +303,6 @@ export class LinearElementEditor {
|
||||
LinearElementEditor.getPointGlobalCoordinates(
|
||||
element,
|
||||
element.points[lastSelectedIndex],
|
||||
elementsMap,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -334,12 +323,10 @@ export class LinearElementEditor {
|
||||
event: PointerEvent,
|
||||
editingLinearElement: LinearElementEditor,
|
||||
appState: AppState,
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
): LinearElementEditor {
|
||||
const { elementId, selectedPointsIndices, isDragging, pointerDownState } =
|
||||
editingLinearElement;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return editingLinearElement;
|
||||
}
|
||||
@@ -377,11 +364,9 @@ export class LinearElementEditor {
|
||||
LinearElementEditor.getPointAtIndexGlobalCoordinates(
|
||||
element,
|
||||
selectedPoint!,
|
||||
elementsMap,
|
||||
),
|
||||
),
|
||||
elements,
|
||||
elementsMap,
|
||||
Scene.getScene(element)!,
|
||||
)
|
||||
: null;
|
||||
|
||||
@@ -440,23 +425,15 @@ export class LinearElementEditor {
|
||||
) {
|
||||
return editorMidPointsCache.points;
|
||||
}
|
||||
LinearElementEditor.updateEditorMidPointsCache(
|
||||
element,
|
||||
elementsMap,
|
||||
appState,
|
||||
);
|
||||
LinearElementEditor.updateEditorMidPointsCache(element, appState);
|
||||
return editorMidPointsCache.points!;
|
||||
};
|
||||
|
||||
static updateEditorMidPointsCache = (
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
elementsMap: ElementsMap,
|
||||
appState: InteractiveCanvasAppState,
|
||||
) => {
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||
|
||||
let index = 0;
|
||||
const midpoints: (Point | null)[] = [];
|
||||
@@ -478,7 +455,6 @@ export class LinearElementEditor {
|
||||
points[index],
|
||||
points[index + 1],
|
||||
index + 1,
|
||||
elementsMap,
|
||||
);
|
||||
midpoints.push(segmentMidPoint);
|
||||
index++;
|
||||
@@ -495,13 +471,12 @@ export class LinearElementEditor {
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const { elementId } = linearElementEditor;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
|
||||
element,
|
||||
elementsMap,
|
||||
appState.zoom,
|
||||
scenePointer.x,
|
||||
scenePointer.y,
|
||||
@@ -509,10 +484,7 @@ export class LinearElementEditor {
|
||||
if (clickedPointIndex >= 0) {
|
||||
return null;
|
||||
}
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||
if (points.length >= 3 && !appState.editingLinearElement) {
|
||||
return null;
|
||||
}
|
||||
@@ -578,7 +550,6 @@ export class LinearElementEditor {
|
||||
startPoint: Point,
|
||||
endPoint: Point,
|
||||
endPointIndex: number,
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
let segmentMidPoint = centerPoint(startPoint, endPoint);
|
||||
if (element.points.length > 2 && element.roundness) {
|
||||
@@ -603,7 +574,6 @@ export class LinearElementEditor {
|
||||
segmentMidPoint = LinearElementEditor.getPointGlobalCoordinates(
|
||||
element,
|
||||
[tx, ty],
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -619,7 +589,6 @@ export class LinearElementEditor {
|
||||
) {
|
||||
const element = LinearElementEditor.getElement(
|
||||
linearElementEditor.elementId,
|
||||
elementsMap,
|
||||
);
|
||||
if (!element) {
|
||||
return -1;
|
||||
@@ -645,8 +614,7 @@ export class LinearElementEditor {
|
||||
history: History,
|
||||
scenePointer: { x: number; y: number },
|
||||
linearElementEditor: LinearElementEditor,
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
elementsMap: NonDeletedSceneElementsMap,
|
||||
elementsMap: ElementsMap,
|
||||
): {
|
||||
didAddPoint: boolean;
|
||||
hitElement: NonDeleted<ExcalidrawElement> | null;
|
||||
@@ -663,7 +631,7 @@ export class LinearElementEditor {
|
||||
}
|
||||
|
||||
const { elementId } = linearElementEditor;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
|
||||
if (!element) {
|
||||
return ret;
|
||||
@@ -690,7 +658,6 @@ export class LinearElementEditor {
|
||||
...element.points,
|
||||
LinearElementEditor.createPointAt(
|
||||
element,
|
||||
elementsMap,
|
||||
scenePointer.x,
|
||||
scenePointer.y,
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -716,8 +683,7 @@ export class LinearElementEditor {
|
||||
lastUncommittedPoint: null,
|
||||
endBindingElement: getHoveredElementForBinding(
|
||||
scenePointer,
|
||||
elements,
|
||||
elementsMap,
|
||||
Scene.getScene(element)!,
|
||||
),
|
||||
};
|
||||
|
||||
@@ -727,7 +693,6 @@ export class LinearElementEditor {
|
||||
|
||||
const clickedPointIndex = LinearElementEditor.getPointIndexUnderCursor(
|
||||
element,
|
||||
elementsMap,
|
||||
appState.zoom,
|
||||
scenePointer.x,
|
||||
scenePointer.y,
|
||||
@@ -748,12 +713,11 @@ export class LinearElementEditor {
|
||||
element,
|
||||
startBindingElement,
|
||||
endBindingElement,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
const targetPoint =
|
||||
@@ -815,13 +779,12 @@ export class LinearElementEditor {
|
||||
scenePointerX: number,
|
||||
scenePointerY: number,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
): LinearElementEditor | null {
|
||||
if (!appState.editingLinearElement) {
|
||||
return null;
|
||||
}
|
||||
const { elementId, lastUncommittedPoint } = appState.editingLinearElement;
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
if (!element) {
|
||||
return appState.editingLinearElement;
|
||||
}
|
||||
@@ -846,7 +809,6 @@ export class LinearElementEditor {
|
||||
|
||||
const [width, height] = LinearElementEditor._getShiftLockedDelta(
|
||||
element,
|
||||
elementsMap,
|
||||
lastCommittedPoint,
|
||||
[scenePointerX, scenePointerY],
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -859,7 +821,6 @@ export class LinearElementEditor {
|
||||
} else {
|
||||
newPoint = LinearElementEditor.createPointAt(
|
||||
element,
|
||||
elementsMap,
|
||||
scenePointerX - appState.editingLinearElement.pointerOffset.x,
|
||||
scenePointerY - appState.editingLinearElement.pointerOffset.y,
|
||||
event[KEYS.CTRL_OR_CMD] ? null : appState.gridSize,
|
||||
@@ -886,9 +847,8 @@ export class LinearElementEditor {
|
||||
static getPointGlobalCoordinates(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
point: Point,
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
|
||||
@@ -900,9 +860,8 @@ export class LinearElementEditor {
|
||||
/** scene coords */
|
||||
static getPointsGlobalCoordinates(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
elementsMap: ElementsMap,
|
||||
): Point[] {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
return element.points.map((point) => {
|
||||
@@ -914,15 +873,13 @@ export class LinearElementEditor {
|
||||
|
||||
static getPointAtIndexGlobalCoordinates(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
|
||||
indexMaybeFromEnd: number, // -1 for last element
|
||||
elementsMap: ElementsMap,
|
||||
): Point {
|
||||
const index =
|
||||
indexMaybeFromEnd < 0
|
||||
? element.points.length + indexMaybeFromEnd
|
||||
: indexMaybeFromEnd;
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
|
||||
@@ -936,9 +893,8 @@ export class LinearElementEditor {
|
||||
static pointFromAbsoluteCoords(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
absoluteCoords: Point,
|
||||
elementsMap: ElementsMap,
|
||||
): Point {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
const [x, y] = rotate(
|
||||
@@ -953,15 +909,12 @@ export class LinearElementEditor {
|
||||
|
||||
static getPointIndexUnderCursor(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
elementsMap: ElementsMap,
|
||||
zoom: AppState["zoom"],
|
||||
x: number,
|
||||
y: number,
|
||||
) {
|
||||
const pointHandles = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const pointHandles =
|
||||
LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||
let idx = pointHandles.length;
|
||||
// loop from right to left because points on the right are rendered over
|
||||
// points on the left, thus should take precedence when clicking, if they
|
||||
@@ -981,13 +934,12 @@ export class LinearElementEditor {
|
||||
|
||||
static createPointAt(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
elementsMap: ElementsMap,
|
||||
scenePointerX: number,
|
||||
scenePointerY: number,
|
||||
gridSize: number | null,
|
||||
): Point {
|
||||
const pointerOnGrid = getGridPoint(scenePointerX, scenePointerY, gridSize);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
const [rotatedX, rotatedY] = rotate(
|
||||
@@ -1028,14 +980,14 @@ export class LinearElementEditor {
|
||||
mutateElement(element, LinearElementEditor.getNormalizedPoints(element));
|
||||
}
|
||||
|
||||
static duplicateSelectedPoints(appState: AppState, elementsMap: ElementsMap) {
|
||||
static duplicateSelectedPoints(appState: AppState) {
|
||||
if (!appState.editingLinearElement) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { selectedPointsIndices, elementId } = appState.editingLinearElement;
|
||||
|
||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||
const element = LinearElementEditor.getElement(elementId);
|
||||
|
||||
if (!element || selectedPointsIndices === null) {
|
||||
return false;
|
||||
@@ -1197,11 +1149,9 @@ export class LinearElementEditor {
|
||||
linearElementEditor: LinearElementEditor,
|
||||
pointerCoords: PointerCoords,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
const element = LinearElementEditor.getElement(
|
||||
linearElementEditor.elementId,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
if (!element) {
|
||||
@@ -1240,11 +1190,9 @@ export class LinearElementEditor {
|
||||
pointerCoords: PointerCoords,
|
||||
appState: AppState,
|
||||
snapToGrid: boolean,
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
const element = LinearElementEditor.getElement(
|
||||
linearElementEditor.elementId,
|
||||
elementsMap,
|
||||
);
|
||||
if (!element) {
|
||||
return;
|
||||
@@ -1260,7 +1208,6 @@ export class LinearElementEditor {
|
||||
|
||||
const midpoint = LinearElementEditor.createPointAt(
|
||||
element,
|
||||
elementsMap,
|
||||
pointerCoords.x,
|
||||
pointerCoords.y,
|
||||
snapToGrid ? appState.gridSize : null,
|
||||
@@ -1313,7 +1260,6 @@ export class LinearElementEditor {
|
||||
|
||||
private static _getShiftLockedDelta(
|
||||
element: NonDeleted<ExcalidrawLinearElement>,
|
||||
elementsMap: ElementsMap,
|
||||
referencePoint: Point,
|
||||
scenePointer: Point,
|
||||
gridSize: number | null,
|
||||
@@ -1321,7 +1267,6 @@ export class LinearElementEditor {
|
||||
const referencePointCoords = LinearElementEditor.getPointGlobalCoordinates(
|
||||
element,
|
||||
referencePoint,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
const [gridX, gridY] = getGridPoint(
|
||||
@@ -1343,12 +1288,8 @@ export class LinearElementEditor {
|
||||
static getBoundTextElementPosition = (
|
||||
element: ExcalidrawLinearElement,
|
||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||
elementsMap: ElementsMap,
|
||||
): { x: number; y: number } => {
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(element);
|
||||
if (points.length < 2) {
|
||||
mutateElement(boundTextElement, { isDeleted: true });
|
||||
}
|
||||
@@ -1359,7 +1300,6 @@ export class LinearElementEditor {
|
||||
const midPoint = LinearElementEditor.getPointGlobalCoordinates(
|
||||
element,
|
||||
element.points[index],
|
||||
elementsMap,
|
||||
);
|
||||
x = midPoint[0] - boundTextElement.width / 2;
|
||||
y = midPoint[1] - boundTextElement.height / 2;
|
||||
@@ -1379,7 +1319,6 @@ export class LinearElementEditor {
|
||||
points[index],
|
||||
points[index + 1],
|
||||
index + 1,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
x = midSegmentMidpoint[0] - boundTextElement.width / 2;
|
||||
@@ -1390,7 +1329,6 @@ export class LinearElementEditor {
|
||||
|
||||
static getMinMaxXYWithBoundText = (
|
||||
element: ExcalidrawLinearElement,
|
||||
elementsMap: ElementsMap,
|
||||
elementBounds: Bounds,
|
||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||
): [number, number, number, number, number, number] => {
|
||||
@@ -1401,7 +1339,6 @@ export class LinearElementEditor {
|
||||
LinearElementEditor.getBoundTextElementPosition(
|
||||
element,
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
const boundTextX2 = boundTextX1 + boundTextElement.width;
|
||||
const boundTextY2 = boundTextY1 + boundTextElement.height;
|
||||
@@ -1542,7 +1479,6 @@ export class LinearElementEditor {
|
||||
if (boundTextElement) {
|
||||
coords = LinearElementEditor.getMinMaxXYWithBoundText(
|
||||
element,
|
||||
elementsMap,
|
||||
[x1, y1, x2, y2],
|
||||
boundTextElement,
|
||||
);
|
||||
|
||||
@@ -16,7 +16,6 @@ import {
|
||||
ExcalidrawEmbeddableElement,
|
||||
ExcalidrawMagicFrameElement,
|
||||
ExcalidrawIframeElement,
|
||||
ElementsMap,
|
||||
} from "./types";
|
||||
import {
|
||||
arrayToMap,
|
||||
@@ -69,7 +68,6 @@ export type ElementConstructorOpts = MarkOptional<
|
||||
| "roundness"
|
||||
| "locked"
|
||||
| "opacity"
|
||||
| "customData"
|
||||
>;
|
||||
|
||||
const _newElementBase = <T extends ExcalidrawElement>(
|
||||
@@ -123,7 +121,6 @@ const _newElementBase = <T extends ExcalidrawElement>(
|
||||
updated: getUpdatedTimestamp(),
|
||||
link,
|
||||
locked,
|
||||
customData: rest.customData,
|
||||
};
|
||||
return element;
|
||||
};
|
||||
@@ -249,6 +246,7 @@ export const newTextElement = (
|
||||
y: opts.y - offsets.y,
|
||||
width: metrics.width,
|
||||
height: metrics.height,
|
||||
baseline: metrics.baseline,
|
||||
containerId: opts.containerId || null,
|
||||
originalText: text,
|
||||
lineHeight,
|
||||
@@ -260,19 +258,19 @@ export const newTextElement = (
|
||||
|
||||
const getAdjustedDimensions = (
|
||||
element: ExcalidrawTextElement,
|
||||
elementsMap: ElementsMap,
|
||||
nextText: string,
|
||||
): {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
baseline: number;
|
||||
} => {
|
||||
const { width: nextWidth, height: nextHeight } = measureText(
|
||||
nextText,
|
||||
getFontString(element),
|
||||
element.lineHeight,
|
||||
);
|
||||
const {
|
||||
width: nextWidth,
|
||||
height: nextHeight,
|
||||
baseline: nextBaseline,
|
||||
} = measureText(nextText, getFontString(element), element.lineHeight);
|
||||
const { textAlign, verticalAlign } = element;
|
||||
let x: number;
|
||||
let y: number;
|
||||
@@ -294,7 +292,7 @@ const getAdjustedDimensions = (
|
||||
x = element.x - offsets.x;
|
||||
y = element.y - offsets.y;
|
||||
} else {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
|
||||
const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
|
||||
element,
|
||||
@@ -326,6 +324,7 @@ const getAdjustedDimensions = (
|
||||
return {
|
||||
width: nextWidth,
|
||||
height: nextHeight,
|
||||
baseline: nextBaseline,
|
||||
x: Number.isFinite(x) ? x : element.x,
|
||||
y: Number.isFinite(y) ? y : element.y,
|
||||
};
|
||||
@@ -334,7 +333,6 @@ const getAdjustedDimensions = (
|
||||
export const refreshTextDimensions = (
|
||||
textElement: ExcalidrawTextElement,
|
||||
container: ExcalidrawTextContainer | null,
|
||||
elementsMap: ElementsMap,
|
||||
text = textElement.text,
|
||||
) => {
|
||||
if (textElement.isDeleted) {
|
||||
@@ -347,14 +345,13 @@ export const refreshTextDimensions = (
|
||||
getBoundTextMaxWidth(container, textElement),
|
||||
);
|
||||
}
|
||||
const dimensions = getAdjustedDimensions(textElement, elementsMap, text);
|
||||
const dimensions = getAdjustedDimensions(textElement, text);
|
||||
return { text, ...dimensions };
|
||||
};
|
||||
|
||||
export const updateTextElement = (
|
||||
textElement: ExcalidrawTextElement,
|
||||
container: ExcalidrawTextContainer | null,
|
||||
elementsMap: ElementsMap,
|
||||
{
|
||||
text,
|
||||
isDeleted,
|
||||
@@ -368,7 +365,7 @@ export const updateTextElement = (
|
||||
return newElementWith(textElement, {
|
||||
originalText,
|
||||
isDeleted: isDeleted ?? textElement.isDeleted,
|
||||
...refreshTextDimensions(textElement, container, elementsMap, originalText),
|
||||
...refreshTextDimensions(textElement, container, originalText),
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -52,6 +52,8 @@ import {
|
||||
handleBindTextResize,
|
||||
getBoundTextMaxWidth,
|
||||
getApproxMinLineHeight,
|
||||
measureText,
|
||||
getBoundTextMaxHeight,
|
||||
} from "./textElement";
|
||||
import { LinearElementEditor } from "./linearElementEditor";
|
||||
|
||||
@@ -84,12 +86,11 @@ export const transformElements = (
|
||||
if (transformHandleType === "rotation") {
|
||||
rotateSingleElement(
|
||||
element,
|
||||
elementsMap,
|
||||
pointerX,
|
||||
pointerY,
|
||||
shouldRotateWithDiscreteAngle,
|
||||
);
|
||||
updateBoundElements(element, elementsMap);
|
||||
updateBoundElements(element);
|
||||
} else if (
|
||||
isTextElement(element) &&
|
||||
(transformHandleType === "nw" ||
|
||||
@@ -105,7 +106,7 @@ export const transformElements = (
|
||||
pointerX,
|
||||
pointerY,
|
||||
);
|
||||
updateBoundElements(element, elementsMap);
|
||||
updateBoundElements(element);
|
||||
} else if (transformHandleType) {
|
||||
resizeSingleElement(
|
||||
originalElements,
|
||||
@@ -156,12 +157,11 @@ export const transformElements = (
|
||||
|
||||
const rotateSingleElement = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
pointerX: number,
|
||||
pointerY: number,
|
||||
shouldRotateWithDiscreteAngle: boolean,
|
||||
) => {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
let angle: number;
|
||||
@@ -211,7 +211,8 @@ const measureFontSizeFromWidth = (
|
||||
element: NonDeleted<ExcalidrawTextElement>,
|
||||
elementsMap: ElementsMap,
|
||||
nextWidth: number,
|
||||
): { size: number } | null => {
|
||||
nextHeight: number,
|
||||
): { size: number; baseline: number } | null => {
|
||||
// We only use width to scale font on resize
|
||||
let width = element.width;
|
||||
|
||||
@@ -226,9 +227,14 @@ const measureFontSizeFromWidth = (
|
||||
if (nextFontSize < MIN_FONT_SIZE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const metrics = measureText(
|
||||
element.text,
|
||||
getFontString({ fontSize: nextFontSize, fontFamily: element.fontFamily }),
|
||||
element.lineHeight,
|
||||
);
|
||||
return {
|
||||
size: nextFontSize,
|
||||
baseline: metrics.baseline + (nextHeight - metrics.height),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -260,7 +266,7 @@ const resizeSingleTextElement = (
|
||||
pointerX: number,
|
||||
pointerY: number,
|
||||
) => {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
// rotation pointer with reverse angle
|
||||
@@ -301,7 +307,12 @@ const resizeSingleTextElement = (
|
||||
if (scale > 0) {
|
||||
const nextWidth = element.width * scale;
|
||||
const nextHeight = element.height * scale;
|
||||
const metrics = measureFontSizeFromWidth(element, elementsMap, nextWidth);
|
||||
const metrics = measureFontSizeFromWidth(
|
||||
element,
|
||||
elementsMap,
|
||||
nextWidth,
|
||||
nextHeight,
|
||||
);
|
||||
if (metrics === null) {
|
||||
return;
|
||||
}
|
||||
@@ -329,6 +340,7 @@ const resizeSingleTextElement = (
|
||||
fontSize: metrics.size,
|
||||
width: nextWidth,
|
||||
height: nextHeight,
|
||||
baseline: metrics.baseline,
|
||||
x: nextElementX,
|
||||
y: nextElementY,
|
||||
});
|
||||
@@ -382,7 +394,7 @@ export const resizeSingleElement = (
|
||||
let scaleX = atStartBoundsWidth / boundsCurrentWidth;
|
||||
let scaleY = atStartBoundsHeight / boundsCurrentHeight;
|
||||
|
||||
let boundTextFont: { fontSize?: number } = {};
|
||||
let boundTextFont: { fontSize?: number; baseline?: number } = {};
|
||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
||||
|
||||
if (transformHandleDirection.includes("e")) {
|
||||
@@ -434,6 +446,7 @@ export const resizeSingleElement = (
|
||||
if (stateOfBoundTextElementAtResize) {
|
||||
boundTextFont = {
|
||||
fontSize: stateOfBoundTextElementAtResize.fontSize,
|
||||
baseline: stateOfBoundTextElementAtResize.baseline,
|
||||
};
|
||||
}
|
||||
if (shouldMaintainAspectRatio) {
|
||||
@@ -447,12 +460,14 @@ export const resizeSingleElement = (
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
getBoundTextMaxWidth(updatedElement, boundTextElement),
|
||||
getBoundTextMaxHeight(updatedElement, boundTextElement),
|
||||
);
|
||||
if (nextFont === null) {
|
||||
return;
|
||||
}
|
||||
boundTextFont = {
|
||||
fontSize: nextFont.size,
|
||||
baseline: nextFont.baseline,
|
||||
};
|
||||
} else {
|
||||
const minWidth = getApproxMinLineWidth(
|
||||
@@ -614,13 +629,14 @@ export const resizeSingleElement = (
|
||||
) {
|
||||
mutateElement(element, resizedElement);
|
||||
|
||||
updateBoundElements(element, elementsMap, {
|
||||
updateBoundElements(element, {
|
||||
newSize: { width: resizedElement.width, height: resizedElement.height },
|
||||
});
|
||||
|
||||
if (boundTextElement && boundTextFont != null) {
|
||||
mutateElement(boundTextElement, {
|
||||
fontSize: boundTextFont.fontSize,
|
||||
baseline: boundTextFont.baseline,
|
||||
});
|
||||
}
|
||||
handleBindTextResize(
|
||||
@@ -680,11 +696,7 @@ export const resizeMultipleElements = (
|
||||
if (!isBoundToContainer(text)) {
|
||||
return acc;
|
||||
}
|
||||
const xy = LinearElementEditor.getBoundTextElementPosition(
|
||||
orig,
|
||||
text,
|
||||
elementsMap,
|
||||
);
|
||||
const xy = LinearElementEditor.getBoundTextElementPosition(orig, text);
|
||||
return [...acc, { ...text, ...xy }];
|
||||
}, [] as ExcalidrawTextElementWithContainer[]);
|
||||
|
||||
@@ -751,6 +763,7 @@ export const resizeMultipleElements = (
|
||||
> & {
|
||||
points?: ExcalidrawLinearElement["points"];
|
||||
fontSize?: ExcalidrawTextElement["fontSize"];
|
||||
baseline?: ExcalidrawTextElement["baseline"];
|
||||
scale?: ExcalidrawImageElement["scale"];
|
||||
boundTextFontSize?: ExcalidrawTextElement["fontSize"];
|
||||
};
|
||||
@@ -825,11 +838,17 @@ export const resizeMultipleElements = (
|
||||
}
|
||||
|
||||
if (isTextElement(orig)) {
|
||||
const metrics = measureFontSizeFromWidth(orig, elementsMap, width);
|
||||
const metrics = measureFontSizeFromWidth(
|
||||
orig,
|
||||
elementsMap,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
if (!metrics) {
|
||||
return;
|
||||
}
|
||||
update.fontSize = metrics.size;
|
||||
update.baseline = metrics.baseline;
|
||||
}
|
||||
|
||||
const boundTextElement = originalElements.get(
|
||||
@@ -860,7 +879,7 @@ export const resizeMultipleElements = (
|
||||
|
||||
mutateElement(element, update, false);
|
||||
|
||||
updateBoundElements(element, elementsMap, {
|
||||
updateBoundElements(element, {
|
||||
simultaneouslyUpdated: elementsToUpdate,
|
||||
newSize: { width, height },
|
||||
});
|
||||
@@ -902,7 +921,7 @@ const rotateMultipleElements = (
|
||||
elements
|
||||
.filter((element) => !isFrameLikeElement(element))
|
||||
.forEach((element) => {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
const origAngle =
|
||||
@@ -923,9 +942,7 @@ const rotateMultipleElements = (
|
||||
},
|
||||
false,
|
||||
);
|
||||
updateBoundElements(element, elementsMap, {
|
||||
simultaneouslyUpdated: elements,
|
||||
});
|
||||
updateBoundElements(element, { simultaneouslyUpdated: elements });
|
||||
|
||||
const boundText = getBoundTextElement(element, elementsMap);
|
||||
if (boundText && !isArrowElement(element)) {
|
||||
@@ -947,13 +964,12 @@ const rotateMultipleElements = (
|
||||
export const getResizeOffsetXY = (
|
||||
transformHandleType: MaybeTransformHandleType,
|
||||
selectedElements: NonDeletedExcalidrawElement[],
|
||||
elementsMap: ElementsMap,
|
||||
x: number,
|
||||
y: number,
|
||||
): [number, number] => {
|
||||
const [x1, y1, x2, y2] =
|
||||
selectedElements.length === 1
|
||||
? getElementAbsoluteCoords(selectedElements[0], elementsMap)
|
||||
? getElementAbsoluteCoords(selectedElements[0])
|
||||
: getCommonBounds(selectedElements);
|
||||
const cx = (x1 + x2) / 2;
|
||||
const cy = (y1 + y2) / 2;
|
||||
|
||||
@@ -2,7 +2,6 @@ import {
|
||||
ExcalidrawElement,
|
||||
PointerType,
|
||||
NonDeletedExcalidrawElement,
|
||||
ElementsMap,
|
||||
} from "./types";
|
||||
|
||||
import {
|
||||
@@ -28,7 +27,6 @@ const isInsideTransformHandle = (
|
||||
|
||||
export const resizeTest = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
appState: AppState,
|
||||
x: number,
|
||||
y: number,
|
||||
@@ -40,7 +38,7 @@ export const resizeTest = (
|
||||
}
|
||||
|
||||
const { rotation: rotationTransformHandle, ...transformHandles } =
|
||||
getTransformHandles(element, zoom, elementsMap, pointerType);
|
||||
getTransformHandles(element, zoom, pointerType);
|
||||
|
||||
if (
|
||||
rotationTransformHandle &&
|
||||
@@ -72,7 +70,6 @@ export const getElementWithTransformHandleType = (
|
||||
scenePointerY: number,
|
||||
zoom: Zoom,
|
||||
pointerType: PointerType,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
return elements.reduce((result, element) => {
|
||||
if (result) {
|
||||
@@ -80,7 +77,6 @@ export const getElementWithTransformHandleType = (
|
||||
}
|
||||
const transformHandleType = resizeTest(
|
||||
element,
|
||||
elementsMap,
|
||||
appState,
|
||||
scenePointerX,
|
||||
scenePointerY,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ElementsMap, ExcalidrawElement } from "./types";
|
||||
import { ExcalidrawElement } from "./types";
|
||||
import { mutateElement } from "./mutateElement";
|
||||
import { isFreeDrawElement, isLinearElement } from "./typeChecks";
|
||||
import { SHIFT_LOCKING_ANGLE } from "../constants";
|
||||
@@ -26,9 +26,8 @@ export const isElementInViewport = (
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
},
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap); // scene coordinates
|
||||
const [x1, y1, x2, y2] = getElementBounds(element); // scene coordinates
|
||||
const topLeftSceneCoords = viewportCoordsToSceneCoords(
|
||||
{
|
||||
clientX: viewTransformations.offsetLeft,
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
DEFAULT_FONT_FAMILY,
|
||||
DEFAULT_FONT_SIZE,
|
||||
FONT_FAMILY,
|
||||
isSafari,
|
||||
TEXT_ALIGN,
|
||||
VERTICAL_ALIGN,
|
||||
} from "../constants";
|
||||
@@ -31,7 +32,7 @@ import { getElementAbsoluteCoords } from ".";
|
||||
import { getSelectedElements } from "../scene";
|
||||
import { isHittingElementNotConsideringBoundingBox } from "./collision";
|
||||
|
||||
import { ExtractSetType, MakeBrand } from "../utility-types";
|
||||
import { ExtractSetType } from "../utility-types";
|
||||
import {
|
||||
resetOriginalContainerCache,
|
||||
updateOriginalContainerCache,
|
||||
@@ -52,7 +53,6 @@ const splitIntoLines = (text: string) => {
|
||||
export const redrawTextBoundingBox = (
|
||||
textElement: ExcalidrawTextElement,
|
||||
container: ExcalidrawElement | null,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
let maxWidth = undefined;
|
||||
const boundTextUpdates = {
|
||||
@@ -61,6 +61,7 @@ export const redrawTextBoundingBox = (
|
||||
text: textElement.text,
|
||||
width: textElement.width,
|
||||
height: textElement.height,
|
||||
baseline: textElement.baseline,
|
||||
};
|
||||
|
||||
boundTextUpdates.text = textElement.text;
|
||||
@@ -81,6 +82,7 @@ export const redrawTextBoundingBox = (
|
||||
|
||||
boundTextUpdates.width = metrics.width;
|
||||
boundTextUpdates.height = metrics.height;
|
||||
boundTextUpdates.baseline = metrics.baseline;
|
||||
|
||||
if (container) {
|
||||
const maxContainerHeight = getBoundTextMaxHeight(
|
||||
@@ -108,11 +110,7 @@ export const redrawTextBoundingBox = (
|
||||
...textElement,
|
||||
...boundTextUpdates,
|
||||
} as ExcalidrawTextElementWithContainer;
|
||||
const { x, y } = computeBoundTextPosition(
|
||||
container,
|
||||
updatedTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
const { x, y } = computeBoundTextPosition(container, updatedTextElement);
|
||||
boundTextUpdates.x = x;
|
||||
boundTextUpdates.y = y;
|
||||
}
|
||||
@@ -121,11 +119,11 @@ export const redrawTextBoundingBox = (
|
||||
};
|
||||
|
||||
export const bindTextToShapeAfterDuplication = (
|
||||
newElements: ExcalidrawElement[],
|
||||
sceneElements: ExcalidrawElement[],
|
||||
oldElements: ExcalidrawElement[],
|
||||
oldIdToDuplicatedId: Map<ExcalidrawElement["id"], ExcalidrawElement["id"]>,
|
||||
): void => {
|
||||
const newElementsMap = arrayToMap(newElements) as Map<
|
||||
const sceneElementMap = arrayToMap(sceneElements) as Map<
|
||||
ExcalidrawElement["id"],
|
||||
ExcalidrawElement
|
||||
>;
|
||||
@@ -136,7 +134,7 @@ export const bindTextToShapeAfterDuplication = (
|
||||
if (boundTextElementId) {
|
||||
const newTextElementId = oldIdToDuplicatedId.get(boundTextElementId);
|
||||
if (newTextElementId) {
|
||||
const newContainer = newElementsMap.get(newElementId);
|
||||
const newContainer = sceneElementMap.get(newElementId);
|
||||
if (newContainer) {
|
||||
mutateElement(newContainer, {
|
||||
boundElements: (element.boundElements || [])
|
||||
@@ -151,7 +149,7 @@ export const bindTextToShapeAfterDuplication = (
|
||||
}),
|
||||
});
|
||||
}
|
||||
const newTextElement = newElementsMap.get(newTextElementId);
|
||||
const newTextElement = sceneElementMap.get(newTextElementId);
|
||||
if (newTextElement && isTextElement(newTextElement)) {
|
||||
mutateElement(newTextElement, {
|
||||
containerId: newContainer ? newElementId : null,
|
||||
@@ -185,6 +183,7 @@ export const handleBindTextResize = (
|
||||
const maxWidth = getBoundTextMaxWidth(container, textElement);
|
||||
const maxHeight = getBoundTextMaxHeight(container, textElement);
|
||||
let containerHeight = container.height;
|
||||
let nextBaseLine = textElement.baseline;
|
||||
if (
|
||||
shouldMaintainAspectRatio ||
|
||||
(transformHandleType !== "n" && transformHandleType !== "s")
|
||||
@@ -203,6 +202,7 @@ export const handleBindTextResize = (
|
||||
);
|
||||
nextHeight = metrics.height;
|
||||
nextWidth = metrics.width;
|
||||
nextBaseLine = metrics.baseline;
|
||||
}
|
||||
// increase height in case text element height exceeds
|
||||
if (nextHeight > maxHeight) {
|
||||
@@ -230,12 +230,13 @@ export const handleBindTextResize = (
|
||||
text,
|
||||
width: nextWidth,
|
||||
height: nextHeight,
|
||||
baseline: nextBaseLine,
|
||||
});
|
||||
|
||||
if (!isArrowElement(container)) {
|
||||
mutateElement(
|
||||
textElement,
|
||||
computeBoundTextPosition(container, textElement, elementsMap),
|
||||
computeBoundTextPosition(container, textElement),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -244,13 +245,11 @@ export const handleBindTextResize = (
|
||||
export const computeBoundTextPosition = (
|
||||
container: ExcalidrawElement,
|
||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
if (isArrowElement(container)) {
|
||||
return LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
const containerCoords = getContainerCoords(container);
|
||||
@@ -279,6 +278,8 @@ export const computeBoundTextPosition = (
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
// https://github.com/grassator/canvas-text-editor/blob/master/lib/FontMetrics.js
|
||||
|
||||
export const measureText = (
|
||||
text: string,
|
||||
font: FontString,
|
||||
@@ -293,7 +294,59 @@ export const measureText = (
|
||||
const fontSize = parseFloat(font);
|
||||
const height = getTextHeight(text, fontSize, lineHeight);
|
||||
const width = getTextWidth(text, font);
|
||||
return { width, height };
|
||||
const baseline = measureBaseline(text, font, lineHeight);
|
||||
return { width, height, baseline };
|
||||
};
|
||||
|
||||
export const measureBaseline = (
|
||||
text: string,
|
||||
font: FontString,
|
||||
lineHeight: ExcalidrawTextElement["lineHeight"],
|
||||
wrapInContainer?: boolean,
|
||||
) => {
|
||||
const container = document.createElement("div");
|
||||
container.style.position = "absolute";
|
||||
container.style.whiteSpace = "pre";
|
||||
container.style.font = font;
|
||||
container.style.minHeight = "1em";
|
||||
if (wrapInContainer) {
|
||||
container.style.overflow = "hidden";
|
||||
container.style.wordBreak = "break-word";
|
||||
container.style.whiteSpace = "pre-wrap";
|
||||
}
|
||||
|
||||
container.style.lineHeight = String(lineHeight);
|
||||
|
||||
container.innerText = text;
|
||||
|
||||
// Baseline is important for positioning text on canvas
|
||||
document.body.appendChild(container);
|
||||
|
||||
const span = document.createElement("span");
|
||||
span.style.display = "inline-block";
|
||||
span.style.overflow = "hidden";
|
||||
span.style.width = "1px";
|
||||
span.style.height = "1px";
|
||||
container.appendChild(span);
|
||||
let baseline = span.offsetTop + span.offsetHeight;
|
||||
const height = container.offsetHeight;
|
||||
|
||||
if (isSafari) {
|
||||
const canvasHeight = getTextHeight(text, parseFloat(font), lineHeight);
|
||||
const fontSize = parseFloat(font);
|
||||
// In Safari the font size gets rounded off when rendering hence calculating the safari height and shifting the baseline if it differs
|
||||
// from the actual canvas height
|
||||
const domHeight = getTextHeight(text, Math.round(fontSize), lineHeight);
|
||||
if (canvasHeight > height) {
|
||||
baseline += canvasHeight - domHeight;
|
||||
}
|
||||
|
||||
if (height > canvasHeight) {
|
||||
baseline -= domHeight - canvasHeight;
|
||||
}
|
||||
}
|
||||
document.body.removeChild(container);
|
||||
return baseline;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -318,24 +371,6 @@ export const getLineHeightInPx = (
|
||||
return fontSize * lineHeight;
|
||||
};
|
||||
|
||||
/**
|
||||
* Calculates vertical offset for a text with alphabetic baseline.
|
||||
*/
|
||||
export const getVerticalOffset = (
|
||||
fontFamily: ExcalidrawTextElement["fontFamily"],
|
||||
fontSize: ExcalidrawTextElement["fontSize"],
|
||||
lineHeightPx: number,
|
||||
) => {
|
||||
const { unitsPerEm, ascender, descender } =
|
||||
FONT_METRICS[fontFamily] || FONT_METRICS[FONT_FAMILY.Helvetica];
|
||||
|
||||
const fontSizeEm = fontSize / unitsPerEm;
|
||||
const lineGap = lineHeightPx - fontSizeEm * ascender + fontSizeEm * descender;
|
||||
|
||||
const verticalOffset = fontSizeEm * ascender + lineGap;
|
||||
return verticalOffset;
|
||||
};
|
||||
|
||||
// FIXME rename to getApproxMinContainerHeight
|
||||
export const getApproxMinLineHeight = (
|
||||
fontSize: ExcalidrawTextElement["fontSize"],
|
||||
@@ -663,16 +698,12 @@ export const getContainerCenter = (
|
||||
y: container.y + container.height / 2,
|
||||
};
|
||||
}
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(
|
||||
container,
|
||||
elementsMap,
|
||||
);
|
||||
const points = LinearElementEditor.getPointsGlobalCoordinates(container);
|
||||
if (points.length % 2 === 1) {
|
||||
const index = Math.floor(container.points.length / 2);
|
||||
const midPoint = LinearElementEditor.getPointGlobalCoordinates(
|
||||
container,
|
||||
container.points[index],
|
||||
elementsMap,
|
||||
);
|
||||
return { x: midPoint[0], y: midPoint[1] };
|
||||
}
|
||||
@@ -688,7 +719,6 @@ export const getContainerCenter = (
|
||||
points[index],
|
||||
points[index + 1],
|
||||
index + 1,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
return { x: midSegmentMidpoint[0], y: midSegmentMidpoint[1] };
|
||||
@@ -727,13 +757,11 @@ export const getTextElementAngle = (
|
||||
export const getBoundTextElementPosition = (
|
||||
container: ExcalidrawElement,
|
||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
if (isArrowElement(container)) {
|
||||
return LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -776,7 +804,6 @@ export const getTextBindableContainerAtPosition = (
|
||||
appState: AppState,
|
||||
x: number,
|
||||
y: number,
|
||||
elementsMap: ElementsMap,
|
||||
): ExcalidrawTextContainer | null => {
|
||||
const selectedElements = getSelectedElements(elements, appState);
|
||||
if (selectedElements.length === 1) {
|
||||
@@ -790,10 +817,7 @@ export const getTextBindableContainerAtPosition = (
|
||||
if (elements[index].isDeleted) {
|
||||
continue;
|
||||
}
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(
|
||||
elements[index],
|
||||
elementsMap,
|
||||
);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(elements[index]);
|
||||
if (
|
||||
isArrowElement(elements[index]) &&
|
||||
isHittingElementNotConsideringBoundingBox(
|
||||
@@ -801,7 +825,6 @@ export const getTextBindableContainerAtPosition = (
|
||||
appState,
|
||||
null,
|
||||
[x, y],
|
||||
elementsMap,
|
||||
)
|
||||
) {
|
||||
hitElement = elements[index];
|
||||
@@ -922,57 +945,13 @@ const DEFAULT_LINE_HEIGHT = {
|
||||
// ~1.25 is the average for Virgil in WebKit and Blink.
|
||||
// Gecko (FF) uses ~1.28.
|
||||
[FONT_FAMILY.Virgil]: 1.25 as ExcalidrawTextElement["lineHeight"],
|
||||
// ~1.15 is the average for Helvetica in WebKit and Blink.
|
||||
// ~1.15 is the average for Virgil in WebKit and Blink.
|
||||
// Gecko if all over the place.
|
||||
[FONT_FAMILY.Helvetica]: 1.15 as ExcalidrawTextElement["lineHeight"],
|
||||
// ~1.2 is the average for Cascadia in WebKit and Blink, and kinda Gecko too
|
||||
// ~1.2 is the average for Virgil in WebKit and Blink, and kinda Gecko too
|
||||
[FONT_FAMILY.Cascadia]: 1.2 as ExcalidrawTextElement["lineHeight"],
|
||||
};
|
||||
|
||||
/** OS/2 sTypoAscender, https://learn.microsoft.com/en-us/typography/opentype/spec/os2#stypoascender */
|
||||
type sTypoAscender = number & MakeBrand<"sTypoAscender">;
|
||||
|
||||
/** OS/2 sTypoDescender, https://learn.microsoft.com/en-us/typography/opentype/spec/os2#stypodescender */
|
||||
type sTypoDescender = number & MakeBrand<"sTypoDescender">;
|
||||
|
||||
/** head.unitsPerEm, usually either 1000 or 2048 */
|
||||
type unitsPerEm = number & MakeBrand<"unitsPerEm">;
|
||||
|
||||
/**
|
||||
* Hardcoded metrics for default fonts, read by https://opentype.js.org/font-inspector.html.
|
||||
* For custom fonts, read these metrics from OS/2 table and extend this object.
|
||||
*
|
||||
* WARN: opentype does NOT open WOFF2 correctly, make sure to convert WOFF2 to TTF first.
|
||||
*/
|
||||
export const FONT_METRICS: Record<
|
||||
number,
|
||||
{
|
||||
unitsPerEm: number;
|
||||
ascender: sTypoAscender;
|
||||
descender: sTypoDescender;
|
||||
}
|
||||
> = {
|
||||
[FONT_FAMILY.Virgil]: {
|
||||
unitsPerEm: 1000 as unitsPerEm,
|
||||
ascender: 886 as sTypoAscender,
|
||||
descender: -374 as sTypoDescender,
|
||||
},
|
||||
[FONT_FAMILY.Helvetica]: {
|
||||
unitsPerEm: 2048 as unitsPerEm,
|
||||
ascender: 1577 as sTypoAscender,
|
||||
descender: -471 as sTypoDescender,
|
||||
},
|
||||
[FONT_FAMILY.Cascadia]: {
|
||||
unitsPerEm: 2048 as unitsPerEm,
|
||||
ascender: 1977 as sTypoAscender,
|
||||
descender: -480 as sTypoDescender,
|
||||
},
|
||||
[FONT_FAMILY.Assistant]: {
|
||||
unitsPerEm: 1000 as unitsPerEm,
|
||||
ascender: 1021 as sTypoAscender,
|
||||
descender: -287 as sTypoDescender,
|
||||
},
|
||||
};
|
||||
|
||||
export const getDefaultLineHeight = (fontFamily: FontFamilyValues) => {
|
||||
if (fontFamily in DEFAULT_LINE_HEIGHT) {
|
||||
return DEFAULT_LINE_HEIGHT[fontFamily];
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
isBoundToContainer,
|
||||
isTextElement,
|
||||
} from "./typeChecks";
|
||||
import { CLASSES } from "../constants";
|
||||
import { CLASSES, isSafari } from "../constants";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawLinearElement,
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
getBoundTextMaxHeight,
|
||||
getBoundTextMaxWidth,
|
||||
computeContainerDimensionForBoundText,
|
||||
detectLineHeight,
|
||||
computeBoundTextPosition,
|
||||
getBoundTextElement,
|
||||
} from "./textElement";
|
||||
@@ -120,13 +121,13 @@ export const textWysiwyg = ({
|
||||
return;
|
||||
}
|
||||
const { textAlign, verticalAlign } = updatedTextElement;
|
||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||
|
||||
if (updatedTextElement && isTextElement(updatedTextElement)) {
|
||||
let coordX = updatedTextElement.x;
|
||||
let coordY = updatedTextElement.y;
|
||||
const container = getContainerElement(
|
||||
updatedTextElement,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
app.scene.getElementsMapIncludingDeleted(),
|
||||
);
|
||||
let maxWidth = updatedTextElement.width;
|
||||
|
||||
@@ -142,7 +143,6 @@ export const textWysiwyg = ({
|
||||
LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
updatedTextElement as ExcalidrawTextElementWithContainer,
|
||||
elementsMap,
|
||||
);
|
||||
coordX = boundTextCoords.x;
|
||||
coordY = boundTextCoords.y;
|
||||
@@ -200,7 +200,6 @@ export const textWysiwyg = ({
|
||||
const { y } = computeBoundTextPosition(
|
||||
container,
|
||||
updatedTextElement as ExcalidrawTextElementWithContainer,
|
||||
elementsMap,
|
||||
);
|
||||
coordY = y;
|
||||
}
|
||||
@@ -226,6 +225,18 @@ export const textWysiwyg = ({
|
||||
if (!container) {
|
||||
maxWidth = (appState.width - 8 - viewportX) / appState.zoom.value;
|
||||
textElementWidth = Math.min(textElementWidth, maxWidth);
|
||||
} else {
|
||||
textElementWidth += 0.5;
|
||||
}
|
||||
|
||||
let lineHeight = updatedTextElement.lineHeight;
|
||||
|
||||
// In Safari the font size gets rounded off when rendering hence calculating the line height by rounding off font size
|
||||
if (isSafari) {
|
||||
lineHeight = detectLineHeight({
|
||||
...updatedTextElement,
|
||||
fontSize: Math.round(updatedTextElement.fontSize),
|
||||
});
|
||||
}
|
||||
|
||||
// Make sure text editor height doesn't go beyond viewport
|
||||
@@ -234,7 +245,7 @@ export const textWysiwyg = ({
|
||||
Object.assign(editable.style, {
|
||||
font: getFontString(updatedTextElement),
|
||||
// must be defined *after* font ¯\_(ツ)_/¯
|
||||
lineHeight: updatedTextElement.lineHeight,
|
||||
lineHeight,
|
||||
width: `${textElementWidth}px`,
|
||||
height: `${textElementHeight}px`,
|
||||
left: `${viewportX}px`,
|
||||
@@ -315,7 +326,7 @@ export const textWysiwyg = ({
|
||||
}
|
||||
const container = getContainerElement(
|
||||
element,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
app.scene.getElementsMapIncludingDeleted(),
|
||||
);
|
||||
|
||||
const font = getFontString({
|
||||
@@ -502,7 +513,7 @@ export const textWysiwyg = ({
|
||||
let text = editable.value;
|
||||
const container = getContainerElement(
|
||||
updateElement,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
app.scene.getElementsMapIncludingDeleted(),
|
||||
);
|
||||
|
||||
if (container) {
|
||||
@@ -530,11 +541,7 @@ export const textWysiwyg = ({
|
||||
),
|
||||
});
|
||||
}
|
||||
redrawTextBoundingBox(
|
||||
updateElement,
|
||||
container,
|
||||
app.scene.getNonDeletedElementsMap(),
|
||||
);
|
||||
redrawTextBoundingBox(updateElement, container);
|
||||
}
|
||||
|
||||
onSubmit({
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
ElementsMap,
|
||||
ExcalidrawElement,
|
||||
NonDeletedExcalidrawElement,
|
||||
PointerType,
|
||||
@@ -231,8 +230,6 @@ export const getTransformHandlesFromCoords = (
|
||||
export const getTransformHandles = (
|
||||
element: ExcalidrawElement,
|
||||
zoom: Zoom,
|
||||
elementsMap: ElementsMap,
|
||||
|
||||
pointerType: PointerType = "mouse",
|
||||
): TransformHandles => {
|
||||
// so that when locked element is selected (especially when you toggle lock
|
||||
@@ -270,7 +267,7 @@ export const getTransformHandles = (
|
||||
? DEFAULT_TRANSFORM_HANDLE_SPACING + 8
|
||||
: DEFAULT_TRANSFORM_HANDLE_SPACING;
|
||||
return getTransformHandlesFromCoords(
|
||||
getElementAbsoluteCoords(element, elementsMap, true),
|
||||
getElementAbsoluteCoords(element, true),
|
||||
element.angle,
|
||||
zoom,
|
||||
pointerType,
|
||||
|
||||
@@ -176,6 +176,7 @@ export type ExcalidrawTextElement = _ExcalidrawElementBase &
|
||||
fontSize: number;
|
||||
fontFamily: FontFamilyValues;
|
||||
text: string;
|
||||
baseline: number;
|
||||
textAlign: TextAlign;
|
||||
verticalAlign: VerticalAlign;
|
||||
containerId: ExcalidrawGenericElement["id"] | null;
|
||||
|
||||
@@ -21,9 +21,12 @@ import { mutateElement } from "./element/mutateElement";
|
||||
import { AppClassProperties, AppState, StaticCanvasAppState } from "./types";
|
||||
import { getElementsWithinSelection, getSelectedElements } from "./scene";
|
||||
import { getElementsInGroup, selectGroupsFromGivenElements } from "./groups";
|
||||
import type { ExcalidrawElementsIncludingDeleted } from "./scene/Scene";
|
||||
import Scene, { ExcalidrawElementsIncludingDeleted } from "./scene/Scene";
|
||||
import { getElementLineSegments } from "./element/bounds";
|
||||
import { doLineSegmentsIntersect, elementsOverlappingBBox } from "../utils/";
|
||||
import {
|
||||
doLineSegmentsIntersect,
|
||||
elementsOverlappingBBox,
|
||||
} from "../utils/export";
|
||||
import { isFrameElement, isFrameLikeElement } from "./element/typeChecks";
|
||||
import { ReadonlySetLike } from "./utility-types";
|
||||
|
||||
@@ -62,11 +65,10 @@ export const bindElementsToFramesAfterDuplication = (
|
||||
export function isElementIntersectingFrame(
|
||||
element: ExcalidrawElement,
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) {
|
||||
const frameLineSegments = getElementLineSegments(frame, elementsMap);
|
||||
const frameLineSegments = getElementLineSegments(frame);
|
||||
|
||||
const elementLineSegments = getElementLineSegments(element, elementsMap);
|
||||
const elementLineSegments = getElementLineSegments(element);
|
||||
|
||||
const intersecting = frameLineSegments.some((frameLineSegment) =>
|
||||
elementLineSegments.some((elementLineSegment) =>
|
||||
@@ -80,10 +82,9 @@ export function isElementIntersectingFrame(
|
||||
export const getElementsCompletelyInFrame = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) =>
|
||||
omitGroupsContainingFrameLikes(
|
||||
getElementsWithinSelection(elements, frame, elementsMap, false),
|
||||
getElementsWithinSelection(elements, frame, false),
|
||||
).filter(
|
||||
(element) =>
|
||||
(!isFrameLikeElement(element) && !element.frameId) ||
|
||||
@@ -94,9 +95,8 @@ export const isElementContainingFrame = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
element: ExcalidrawElement,
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
return getElementsWithinSelection(elements, element, elementsMap).some(
|
||||
return getElementsWithinSelection(elements, element).some(
|
||||
(e) => e.id === frame.id,
|
||||
);
|
||||
};
|
||||
@@ -104,22 +104,13 @@ export const isElementContainingFrame = (
|
||||
export const getElementsIntersectingFrame = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
) => {
|
||||
const elementsMap = arrayToMap(elements);
|
||||
return elements.filter((element) =>
|
||||
isElementIntersectingFrame(element, frame, elementsMap),
|
||||
);
|
||||
};
|
||||
) => elements.filter((element) => isElementIntersectingFrame(element, frame));
|
||||
|
||||
export const elementsAreInFrameBounds = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const [frameX1, frameY1, frameX2, frameY2] = getElementAbsoluteCoords(
|
||||
frame,
|
||||
elementsMap,
|
||||
);
|
||||
const [frameX1, frameY1, frameX2, frameY2] = getElementAbsoluteCoords(frame);
|
||||
|
||||
const [elementX1, elementY1, elementX2, elementY2] =
|
||||
getCommonBounds(elements);
|
||||
@@ -135,12 +126,11 @@ export const elementsAreInFrameBounds = (
|
||||
export const elementOverlapsWithFrame = (
|
||||
element: ExcalidrawElement,
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
return (
|
||||
elementsAreInFrameBounds([element], frame, elementsMap) ||
|
||||
isElementIntersectingFrame(element, frame, elementsMap) ||
|
||||
isElementContainingFrame([frame], element, frame, elementsMap)
|
||||
elementsAreInFrameBounds([element], frame) ||
|
||||
isElementIntersectingFrame(element, frame) ||
|
||||
isElementContainingFrame([frame], element, frame)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -150,9 +140,8 @@ export const isCursorInFrame = (
|
||||
y: number;
|
||||
},
|
||||
frame: NonDeleted<ExcalidrawFrameLikeElement>,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const [fx1, fy1, fx2, fy2] = getElementAbsoluteCoords(frame, elementsMap);
|
||||
const [fx1, fy1, fx2, fy2] = getElementAbsoluteCoords(frame);
|
||||
|
||||
return isPointWithinBounds(
|
||||
[fx1, fy1],
|
||||
@@ -166,7 +155,6 @@ export const groupsAreAtLeastIntersectingTheFrame = (
|
||||
groupIds: readonly string[],
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
) => {
|
||||
const elementsMap = arrayToMap(elements);
|
||||
const elementsInGroup = groupIds.flatMap((groupId) =>
|
||||
getElementsInGroup(elements, groupId),
|
||||
);
|
||||
@@ -177,8 +165,8 @@ export const groupsAreAtLeastIntersectingTheFrame = (
|
||||
|
||||
return !!elementsInGroup.find(
|
||||
(element) =>
|
||||
elementsAreInFrameBounds([element], frame, elementsMap) ||
|
||||
isElementIntersectingFrame(element, frame, elementsMap),
|
||||
elementsAreInFrameBounds([element], frame) ||
|
||||
isElementIntersectingFrame(element, frame),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -187,7 +175,6 @@ export const groupsAreCompletelyOutOfFrame = (
|
||||
groupIds: readonly string[],
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
) => {
|
||||
const elementsMap = arrayToMap(elements);
|
||||
const elementsInGroup = groupIds.flatMap((groupId) =>
|
||||
getElementsInGroup(elements, groupId),
|
||||
);
|
||||
@@ -199,8 +186,8 @@ export const groupsAreCompletelyOutOfFrame = (
|
||||
return (
|
||||
elementsInGroup.find(
|
||||
(element) =>
|
||||
elementsAreInFrameBounds([element], frame, elementsMap) ||
|
||||
isElementIntersectingFrame(element, frame, elementsMap),
|
||||
elementsAreInFrameBounds([element], frame) ||
|
||||
isElementIntersectingFrame(element, frame),
|
||||
) === undefined
|
||||
);
|
||||
};
|
||||
@@ -271,15 +258,14 @@ export const getElementsInResizingFrame = (
|
||||
allElements: ExcalidrawElementsIncludingDeleted,
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
): ExcalidrawElement[] => {
|
||||
const prevElementsInFrame = getFrameChildren(allElements, frame.id);
|
||||
const nextElementsInFrame = new Set<ExcalidrawElement>(prevElementsInFrame);
|
||||
|
||||
const elementsCompletelyInFrame = new Set([
|
||||
...getElementsCompletelyInFrame(allElements, frame, elementsMap),
|
||||
...getElementsCompletelyInFrame(allElements, frame),
|
||||
...prevElementsInFrame.filter((element) =>
|
||||
isElementContainingFrame(allElements, element, frame, elementsMap),
|
||||
isElementContainingFrame(allElements, element, frame),
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -297,7 +283,7 @@ export const getElementsInResizingFrame = (
|
||||
);
|
||||
|
||||
for (const element of elementsNotCompletelyInFrame) {
|
||||
if (!isElementIntersectingFrame(element, frame, elementsMap)) {
|
||||
if (!isElementIntersectingFrame(element, frame)) {
|
||||
if (element.groupIds.length === 0) {
|
||||
nextElementsInFrame.delete(element);
|
||||
}
|
||||
@@ -348,7 +334,7 @@ export const getElementsInResizingFrame = (
|
||||
if (isSelected) {
|
||||
const elementsInGroup = getElementsInGroup(allElements, id);
|
||||
|
||||
if (elementsAreInFrameBounds(elementsInGroup, frame, elementsMap)) {
|
||||
if (elementsAreInFrameBounds(elementsInGroup, frame)) {
|
||||
for (const element of elementsInGroup) {
|
||||
nextElementsInFrame.add(element);
|
||||
}
|
||||
@@ -362,25 +348,36 @@ export const getElementsInResizingFrame = (
|
||||
};
|
||||
|
||||
export const getElementsInNewFrame = (
|
||||
elements: ExcalidrawElementsIncludingDeleted,
|
||||
allElements: ExcalidrawElementsIncludingDeleted,
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
return omitGroupsContainingFrameLikes(
|
||||
elements,
|
||||
getElementsCompletelyInFrame(elements, frame, elementsMap),
|
||||
allElements,
|
||||
getElementsCompletelyInFrame(allElements, frame),
|
||||
);
|
||||
};
|
||||
|
||||
export const getContainingFrame = (
|
||||
element: ExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
/**
|
||||
* Optionally an elements map, in case the elements aren't in the Scene yet.
|
||||
* Takes precedence over Scene elements, even if the element exists
|
||||
* in Scene elements and not the supplied elements map.
|
||||
*/
|
||||
elementsMap?: Map<string, ExcalidrawElement>,
|
||||
) => {
|
||||
if (!element.frameId) {
|
||||
return null;
|
||||
if (element.frameId) {
|
||||
if (elementsMap) {
|
||||
return (elementsMap.get(element.frameId) ||
|
||||
null) as null | ExcalidrawFrameLikeElement;
|
||||
}
|
||||
return (
|
||||
(Scene.getScene(element)?.getElement(
|
||||
element.frameId,
|
||||
) as ExcalidrawFrameLikeElement) || null
|
||||
);
|
||||
}
|
||||
return (elementsMap.get(element.frameId) ||
|
||||
null) as null | ExcalidrawFrameLikeElement;
|
||||
return null;
|
||||
};
|
||||
|
||||
// --------------------------- Frame Operations -------------------------------
|
||||
@@ -391,7 +388,7 @@ export const filterElementsEligibleAsFrameChildren = (
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
) => {
|
||||
const otherFrames = new Set<ExcalidrawFrameLikeElement["id"]>();
|
||||
const elementsMap = arrayToMap(elements);
|
||||
|
||||
elements = omitGroupsContainingFrameLikes(elements);
|
||||
|
||||
for (const element of elements) {
|
||||
@@ -418,18 +415,14 @@ export const filterElementsEligibleAsFrameChildren = (
|
||||
if (!processedGroups.has(shallowestGroupId)) {
|
||||
processedGroups.add(shallowestGroupId);
|
||||
const groupElements = getElementsInGroup(elements, shallowestGroupId);
|
||||
if (
|
||||
groupElements.some((el) =>
|
||||
elementOverlapsWithFrame(el, frame, elementsMap),
|
||||
)
|
||||
) {
|
||||
if (groupElements.some((el) => elementOverlapsWithFrame(el, frame))) {
|
||||
for (const child of groupElements) {
|
||||
eligibleElements.push(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const overlaps = elementOverlapsWithFrame(element, frame, elementsMap);
|
||||
const overlaps = elementOverlapsWithFrame(element, frame);
|
||||
if (overlaps) {
|
||||
eligibleElements.push(element);
|
||||
}
|
||||
@@ -682,19 +675,19 @@ export const getTargetFrame = (
|
||||
return appState.selectedElementIds[_element.id] &&
|
||||
appState.selectedElementsAreBeingDragged
|
||||
? appState.frameToHighlight
|
||||
: getContainingFrame(_element, elementsMap);
|
||||
: getContainingFrame(_element);
|
||||
};
|
||||
|
||||
// TODO: this a huge bottleneck for large scenes, optimise
|
||||
// given an element, return if the element is in some frame
|
||||
export const isElementInFrame = (
|
||||
element: ExcalidrawElement,
|
||||
allElementsMap: ElementsMap,
|
||||
allElements: ElementsMap,
|
||||
appState: StaticCanvasAppState,
|
||||
) => {
|
||||
const frame = getTargetFrame(element, allElementsMap, appState);
|
||||
const frame = getTargetFrame(element, allElements, appState);
|
||||
const _element = isTextElement(element)
|
||||
? getContainerElement(element, allElementsMap) || element
|
||||
? getContainerElement(element, allElements) || element
|
||||
: element;
|
||||
|
||||
if (frame) {
|
||||
@@ -710,18 +703,16 @@ export const isElementInFrame = (
|
||||
}
|
||||
|
||||
if (_element.groupIds.length === 0) {
|
||||
return elementOverlapsWithFrame(_element, frame, allElementsMap);
|
||||
return elementOverlapsWithFrame(_element, frame);
|
||||
}
|
||||
|
||||
const allElementsInGroup = new Set(
|
||||
_element.groupIds.flatMap((gid) =>
|
||||
getElementsInGroup(allElementsMap, gid),
|
||||
),
|
||||
_element.groupIds.flatMap((gid) => getElementsInGroup(allElements, gid)),
|
||||
);
|
||||
|
||||
if (appState.editingGroupId && appState.selectedElementsAreBeingDragged) {
|
||||
const selectedElements = new Set(
|
||||
getSelectedElements(allElementsMap, appState),
|
||||
getSelectedElements(allElements, appState),
|
||||
);
|
||||
|
||||
const editingGroupOverlapsFrame = appState.frameToHighlight !== null;
|
||||
@@ -742,7 +733,7 @@ export const isElementInFrame = (
|
||||
}
|
||||
|
||||
for (const elementInGroup of allElementsInGroup) {
|
||||
if (elementOverlapsWithFrame(elementInGroup, frame, allElementsMap)) {
|
||||
if (elementOverlapsWithFrame(elementInGroup, frame)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ const clearAppStatePropertiesForHistory = (appState: AppState) => {
|
||||
viewBackgroundColor: appState.viewBackgroundColor,
|
||||
editingLinearElement: appState.editingLinearElement,
|
||||
editingGroupId: appState.editingGroupId,
|
||||
name: appState.name,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -207,8 +207,6 @@ Excalidraw.displayName = "Excalidraw";
|
||||
|
||||
export {
|
||||
getSceneVersion,
|
||||
hashElementsVersion,
|
||||
hashString,
|
||||
isInvisiblySmallElement,
|
||||
getNonDeletedElements,
|
||||
} from "./element";
|
||||
@@ -219,31 +217,22 @@ export {
|
||||
restoreElements,
|
||||
restoreLibraryItems,
|
||||
} from "./data/restore";
|
||||
|
||||
export {
|
||||
exportToCanvas,
|
||||
exportToBlob,
|
||||
exportToSvg,
|
||||
exportToClipboard,
|
||||
} from "../utils/export";
|
||||
|
||||
export { serializeAsJSON, serializeLibraryAsJSON } from "./data/json";
|
||||
export {
|
||||
serializeAsJSON,
|
||||
serializeLibraryAsJSON,
|
||||
loadLibraryFromBlob,
|
||||
loadFromBlob,
|
||||
loadSceneOrLibraryFromBlob,
|
||||
loadLibraryFromBlob,
|
||||
} from "./data/blob";
|
||||
export { getFreeDrawSvgPath } from "./renderer/renderElement";
|
||||
export { mergeLibraryItems, getLibraryItemsHash } from "./data/library";
|
||||
getFreeDrawSvgPath,
|
||||
exportToClipboard,
|
||||
mergeLibraryItems,
|
||||
} from "../utils/export";
|
||||
export { isLinearElement } from "./element/typeChecks";
|
||||
|
||||
export {
|
||||
FONT_FAMILY,
|
||||
THEME,
|
||||
MIME_TYPES,
|
||||
ROUNDNESS,
|
||||
DEFAULT_LASER_COLOR,
|
||||
} from "./constants";
|
||||
export { FONT_FAMILY, THEME, MIME_TYPES, ROUNDNESS } from "./constants";
|
||||
|
||||
export {
|
||||
mutateElement,
|
||||
@@ -279,4 +268,4 @@ export {
|
||||
elementsOverlappingBBox,
|
||||
isElementInsideBBox,
|
||||
elementPartiallyOverlapsWithOrContainsBBox,
|
||||
} from "../utils/withinBounds";
|
||||
} from "../utils/export";
|
||||
|
||||
@@ -5,7 +5,6 @@ import type App from "./components/App";
|
||||
import { SocketId } from "./types";
|
||||
import { easeOut } from "./utils";
|
||||
import { getClientColor } from "./clients";
|
||||
import { DEFAULT_LASER_COLOR } from "./constants";
|
||||
|
||||
export class LaserTrails implements Trail {
|
||||
public localTrail: AnimatedTrail;
|
||||
@@ -21,7 +20,7 @@ export class LaserTrails implements Trail {
|
||||
|
||||
this.localTrail = new AnimatedTrail(animationFrameHandler, app, {
|
||||
...this.getTrailOptions(),
|
||||
fill: () => DEFAULT_LASER_COLOR,
|
||||
fill: () => "red",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -79,15 +78,13 @@ export class LaserTrails implements Trail {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [key, collaborator] of this.app.state.collaborators.entries()) {
|
||||
for (const [key, collabolator] of this.app.state.collaborators.entries()) {
|
||||
let trail!: AnimatedTrail;
|
||||
|
||||
if (!this.collabTrails.has(key)) {
|
||||
trail = new AnimatedTrail(this.animationFrameHandler, this.app, {
|
||||
...this.getTrailOptions(),
|
||||
fill: () =>
|
||||
collaborator.pointer?.laserColor ||
|
||||
getClientColor(key, collaborator),
|
||||
fill: () => getClientColor(key),
|
||||
});
|
||||
trail.start(this.container);
|
||||
|
||||
@@ -96,21 +93,21 @@ export class LaserTrails implements Trail {
|
||||
trail = this.collabTrails.get(key)!;
|
||||
}
|
||||
|
||||
if (collaborator.pointer && collaborator.pointer.tool === "laser") {
|
||||
if (collaborator.button === "down" && !trail.hasCurrentTrail) {
|
||||
trail.startPath(collaborator.pointer.x, collaborator.pointer.y);
|
||||
if (collabolator.pointer && collabolator.pointer.tool === "laser") {
|
||||
if (collabolator.button === "down" && !trail.hasCurrentTrail) {
|
||||
trail.startPath(collabolator.pointer.x, collabolator.pointer.y);
|
||||
}
|
||||
|
||||
if (
|
||||
collaborator.button === "down" &&
|
||||
collabolator.button === "down" &&
|
||||
trail.hasCurrentTrail &&
|
||||
!trail.hasLastPoint(collaborator.pointer.x, collaborator.pointer.y)
|
||||
!trail.hasLastPoint(collabolator.pointer.x, collabolator.pointer.y)
|
||||
) {
|
||||
trail.addPointToPath(collaborator.pointer.x, collaborator.pointer.y);
|
||||
trail.addPointToPath(collabolator.pointer.x, collabolator.pointer.y);
|
||||
}
|
||||
|
||||
if (collaborator.button === "up" && trail.hasCurrentTrail) {
|
||||
trail.addPointToPath(collaborator.pointer.x, collaborator.pointer.y);
|
||||
if (collabolator.button === "up" && trail.hasCurrentTrail) {
|
||||
trail.addPointToPath(collabolator.pointer.x, collabolator.pointer.y);
|
||||
trail.endPath();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,9 +214,9 @@
|
||||
"fileTooBig": "File is too big. Maximum allowed size is {{maxSize}}.",
|
||||
"svgImageInsertError": "Couldn't insert SVG image. The SVG markup looks invalid.",
|
||||
"failedToFetchImage": "Failed to fetch image.",
|
||||
"invalidSVGString": "Invalid SVG.",
|
||||
"cannotResolveCollabServer": "Couldn't connect to the collab server. Please reload the page and try again.",
|
||||
"importLibraryError": "Couldn't load library",
|
||||
"saveLibraryError": "Couldn't save library to storage. Please save your library to a file locally to make sure you don't lose changes.",
|
||||
"collabSaveFailed": "Couldn't save to the backend database. If problems persist, you should save your file locally to ensure you don't lose your work.",
|
||||
"collabSaveFailed_sizeExceeded": "Couldn't save to the backend database, the canvas seems to be too big. You should save the file locally to ensure you don't lose your work.",
|
||||
"imageToolNotSupported": "Images are disabled.",
|
||||
@@ -248,7 +248,7 @@
|
||||
"library": "Library",
|
||||
"lock": "Keep selected tool active after drawing",
|
||||
"penMode": "Pen mode - prevent touch",
|
||||
"link": "Add / Update link for a selected shape",
|
||||
"link": "Add/ Update link for a selected shape",
|
||||
"eraser": "Eraser",
|
||||
"frame": "Frame tool",
|
||||
"magicframe": "Wireframe to code",
|
||||
@@ -534,10 +534,7 @@
|
||||
},
|
||||
"hint": {
|
||||
"text": "Click on user to follow",
|
||||
"followStatus": "You're currently following this user",
|
||||
"inCall": "User is in a voice call",
|
||||
"micMuted": "User's microphone is muted",
|
||||
"isSpeaking": "User is speaking"
|
||||
"followStatus": "You're currently following this user"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { Queue } from "./queue";
|
||||
|
||||
describe("Queue", () => {
|
||||
const calls: any[] = [];
|
||||
|
||||
const createJobFactory =
|
||||
<T>(
|
||||
// for purpose of this test, Error object will become a rejection value
|
||||
resolutionOrRejectionValue: T,
|
||||
ms = 1,
|
||||
) =>
|
||||
() => {
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
if (resolutionOrRejectionValue instanceof Error) {
|
||||
reject(resolutionOrRejectionValue);
|
||||
} else {
|
||||
resolve(resolutionOrRejectionValue);
|
||||
}
|
||||
}, ms);
|
||||
}).then((x) => {
|
||||
calls.push(x);
|
||||
return x;
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
calls.length = 0;
|
||||
});
|
||||
|
||||
it("should await and resolve values in order of enqueueing", async () => {
|
||||
const queue = new Queue();
|
||||
|
||||
const p1 = queue.push(createJobFactory("A", 50));
|
||||
const p2 = queue.push(createJobFactory("B"));
|
||||
const p3 = queue.push(createJobFactory("C"));
|
||||
|
||||
expect(await p3).toBe("C");
|
||||
expect(await p2).toBe("B");
|
||||
expect(await p1).toBe("A");
|
||||
|
||||
expect(calls).toEqual(["A", "B", "C"]);
|
||||
});
|
||||
|
||||
it("should reject a job if it throws, and not affect other jobs", async () => {
|
||||
const queue = new Queue();
|
||||
|
||||
const err = new Error("B");
|
||||
|
||||
queue.push(createJobFactory("A", 50));
|
||||
const p2 = queue.push(createJobFactory(err));
|
||||
const p3 = queue.push(createJobFactory("C"));
|
||||
|
||||
const p2err = p2.catch((err) => err);
|
||||
|
||||
await p3;
|
||||
|
||||
expect(await p2err).toBe(err);
|
||||
|
||||
expect(calls).toEqual(["A", "C"]);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { MaybePromise } from "./utility-types";
|
||||
import { promiseTry, ResolvablePromise, resolvablePromise } from "./utils";
|
||||
|
||||
type Job<T, TArgs extends unknown[]> = (...args: TArgs) => MaybePromise<T>;
|
||||
|
||||
type QueueJob<T, TArgs extends unknown[]> = {
|
||||
jobFactory: Job<T, TArgs>;
|
||||
promise: ResolvablePromise<T>;
|
||||
args: TArgs;
|
||||
};
|
||||
|
||||
export class Queue {
|
||||
private jobs: QueueJob<any, any[]>[] = [];
|
||||
private running = false;
|
||||
|
||||
private tick() {
|
||||
if (this.running) {
|
||||
return;
|
||||
}
|
||||
const job = this.jobs.shift();
|
||||
if (job) {
|
||||
this.running = true;
|
||||
job.promise.resolve(
|
||||
promiseTry(job.jobFactory, ...job.args).finally(() => {
|
||||
this.running = false;
|
||||
this.tick();
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
this.running = false;
|
||||
}
|
||||
}
|
||||
|
||||
push<TValue, TArgs extends unknown[]>(
|
||||
jobFactory: Job<TValue, TArgs>,
|
||||
...args: TArgs
|
||||
): Promise<TValue> {
|
||||
const promise = resolvablePromise<TValue>();
|
||||
this.jobs.push({ jobFactory, promise, args });
|
||||
|
||||
this.tick();
|
||||
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import { StaticCanvasAppState, AppState } from "../types";
|
||||
|
||||
import { StaticCanvasRenderConfig } from "../scene/types";
|
||||
|
||||
import { THEME_FILTER } from "../constants";
|
||||
|
||||
export const fillCircle = (
|
||||
context: CanvasRenderingContext2D,
|
||||
cx: number,
|
||||
cy: number,
|
||||
radius: number,
|
||||
stroke = true,
|
||||
) => {
|
||||
context.beginPath();
|
||||
context.arc(cx, cy, radius, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
if (stroke) {
|
||||
context.stroke();
|
||||
}
|
||||
};
|
||||
|
||||
export const getNormalizedCanvasDimensions = (
|
||||
canvas: HTMLCanvasElement,
|
||||
scale: number,
|
||||
): [number, number] => {
|
||||
// When doing calculations based on canvas width we should used normalized one
|
||||
return [canvas.width / scale, canvas.height / scale];
|
||||
};
|
||||
|
||||
export const bootstrapCanvas = ({
|
||||
canvas,
|
||||
scale,
|
||||
normalizedWidth,
|
||||
normalizedHeight,
|
||||
theme,
|
||||
isExporting,
|
||||
viewBackgroundColor,
|
||||
}: {
|
||||
canvas: HTMLCanvasElement;
|
||||
scale: number;
|
||||
normalizedWidth: number;
|
||||
normalizedHeight: number;
|
||||
theme?: AppState["theme"];
|
||||
isExporting?: StaticCanvasRenderConfig["isExporting"];
|
||||
viewBackgroundColor?: StaticCanvasAppState["viewBackgroundColor"];
|
||||
}): CanvasRenderingContext2D => {
|
||||
const context = canvas.getContext("2d")!;
|
||||
|
||||
context.setTransform(1, 0, 0, 1, 0, 0);
|
||||
context.scale(scale, scale);
|
||||
|
||||
if (isExporting && theme === "dark") {
|
||||
context.filter = THEME_FILTER;
|
||||
}
|
||||
|
||||
// Paint background
|
||||
if (typeof viewBackgroundColor === "string") {
|
||||
const hasTransparence =
|
||||
viewBackgroundColor === "transparent" ||
|
||||
viewBackgroundColor.length === 5 || // #RGBA
|
||||
viewBackgroundColor.length === 9 || // #RRGGBBA
|
||||
/(hsla|rgba)\(/.test(viewBackgroundColor);
|
||||
if (hasTransparence) {
|
||||
context.clearRect(0, 0, normalizedWidth, normalizedHeight);
|
||||
}
|
||||
context.save();
|
||||
context.fillStyle = viewBackgroundColor;
|
||||
context.fillRect(0, 0, normalizedWidth, normalizedHeight);
|
||||
context.restore();
|
||||
} else {
|
||||
context.clearRect(0, 0, normalizedWidth, normalizedHeight);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
ExcalidrawTextElementWithContainer,
|
||||
ExcalidrawFrameLikeElement,
|
||||
NonDeletedSceneElementsMap,
|
||||
ElementsMap,
|
||||
} from "../element/types";
|
||||
import {
|
||||
isTextElement,
|
||||
@@ -20,17 +19,27 @@ import {
|
||||
} from "../element/typeChecks";
|
||||
import { getElementAbsoluteCoords } from "../element/bounds";
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import type { Drawable } from "roughjs/bin/core";
|
||||
import type { RoughSVG } from "roughjs/bin/svg";
|
||||
|
||||
import {
|
||||
SVGRenderConfig,
|
||||
StaticCanvasRenderConfig,
|
||||
RenderableElementsMap,
|
||||
} from "../scene/types";
|
||||
import { distance, getFontString, isRTL } from "../utils";
|
||||
import { getCornerRadius, isRightAngle } from "../math";
|
||||
import {
|
||||
distance,
|
||||
getFontString,
|
||||
getFontFamilyString,
|
||||
isRTL,
|
||||
isTestEnv,
|
||||
} from "../utils";
|
||||
import { getCornerRadius, isPathALoop, isRightAngle } from "../math";
|
||||
import rough from "roughjs/bin/rough";
|
||||
import {
|
||||
AppState,
|
||||
StaticCanvasAppState,
|
||||
BinaryFiles,
|
||||
Zoom,
|
||||
InteractiveCanvasAppState,
|
||||
ElementsPendingErasure,
|
||||
@@ -40,7 +49,9 @@ import {
|
||||
BOUND_TEXT_PADDING,
|
||||
ELEMENT_READY_TO_ERASE_OPACITY,
|
||||
FRAME_STYLE,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
MIME_TYPES,
|
||||
SVG_NS,
|
||||
} from "../constants";
|
||||
import { getStroke, StrokeOptions } from "perfect-freehand";
|
||||
import {
|
||||
@@ -50,19 +61,21 @@ import {
|
||||
getLineHeightInPx,
|
||||
getBoundTextMaxHeight,
|
||||
getBoundTextMaxWidth,
|
||||
getVerticalOffset,
|
||||
} from "../element/textElement";
|
||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||
|
||||
import {
|
||||
createPlaceholderEmbeddableLabel,
|
||||
getEmbedLink,
|
||||
} from "../element/embeddable";
|
||||
import { getContainingFrame } from "../frame";
|
||||
import { normalizeLink, toValidURL } from "../data/url";
|
||||
import { ShapeCache } from "../scene/ShapeCache";
|
||||
|
||||
// using a stronger invert (100% vs our regular 93%) and saturate
|
||||
// as a temp hack to make images in dark theme look closer to original
|
||||
// color scheme (it's still not quite there and the colors look slightly
|
||||
// desatured, alas...)
|
||||
export const IMAGE_INVERT_FILTER =
|
||||
"invert(100%) hue-rotate(180deg) saturate(1.25)";
|
||||
const IMAGE_INVERT_FILTER = "invert(100%) hue-rotate(180deg) saturate(1.25)";
|
||||
|
||||
const defaultAppState = getDefaultAppState();
|
||||
|
||||
@@ -124,7 +137,6 @@ export interface ExcalidrawElementWithCanvas {
|
||||
|
||||
const cappedElementCanvasSize = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
zoom: Zoom,
|
||||
): {
|
||||
width: number;
|
||||
@@ -143,7 +155,7 @@ const cappedElementCanvasSize = (
|
||||
|
||||
const padding = getCanvasPadding(element);
|
||||
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const elementWidth =
|
||||
isLinearElement(element) || isFreeDrawElement(element)
|
||||
? distance(x1, x2)
|
||||
@@ -188,11 +200,7 @@ const generateElementCanvas = (
|
||||
const context = canvas.getContext("2d")!;
|
||||
const padding = getCanvasPadding(element);
|
||||
|
||||
const { width, height, scale } = cappedElementCanvasSize(
|
||||
element,
|
||||
elementsMap,
|
||||
zoom,
|
||||
);
|
||||
const { width, height, scale } = cappedElementCanvasSize(element, zoom);
|
||||
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
@@ -201,7 +209,7 @@ const generateElementCanvas = (
|
||||
let canvasOffsetY = 0;
|
||||
|
||||
if (isLinearElement(element) || isFreeDrawElement(element)) {
|
||||
const [x1, y1] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1] = getElementAbsoluteCoords(element);
|
||||
|
||||
canvasOffsetX =
|
||||
element.x > x1
|
||||
@@ -243,8 +251,7 @@ const generateElementCanvas = (
|
||||
canvasOffsetY,
|
||||
boundTextElementVersion:
|
||||
getBoundTextElement(element, elementsMap)?.version || null,
|
||||
containingFrameOpacity:
|
||||
getContainingFrame(element, elementsMap)?.opacity || 100,
|
||||
containingFrameOpacity: getContainingFrame(element)?.opacity || 100,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -384,23 +391,16 @@ const drawElementOnCanvas = (
|
||||
: element.textAlign === "right"
|
||||
? element.width
|
||||
: 0;
|
||||
|
||||
const lineHeightPx = getLineHeightInPx(
|
||||
element.fontSize,
|
||||
element.lineHeight,
|
||||
);
|
||||
|
||||
const verticalOffset = getVerticalOffset(
|
||||
element.fontFamily,
|
||||
element.fontSize,
|
||||
lineHeightPx,
|
||||
);
|
||||
|
||||
const verticalOffset = element.height - element.baseline;
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
context.fillText(
|
||||
lines[index],
|
||||
horizontalOffset,
|
||||
index * lineHeightPx + verticalOffset,
|
||||
(index + 1) * lineHeightPx - verticalOffset,
|
||||
);
|
||||
}
|
||||
context.restore();
|
||||
@@ -434,8 +434,7 @@ const generateElementWithCanvas = (
|
||||
const boundTextElementVersion =
|
||||
getBoundTextElement(element, elementsMap)?.version || null;
|
||||
|
||||
const containingFrameOpacity =
|
||||
getContainingFrame(element, elementsMap)?.opacity || 100;
|
||||
const containingFrameOpacity = getContainingFrame(element)?.opacity || 100;
|
||||
|
||||
if (
|
||||
!prevElementWithCanvas ||
|
||||
@@ -469,7 +468,7 @@ const drawElementFromCanvas = (
|
||||
const element = elementWithCanvas.element;
|
||||
const padding = getCanvasPadding(element);
|
||||
const zoom = elementWithCanvas.scale;
|
||||
let [x1, y1, x2, y2] = getElementAbsoluteCoords(element, allElementsMap);
|
||||
let [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
|
||||
// Free draw elements will otherwise "shuffle" as the min x and y change
|
||||
if (isFreeDrawElement(element)) {
|
||||
@@ -514,10 +513,8 @@ const drawElementFromCanvas = (
|
||||
elementWithCanvas.canvas.height,
|
||||
);
|
||||
|
||||
const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
|
||||
boundTextElement,
|
||||
allElementsMap,
|
||||
);
|
||||
const [, , , , boundTextCx, boundTextCy] =
|
||||
getElementAbsoluteCoords(boundTextElement);
|
||||
|
||||
tempCanvasContext.rotate(-element.angle);
|
||||
|
||||
@@ -647,7 +644,7 @@ export const renderElement = (
|
||||
) => {
|
||||
context.globalAlpha = getRenderOpacity(
|
||||
element,
|
||||
getContainingFrame(element, elementsMap),
|
||||
getContainingFrame(element),
|
||||
renderConfig.elementsPendingErasure,
|
||||
);
|
||||
|
||||
@@ -697,7 +694,7 @@ export const renderElement = (
|
||||
ShapeCache.generateElementShape(element, null);
|
||||
|
||||
if (renderConfig.isExporting) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2 + appState.scrollX;
|
||||
const cy = (y1 + y2) / 2 + appState.scrollY;
|
||||
const shiftX = (x2 - x1) / 2 - (element.x - x1);
|
||||
@@ -740,7 +737,7 @@ export const renderElement = (
|
||||
// rely on existing shapes
|
||||
ShapeCache.generateElementShape(element, renderConfig);
|
||||
if (renderConfig.isExporting) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
const cx = (x1 + x2) / 2 + appState.scrollX;
|
||||
const cy = (y1 + y2) / 2 + appState.scrollY;
|
||||
let shiftX = (x2 - x1) / 2 - (element.x - x1);
|
||||
@@ -752,7 +749,6 @@ export const renderElement = (
|
||||
LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
element as ExcalidrawTextElementWithContainer,
|
||||
elementsMap,
|
||||
);
|
||||
shiftX = (x2 - x1) / 2 - (boundTextCoords.x - x1);
|
||||
shiftY = (y2 - y1) / 2 - (boundTextCoords.y - y1);
|
||||
@@ -808,10 +804,8 @@ export const renderElement = (
|
||||
tempCanvasContext.rotate(-element.angle);
|
||||
|
||||
// Shift the canvas to center of bound text
|
||||
const [, , , , boundTextCx, boundTextCy] = getElementAbsoluteCoords(
|
||||
boundTextElement,
|
||||
elementsMap,
|
||||
);
|
||||
const [, , , , boundTextCx, boundTextCy] =
|
||||
getElementAbsoluteCoords(boundTextElement);
|
||||
const boundTextShiftX = (x1 + x2) / 2 - boundTextCx;
|
||||
const boundTextShiftY = (y1 + y2) / 2 - boundTextCy;
|
||||
tempCanvasContext.translate(-boundTextShiftX, -boundTextShiftY);
|
||||
@@ -898,6 +892,554 @@ export const renderElement = (
|
||||
context.globalAlpha = 1;
|
||||
};
|
||||
|
||||
const roughSVGDrawWithPrecision = (
|
||||
rsvg: RoughSVG,
|
||||
drawable: Drawable,
|
||||
precision?: number,
|
||||
) => {
|
||||
if (typeof precision === "undefined") {
|
||||
return rsvg.draw(drawable);
|
||||
}
|
||||
const pshape: Drawable = {
|
||||
sets: drawable.sets,
|
||||
shape: drawable.shape,
|
||||
options: { ...drawable.options, fixedDecimalPlaceDigits: precision },
|
||||
};
|
||||
return rsvg.draw(pshape);
|
||||
};
|
||||
|
||||
const maybeWrapNodesInFrameClipPath = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
root: SVGElement,
|
||||
nodes: SVGElement[],
|
||||
frameRendering: AppState["frameRendering"],
|
||||
) => {
|
||||
if (!frameRendering.enabled || !frameRendering.clip) {
|
||||
return null;
|
||||
}
|
||||
const frame = getContainingFrame(element);
|
||||
if (frame) {
|
||||
const g = root.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
g.setAttributeNS(SVG_NS, "clip-path", `url(#${frame.id})`);
|
||||
nodes.forEach((node) => g.appendChild(node));
|
||||
return g;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const renderElementToSvg = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: RenderableElementsMap,
|
||||
rsvg: RoughSVG,
|
||||
svgRoot: SVGElement,
|
||||
files: BinaryFiles,
|
||||
offsetX: number,
|
||||
offsetY: number,
|
||||
renderConfig: SVGRenderConfig,
|
||||
) => {
|
||||
const offset = { x: offsetX, y: offsetY };
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
|
||||
let cx = (x2 - x1) / 2 - (element.x - x1);
|
||||
let cy = (y2 - y1) / 2 - (element.y - y1);
|
||||
if (isTextElement(element)) {
|
||||
const container = getContainerElement(element, elementsMap);
|
||||
if (isArrowElement(container)) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(container);
|
||||
|
||||
const boundTextCoords = LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
element as ExcalidrawTextElementWithContainer,
|
||||
);
|
||||
cx = (x2 - x1) / 2 - (boundTextCoords.x - x1);
|
||||
cy = (y2 - y1) / 2 - (boundTextCoords.y - y1);
|
||||
offsetX = offsetX + boundTextCoords.x - element.x;
|
||||
offsetY = offsetY + boundTextCoords.y - element.y;
|
||||
}
|
||||
}
|
||||
const degree = (180 * element.angle) / Math.PI;
|
||||
|
||||
// element to append node to, most of the time svgRoot
|
||||
let root = svgRoot;
|
||||
|
||||
// if the element has a link, create an anchor tag and make that the new root
|
||||
if (element.link) {
|
||||
const anchorTag = svgRoot.ownerDocument!.createElementNS(SVG_NS, "a");
|
||||
anchorTag.setAttribute("href", normalizeLink(element.link));
|
||||
root.appendChild(anchorTag);
|
||||
root = anchorTag;
|
||||
}
|
||||
|
||||
const addToRoot = (node: SVGElement, element: ExcalidrawElement) => {
|
||||
if (isTestEnv()) {
|
||||
node.setAttribute("data-id", element.id);
|
||||
}
|
||||
root.appendChild(node);
|
||||
};
|
||||
|
||||
const opacity =
|
||||
((getContainingFrame(element)?.opacity ?? 100) * element.opacity) / 10000;
|
||||
|
||||
switch (element.type) {
|
||||
case "selection": {
|
||||
// Since this is used only during editing experience, which is canvas based,
|
||||
// this should not happen
|
||||
throw new Error("Selection rendering is not supported for SVG");
|
||||
}
|
||||
case "rectangle":
|
||||
case "diamond":
|
||||
case "ellipse": {
|
||||
const shape = ShapeCache.generateElementShape(element, null);
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute("stroke-linecap", "round");
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
break;
|
||||
}
|
||||
case "iframe":
|
||||
case "embeddable": {
|
||||
// render placeholder rectangle
|
||||
const shape = ShapeCache.generateElementShape(element, renderConfig);
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
const opacity = element.opacity / 100;
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute("stroke-linecap", "round");
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
addToRoot(node, element);
|
||||
|
||||
const label: ExcalidrawElement =
|
||||
createPlaceholderEmbeddableLabel(element);
|
||||
renderElementToSvg(
|
||||
label,
|
||||
elementsMap,
|
||||
rsvg,
|
||||
root,
|
||||
files,
|
||||
label.x + offset.x - element.x,
|
||||
label.y + offset.y - element.y,
|
||||
renderConfig,
|
||||
);
|
||||
|
||||
// render embeddable element + iframe
|
||||
const embeddableNode = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
embeddableNode.setAttribute("stroke-linecap", "round");
|
||||
embeddableNode.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
while (embeddableNode.firstChild) {
|
||||
embeddableNode.removeChild(embeddableNode.firstChild);
|
||||
}
|
||||
const radius = getCornerRadius(
|
||||
Math.min(element.width, element.height),
|
||||
element,
|
||||
);
|
||||
|
||||
const embedLink = getEmbedLink(toValidURL(element.link || ""));
|
||||
|
||||
// if rendering embeddables explicitly disabled or
|
||||
// embedding documents via srcdoc (which doesn't seem to work for SVGs)
|
||||
// replace with a link instead
|
||||
if (
|
||||
renderConfig.renderEmbeddables === false ||
|
||||
embedLink?.type === "document"
|
||||
) {
|
||||
const anchorTag = svgRoot.ownerDocument!.createElementNS(SVG_NS, "a");
|
||||
anchorTag.setAttribute("href", normalizeLink(element.link || ""));
|
||||
anchorTag.setAttribute("target", "_blank");
|
||||
anchorTag.setAttribute("rel", "noopener noreferrer");
|
||||
anchorTag.style.borderRadius = `${radius}px`;
|
||||
|
||||
embeddableNode.appendChild(anchorTag);
|
||||
} else {
|
||||
const foreignObject = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"foreignObject",
|
||||
);
|
||||
foreignObject.style.width = `${element.width}px`;
|
||||
foreignObject.style.height = `${element.height}px`;
|
||||
foreignObject.style.border = "none";
|
||||
const div = foreignObject.ownerDocument!.createElementNS(SVG_NS, "div");
|
||||
div.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
|
||||
div.style.width = "100%";
|
||||
div.style.height = "100%";
|
||||
const iframe = div.ownerDocument!.createElement("iframe");
|
||||
iframe.src = embedLink?.link ?? "";
|
||||
iframe.style.width = "100%";
|
||||
iframe.style.height = "100%";
|
||||
iframe.style.border = "none";
|
||||
iframe.style.borderRadius = `${radius}px`;
|
||||
iframe.style.top = "0";
|
||||
iframe.style.left = "0";
|
||||
iframe.allowFullscreen = true;
|
||||
div.appendChild(iframe);
|
||||
foreignObject.appendChild(div);
|
||||
|
||||
embeddableNode.appendChild(foreignObject);
|
||||
}
|
||||
addToRoot(embeddableNode, element);
|
||||
break;
|
||||
}
|
||||
case "line":
|
||||
case "arrow": {
|
||||
const boundText = getBoundTextElement(element, elementsMap);
|
||||
const maskPath = svgRoot.ownerDocument!.createElementNS(SVG_NS, "mask");
|
||||
if (boundText) {
|
||||
maskPath.setAttribute("id", `mask-${element.id}`);
|
||||
const maskRectVisible = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
offsetX = offsetX || 0;
|
||||
offsetY = offsetY || 0;
|
||||
maskRectVisible.setAttribute("x", "0");
|
||||
maskRectVisible.setAttribute("y", "0");
|
||||
maskRectVisible.setAttribute("fill", "#fff");
|
||||
maskRectVisible.setAttribute(
|
||||
"width",
|
||||
`${element.width + 100 + offsetX}`,
|
||||
);
|
||||
maskRectVisible.setAttribute(
|
||||
"height",
|
||||
`${element.height + 100 + offsetY}`,
|
||||
);
|
||||
|
||||
maskPath.appendChild(maskRectVisible);
|
||||
const maskRectInvisible = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
const boundTextCoords = LinearElementEditor.getBoundTextElementPosition(
|
||||
element,
|
||||
boundText,
|
||||
);
|
||||
|
||||
const maskX = offsetX + boundTextCoords.x - element.x;
|
||||
const maskY = offsetY + boundTextCoords.y - element.y;
|
||||
|
||||
maskRectInvisible.setAttribute("x", maskX.toString());
|
||||
maskRectInvisible.setAttribute("y", maskY.toString());
|
||||
maskRectInvisible.setAttribute("fill", "#000");
|
||||
maskRectInvisible.setAttribute("width", `${boundText.width}`);
|
||||
maskRectInvisible.setAttribute("height", `${boundText.height}`);
|
||||
maskRectInvisible.setAttribute("opacity", "1");
|
||||
maskPath.appendChild(maskRectInvisible);
|
||||
}
|
||||
const group = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (boundText) {
|
||||
group.setAttribute("mask", `url(#mask-${element.id})`);
|
||||
}
|
||||
group.setAttribute("stroke-linecap", "round");
|
||||
|
||||
const shapes = ShapeCache.generateElementShape(element, renderConfig);
|
||||
shapes.forEach((shape) => {
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
if (
|
||||
element.type === "line" &&
|
||||
isPathALoop(element.points) &&
|
||||
element.backgroundColor !== "transparent"
|
||||
) {
|
||||
node.setAttribute("fill-rule", "evenodd");
|
||||
}
|
||||
group.appendChild(node);
|
||||
});
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[group, maskPath],
|
||||
renderConfig.frameRendering,
|
||||
);
|
||||
if (g) {
|
||||
addToRoot(g, element);
|
||||
root.appendChild(g);
|
||||
} else {
|
||||
addToRoot(group, element);
|
||||
root.append(maskPath);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "freedraw": {
|
||||
const backgroundFillShape = ShapeCache.generateElementShape(
|
||||
element,
|
||||
renderConfig,
|
||||
);
|
||||
const node = backgroundFillShape
|
||||
? roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
backgroundFillShape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
)
|
||||
: svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
node.setAttribute("stroke", "none");
|
||||
const path = svgRoot.ownerDocument!.createElementNS(SVG_NS, "path");
|
||||
path.setAttribute("fill", element.strokeColor);
|
||||
path.setAttribute("d", getFreeDrawSvgPath(element));
|
||||
node.appendChild(path);
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
break;
|
||||
}
|
||||
case "image": {
|
||||
const width = Math.round(element.width);
|
||||
const height = Math.round(element.height);
|
||||
const fileData =
|
||||
isInitializedImageElement(element) && files[element.fileId];
|
||||
if (fileData) {
|
||||
const symbolId = `image-${fileData.id}`;
|
||||
let symbol = svgRoot.querySelector(`#${symbolId}`);
|
||||
if (!symbol) {
|
||||
symbol = svgRoot.ownerDocument!.createElementNS(SVG_NS, "symbol");
|
||||
symbol.id = symbolId;
|
||||
|
||||
const image = svgRoot.ownerDocument!.createElementNS(SVG_NS, "image");
|
||||
|
||||
image.setAttribute("width", "100%");
|
||||
image.setAttribute("height", "100%");
|
||||
image.setAttribute("href", fileData.dataURL);
|
||||
|
||||
symbol.appendChild(image);
|
||||
|
||||
root.prepend(symbol);
|
||||
}
|
||||
|
||||
const use = svgRoot.ownerDocument!.createElementNS(SVG_NS, "use");
|
||||
use.setAttribute("href", `#${symbolId}`);
|
||||
|
||||
// in dark theme, revert the image color filter
|
||||
if (
|
||||
renderConfig.exportWithDarkMode &&
|
||||
fileData.mimeType !== MIME_TYPES.svg
|
||||
) {
|
||||
use.setAttribute("filter", IMAGE_INVERT_FILTER);
|
||||
}
|
||||
|
||||
use.setAttribute("width", `${width}`);
|
||||
use.setAttribute("height", `${height}`);
|
||||
use.setAttribute("opacity", `${opacity}`);
|
||||
|
||||
// We first apply `scale` transforms (horizontal/vertical mirroring)
|
||||
// on the <use> element, then apply translation and rotation
|
||||
// on the <g> element which wraps the <use>.
|
||||
// Doing this separately is a quick hack to to work around compositing
|
||||
// the transformations correctly (the transform-origin was not being
|
||||
// applied correctly).
|
||||
if (element.scale[0] !== 1 || element.scale[1] !== 1) {
|
||||
const translateX = element.scale[0] !== 1 ? -width : 0;
|
||||
const translateY = element.scale[1] !== 1 ? -height : 0;
|
||||
use.setAttribute(
|
||||
"transform",
|
||||
`scale(${element.scale[0]}, ${element.scale[1]}) translate(${translateX} ${translateY})`,
|
||||
);
|
||||
}
|
||||
|
||||
const g = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
g.appendChild(use);
|
||||
g.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
if (element.roundness) {
|
||||
const clipPath = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"clipPath",
|
||||
);
|
||||
clipPath.id = `image-clipPath-${element.id}`;
|
||||
|
||||
const clipRect = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
const radius = getCornerRadius(
|
||||
Math.min(element.width, element.height),
|
||||
element,
|
||||
);
|
||||
clipRect.setAttribute("width", `${element.width}`);
|
||||
clipRect.setAttribute("height", `${element.height}`);
|
||||
clipRect.setAttribute("rx", `${radius}`);
|
||||
clipRect.setAttribute("ry", `${radius}`);
|
||||
clipPath.appendChild(clipRect);
|
||||
addToRoot(clipPath, element);
|
||||
|
||||
g.setAttributeNS(SVG_NS, "clip-path", `url(#${clipPath.id})`);
|
||||
}
|
||||
|
||||
const clipG = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[g],
|
||||
renderConfig.frameRendering,
|
||||
);
|
||||
addToRoot(clipG || g, element);
|
||||
}
|
||||
break;
|
||||
}
|
||||
// frames are not rendered and only acts as a container
|
||||
case "frame":
|
||||
case "magicframe": {
|
||||
if (
|
||||
renderConfig.frameRendering.enabled &&
|
||||
renderConfig.frameRendering.outline
|
||||
) {
|
||||
const rect = document.createElementNS(SVG_NS, "rect");
|
||||
|
||||
rect.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
rect.setAttribute("width", `${element.width}px`);
|
||||
rect.setAttribute("height", `${element.height}px`);
|
||||
// Rounded corners
|
||||
rect.setAttribute("rx", FRAME_STYLE.radius.toString());
|
||||
rect.setAttribute("ry", FRAME_STYLE.radius.toString());
|
||||
|
||||
rect.setAttribute("fill", "none");
|
||||
rect.setAttribute("stroke", FRAME_STYLE.strokeColor);
|
||||
rect.setAttribute("stroke-width", FRAME_STYLE.strokeWidth.toString());
|
||||
|
||||
addToRoot(rect, element);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
if (isTextElement(element)) {
|
||||
const node = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
|
||||
const lineHeightPx = getLineHeightInPx(
|
||||
element.fontSize,
|
||||
element.lineHeight,
|
||||
);
|
||||
const horizontalOffset =
|
||||
element.textAlign === "center"
|
||||
? element.width / 2
|
||||
: element.textAlign === "right"
|
||||
? element.width
|
||||
: 0;
|
||||
const direction = isRTL(element.text) ? "rtl" : "ltr";
|
||||
const textAnchor =
|
||||
element.textAlign === "center"
|
||||
? "middle"
|
||||
: element.textAlign === "right" || direction === "rtl"
|
||||
? "end"
|
||||
: "start";
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const text = svgRoot.ownerDocument!.createElementNS(SVG_NS, "text");
|
||||
text.textContent = lines[i];
|
||||
text.setAttribute("x", `${horizontalOffset}`);
|
||||
text.setAttribute("y", `${i * lineHeightPx}`);
|
||||
text.setAttribute("font-family", getFontFamilyString(element));
|
||||
text.setAttribute("font-size", `${element.fontSize}px`);
|
||||
text.setAttribute("fill", element.strokeColor);
|
||||
text.setAttribute("text-anchor", textAnchor);
|
||||
text.setAttribute("style", "white-space: pre;");
|
||||
text.setAttribute("direction", direction);
|
||||
text.setAttribute("dominant-baseline", "text-before-edge");
|
||||
node.appendChild(text);
|
||||
}
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
} else {
|
||||
// @ts-ignore
|
||||
throw new Error(`Unimplemented type ${element.type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const pathsCache = new WeakMap<ExcalidrawFreeDrawElement, Path2D>([]);
|
||||
|
||||
export function generateFreeDrawShape(element: ExcalidrawFreeDrawElement) {
|
||||
|
||||
+1246
-646
File diff suppressed because it is too large
Load Diff
@@ -1,370 +0,0 @@
|
||||
import { FRAME_STYLE } from "../constants";
|
||||
import { getElementAbsoluteCoords } from "../element";
|
||||
|
||||
import {
|
||||
elementOverlapsWithFrame,
|
||||
getTargetFrame,
|
||||
isElementInFrame,
|
||||
} from "../frame";
|
||||
import {
|
||||
isEmbeddableElement,
|
||||
isIframeLikeElement,
|
||||
} from "../element/typeChecks";
|
||||
import { renderElement } from "../renderer/renderElement";
|
||||
import { createPlaceholderEmbeddableLabel } from "../element/embeddable";
|
||||
import { StaticCanvasAppState, Zoom } from "../types";
|
||||
import {
|
||||
ElementsMap,
|
||||
ExcalidrawFrameLikeElement,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "../element/types";
|
||||
import {
|
||||
StaticCanvasRenderConfig,
|
||||
StaticSceneRenderConfig,
|
||||
} from "../scene/types";
|
||||
import {
|
||||
EXTERNAL_LINK_IMG,
|
||||
getLinkHandleFromCoords,
|
||||
} from "../components/hyperlink/helpers";
|
||||
import { bootstrapCanvas, getNormalizedCanvasDimensions } from "./helpers";
|
||||
import { throttleRAF } from "../utils";
|
||||
|
||||
const strokeGrid = (
|
||||
context: CanvasRenderingContext2D,
|
||||
gridSize: number,
|
||||
scrollX: number,
|
||||
scrollY: number,
|
||||
zoom: Zoom,
|
||||
width: number,
|
||||
height: number,
|
||||
) => {
|
||||
const BOLD_LINE_FREQUENCY = 5;
|
||||
|
||||
enum GridLineColor {
|
||||
Bold = "#cccccc",
|
||||
Regular = "#e5e5e5",
|
||||
}
|
||||
|
||||
const offsetX =
|
||||
-Math.round(zoom.value / gridSize) * gridSize + (scrollX % gridSize);
|
||||
const offsetY =
|
||||
-Math.round(zoom.value / gridSize) * gridSize + (scrollY % gridSize);
|
||||
|
||||
const lineWidth = Math.min(1 / zoom.value, 1);
|
||||
|
||||
const spaceWidth = 1 / zoom.value;
|
||||
const lineDash = [lineWidth * 3, spaceWidth + (lineWidth + spaceWidth)];
|
||||
|
||||
context.save();
|
||||
context.lineWidth = lineWidth;
|
||||
|
||||
for (let x = offsetX; x < offsetX + width + gridSize * 2; x += gridSize) {
|
||||
const isBold =
|
||||
Math.round(x - scrollX) % (BOLD_LINE_FREQUENCY * gridSize) === 0;
|
||||
context.beginPath();
|
||||
context.setLineDash(isBold ? [] : lineDash);
|
||||
context.strokeStyle = isBold ? GridLineColor.Bold : GridLineColor.Regular;
|
||||
context.moveTo(x, offsetY - gridSize);
|
||||
context.lineTo(x, offsetY + height + gridSize * 2);
|
||||
context.stroke();
|
||||
}
|
||||
for (let y = offsetY; y < offsetY + height + gridSize * 2; y += gridSize) {
|
||||
const isBold =
|
||||
Math.round(y - scrollY) % (BOLD_LINE_FREQUENCY * gridSize) === 0;
|
||||
context.beginPath();
|
||||
context.setLineDash(isBold ? [] : lineDash);
|
||||
context.strokeStyle = isBold ? GridLineColor.Bold : GridLineColor.Regular;
|
||||
context.moveTo(offsetX - gridSize, y);
|
||||
context.lineTo(offsetX + width + gridSize * 2, y);
|
||||
context.stroke();
|
||||
}
|
||||
context.restore();
|
||||
};
|
||||
|
||||
const frameClip = (
|
||||
frame: ExcalidrawFrameLikeElement,
|
||||
context: CanvasRenderingContext2D,
|
||||
renderConfig: StaticCanvasRenderConfig,
|
||||
appState: StaticCanvasAppState,
|
||||
) => {
|
||||
context.translate(frame.x + appState.scrollX, frame.y + appState.scrollY);
|
||||
context.beginPath();
|
||||
if (context.roundRect) {
|
||||
context.roundRect(
|
||||
0,
|
||||
0,
|
||||
frame.width,
|
||||
frame.height,
|
||||
FRAME_STYLE.radius / appState.zoom.value,
|
||||
);
|
||||
} else {
|
||||
context.rect(0, 0, frame.width, frame.height);
|
||||
}
|
||||
context.clip();
|
||||
context.translate(
|
||||
-(frame.x + appState.scrollX),
|
||||
-(frame.y + appState.scrollY),
|
||||
);
|
||||
};
|
||||
|
||||
let linkCanvasCache: any;
|
||||
const renderLinkIcon = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
context: CanvasRenderingContext2D,
|
||||
appState: StaticCanvasAppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
if (element.link && !appState.selectedElementIds[element.id]) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
const [x, y, width, height] = getLinkHandleFromCoords(
|
||||
[x1, y1, x2, y2],
|
||||
element.angle,
|
||||
appState,
|
||||
);
|
||||
const centerX = x + width / 2;
|
||||
const centerY = y + height / 2;
|
||||
context.save();
|
||||
context.translate(appState.scrollX + centerX, appState.scrollY + centerY);
|
||||
context.rotate(element.angle);
|
||||
|
||||
if (!linkCanvasCache || linkCanvasCache.zoom !== appState.zoom.value) {
|
||||
linkCanvasCache = document.createElement("canvas");
|
||||
linkCanvasCache.zoom = appState.zoom.value;
|
||||
linkCanvasCache.width =
|
||||
width * window.devicePixelRatio * appState.zoom.value;
|
||||
linkCanvasCache.height =
|
||||
height * window.devicePixelRatio * appState.zoom.value;
|
||||
const linkCanvasCacheContext = linkCanvasCache.getContext("2d")!;
|
||||
linkCanvasCacheContext.scale(
|
||||
window.devicePixelRatio * appState.zoom.value,
|
||||
window.devicePixelRatio * appState.zoom.value,
|
||||
);
|
||||
linkCanvasCacheContext.fillStyle = "#fff";
|
||||
linkCanvasCacheContext.fillRect(0, 0, width, height);
|
||||
linkCanvasCacheContext.drawImage(EXTERNAL_LINK_IMG, 0, 0, width, height);
|
||||
linkCanvasCacheContext.restore();
|
||||
context.drawImage(
|
||||
linkCanvasCache,
|
||||
x - centerX,
|
||||
y - centerY,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
} else {
|
||||
context.drawImage(
|
||||
linkCanvasCache,
|
||||
x - centerX,
|
||||
y - centerY,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
}
|
||||
context.restore();
|
||||
}
|
||||
};
|
||||
const _renderStaticScene = ({
|
||||
canvas,
|
||||
rc,
|
||||
elementsMap,
|
||||
allElementsMap,
|
||||
visibleElements,
|
||||
scale,
|
||||
appState,
|
||||
renderConfig,
|
||||
}: StaticSceneRenderConfig) => {
|
||||
if (canvas === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { renderGrid = true, isExporting } = renderConfig;
|
||||
|
||||
const [normalizedWidth, normalizedHeight] = getNormalizedCanvasDimensions(
|
||||
canvas,
|
||||
scale,
|
||||
);
|
||||
|
||||
const context = bootstrapCanvas({
|
||||
canvas,
|
||||
scale,
|
||||
normalizedWidth,
|
||||
normalizedHeight,
|
||||
theme: appState.theme,
|
||||
isExporting,
|
||||
viewBackgroundColor: appState.viewBackgroundColor,
|
||||
});
|
||||
|
||||
// Apply zoom
|
||||
context.scale(appState.zoom.value, appState.zoom.value);
|
||||
|
||||
// Grid
|
||||
if (renderGrid && appState.gridSize) {
|
||||
strokeGrid(
|
||||
context,
|
||||
appState.gridSize,
|
||||
appState.scrollX,
|
||||
appState.scrollY,
|
||||
appState.zoom,
|
||||
normalizedWidth / appState.zoom.value,
|
||||
normalizedHeight / appState.zoom.value,
|
||||
);
|
||||
}
|
||||
|
||||
const groupsToBeAddedToFrame = new Set<string>();
|
||||
|
||||
visibleElements.forEach((element) => {
|
||||
if (
|
||||
element.groupIds.length > 0 &&
|
||||
appState.frameToHighlight &&
|
||||
appState.selectedElementIds[element.id] &&
|
||||
(elementOverlapsWithFrame(
|
||||
element,
|
||||
appState.frameToHighlight,
|
||||
elementsMap,
|
||||
) ||
|
||||
element.groupIds.find((groupId) => groupsToBeAddedToFrame.has(groupId)))
|
||||
) {
|
||||
element.groupIds.forEach((groupId) =>
|
||||
groupsToBeAddedToFrame.add(groupId),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Paint visible elements
|
||||
visibleElements
|
||||
.filter((el) => !isIframeLikeElement(el))
|
||||
.forEach((element) => {
|
||||
try {
|
||||
const frameId = element.frameId || appState.frameToHighlight?.id;
|
||||
|
||||
if (
|
||||
frameId &&
|
||||
appState.frameRendering.enabled &&
|
||||
appState.frameRendering.clip
|
||||
) {
|
||||
context.save();
|
||||
|
||||
const frame = getTargetFrame(element, elementsMap, appState);
|
||||
|
||||
// TODO do we need to check isElementInFrame here?
|
||||
if (frame && isElementInFrame(element, elementsMap, appState)) {
|
||||
frameClip(frame, context, renderConfig, appState);
|
||||
}
|
||||
renderElement(
|
||||
element,
|
||||
elementsMap,
|
||||
allElementsMap,
|
||||
rc,
|
||||
context,
|
||||
renderConfig,
|
||||
appState,
|
||||
);
|
||||
context.restore();
|
||||
} else {
|
||||
renderElement(
|
||||
element,
|
||||
elementsMap,
|
||||
allElementsMap,
|
||||
rc,
|
||||
context,
|
||||
renderConfig,
|
||||
appState,
|
||||
);
|
||||
}
|
||||
if (!isExporting) {
|
||||
renderLinkIcon(element, context, appState, elementsMap);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
|
||||
// render embeddables on top
|
||||
visibleElements
|
||||
.filter((el) => isIframeLikeElement(el))
|
||||
.forEach((element) => {
|
||||
try {
|
||||
const render = () => {
|
||||
renderElement(
|
||||
element,
|
||||
elementsMap,
|
||||
allElementsMap,
|
||||
rc,
|
||||
context,
|
||||
renderConfig,
|
||||
appState,
|
||||
);
|
||||
|
||||
if (
|
||||
isIframeLikeElement(element) &&
|
||||
(isExporting ||
|
||||
(isEmbeddableElement(element) &&
|
||||
renderConfig.embedsValidationStatus.get(element.id) !==
|
||||
true)) &&
|
||||
element.width &&
|
||||
element.height
|
||||
) {
|
||||
const label = createPlaceholderEmbeddableLabel(element);
|
||||
renderElement(
|
||||
label,
|
||||
elementsMap,
|
||||
allElementsMap,
|
||||
rc,
|
||||
context,
|
||||
renderConfig,
|
||||
appState,
|
||||
);
|
||||
}
|
||||
if (!isExporting) {
|
||||
renderLinkIcon(element, context, appState, elementsMap);
|
||||
}
|
||||
};
|
||||
// - when exporting the whole canvas, we DO NOT apply clipping
|
||||
// - when we are exporting a particular frame, apply clipping
|
||||
// if the containing frame is not selected, apply clipping
|
||||
const frameId = element.frameId || appState.frameToHighlight?.id;
|
||||
|
||||
if (
|
||||
frameId &&
|
||||
appState.frameRendering.enabled &&
|
||||
appState.frameRendering.clip
|
||||
) {
|
||||
context.save();
|
||||
|
||||
const frame = getTargetFrame(element, elementsMap, appState);
|
||||
|
||||
if (frame && isElementInFrame(element, elementsMap, appState)) {
|
||||
frameClip(frame, context, renderConfig, appState);
|
||||
}
|
||||
render();
|
||||
context.restore();
|
||||
} else {
|
||||
render();
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/** throttled to animation framerate */
|
||||
export const renderStaticSceneThrottled = throttleRAF(
|
||||
(config: StaticSceneRenderConfig) => {
|
||||
_renderStaticScene(config);
|
||||
},
|
||||
{ trailing: true },
|
||||
);
|
||||
|
||||
/**
|
||||
* Static scene is the non-ui canvas where we render elements.
|
||||
*/
|
||||
export const renderStaticScene = (
|
||||
renderConfig: StaticSceneRenderConfig,
|
||||
throttle?: boolean,
|
||||
) => {
|
||||
if (throttle) {
|
||||
renderStaticSceneThrottled(renderConfig);
|
||||
return;
|
||||
}
|
||||
|
||||
_renderStaticScene(renderConfig);
|
||||
};
|
||||
@@ -1,659 +0,0 @@
|
||||
import { Drawable } from "roughjs/bin/core";
|
||||
import { RoughSVG } from "roughjs/bin/svg";
|
||||
import {
|
||||
FRAME_STYLE,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
MIME_TYPES,
|
||||
SVG_NS,
|
||||
} from "../constants";
|
||||
import { normalizeLink, toValidURL } from "../data/url";
|
||||
import { getElementAbsoluteCoords } from "../element";
|
||||
import {
|
||||
createPlaceholderEmbeddableLabel,
|
||||
getEmbedLink,
|
||||
} from "../element/embeddable";
|
||||
import { LinearElementEditor } from "../element/linearElementEditor";
|
||||
import {
|
||||
getBoundTextElement,
|
||||
getContainerElement,
|
||||
getLineHeightInPx,
|
||||
getVerticalOffset,
|
||||
} from "../element/textElement";
|
||||
import {
|
||||
isArrowElement,
|
||||
isIframeLikeElement,
|
||||
isInitializedImageElement,
|
||||
isTextElement,
|
||||
} from "../element/typeChecks";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawTextElementWithContainer,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "../element/types";
|
||||
import { getContainingFrame } from "../frame";
|
||||
import { getCornerRadius, isPathALoop } from "../math";
|
||||
import { ShapeCache } from "../scene/ShapeCache";
|
||||
import { RenderableElementsMap, SVGRenderConfig } from "../scene/types";
|
||||
import { AppState, BinaryFiles } from "../types";
|
||||
import { getFontFamilyString, isRTL, isTestEnv } from "../utils";
|
||||
import { getFreeDrawSvgPath, IMAGE_INVERT_FILTER } from "./renderElement";
|
||||
|
||||
const roughSVGDrawWithPrecision = (
|
||||
rsvg: RoughSVG,
|
||||
drawable: Drawable,
|
||||
precision?: number,
|
||||
) => {
|
||||
if (typeof precision === "undefined") {
|
||||
return rsvg.draw(drawable);
|
||||
}
|
||||
const pshape: Drawable = {
|
||||
sets: drawable.sets,
|
||||
shape: drawable.shape,
|
||||
options: { ...drawable.options, fixedDecimalPlaceDigits: precision },
|
||||
};
|
||||
return rsvg.draw(pshape);
|
||||
};
|
||||
|
||||
const maybeWrapNodesInFrameClipPath = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
root: SVGElement,
|
||||
nodes: SVGElement[],
|
||||
frameRendering: AppState["frameRendering"],
|
||||
elementsMap: RenderableElementsMap,
|
||||
) => {
|
||||
if (!frameRendering.enabled || !frameRendering.clip) {
|
||||
return null;
|
||||
}
|
||||
const frame = getContainingFrame(element, elementsMap);
|
||||
if (frame) {
|
||||
const g = root.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
g.setAttributeNS(SVG_NS, "clip-path", `url(#${frame.id})`);
|
||||
nodes.forEach((node) => g.appendChild(node));
|
||||
return g;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const renderElementToSvg = (
|
||||
element: NonDeletedExcalidrawElement,
|
||||
elementsMap: RenderableElementsMap,
|
||||
rsvg: RoughSVG,
|
||||
svgRoot: SVGElement,
|
||||
files: BinaryFiles,
|
||||
offsetX: number,
|
||||
offsetY: number,
|
||||
renderConfig: SVGRenderConfig,
|
||||
) => {
|
||||
const offset = { x: offsetX, y: offsetY };
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||
let cx = (x2 - x1) / 2 - (element.x - x1);
|
||||
let cy = (y2 - y1) / 2 - (element.y - y1);
|
||||
if (isTextElement(element)) {
|
||||
const container = getContainerElement(element, elementsMap);
|
||||
if (isArrowElement(container)) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(container, elementsMap);
|
||||
|
||||
const boundTextCoords = LinearElementEditor.getBoundTextElementPosition(
|
||||
container,
|
||||
element as ExcalidrawTextElementWithContainer,
|
||||
elementsMap,
|
||||
);
|
||||
cx = (x2 - x1) / 2 - (boundTextCoords.x - x1);
|
||||
cy = (y2 - y1) / 2 - (boundTextCoords.y - y1);
|
||||
offsetX = offsetX + boundTextCoords.x - element.x;
|
||||
offsetY = offsetY + boundTextCoords.y - element.y;
|
||||
}
|
||||
}
|
||||
const degree = (180 * element.angle) / Math.PI;
|
||||
|
||||
// element to append node to, most of the time svgRoot
|
||||
let root = svgRoot;
|
||||
|
||||
// if the element has a link, create an anchor tag and make that the new root
|
||||
if (element.link) {
|
||||
const anchorTag = svgRoot.ownerDocument!.createElementNS(SVG_NS, "a");
|
||||
anchorTag.setAttribute("href", normalizeLink(element.link));
|
||||
root.appendChild(anchorTag);
|
||||
root = anchorTag;
|
||||
}
|
||||
|
||||
const addToRoot = (node: SVGElement, element: ExcalidrawElement) => {
|
||||
if (isTestEnv()) {
|
||||
node.setAttribute("data-id", element.id);
|
||||
}
|
||||
root.appendChild(node);
|
||||
};
|
||||
|
||||
const opacity =
|
||||
((getContainingFrame(element, elementsMap)?.opacity ?? 100) *
|
||||
element.opacity) /
|
||||
10000;
|
||||
|
||||
switch (element.type) {
|
||||
case "selection": {
|
||||
// Since this is used only during editing experience, which is canvas based,
|
||||
// this should not happen
|
||||
throw new Error("Selection rendering is not supported for SVG");
|
||||
}
|
||||
case "rectangle":
|
||||
case "diamond":
|
||||
case "ellipse": {
|
||||
const shape = ShapeCache.generateElementShape(element, null);
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute("stroke-linecap", "round");
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
break;
|
||||
}
|
||||
case "iframe":
|
||||
case "embeddable": {
|
||||
// render placeholder rectangle
|
||||
const shape = ShapeCache.generateElementShape(element, renderConfig);
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
const opacity = element.opacity / 100;
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute("stroke-linecap", "round");
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
addToRoot(node, element);
|
||||
|
||||
const label: ExcalidrawElement =
|
||||
createPlaceholderEmbeddableLabel(element);
|
||||
renderElementToSvg(
|
||||
label,
|
||||
elementsMap,
|
||||
rsvg,
|
||||
root,
|
||||
files,
|
||||
label.x + offset.x - element.x,
|
||||
label.y + offset.y - element.y,
|
||||
renderConfig,
|
||||
);
|
||||
|
||||
// render embeddable element + iframe
|
||||
const embeddableNode = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
embeddableNode.setAttribute("stroke-linecap", "round");
|
||||
embeddableNode.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
while (embeddableNode.firstChild) {
|
||||
embeddableNode.removeChild(embeddableNode.firstChild);
|
||||
}
|
||||
const radius = getCornerRadius(
|
||||
Math.min(element.width, element.height),
|
||||
element,
|
||||
);
|
||||
|
||||
const embedLink = getEmbedLink(toValidURL(element.link || ""));
|
||||
|
||||
// if rendering embeddables explicitly disabled or
|
||||
// embedding documents via srcdoc (which doesn't seem to work for SVGs)
|
||||
// replace with a link instead
|
||||
if (
|
||||
renderConfig.renderEmbeddables === false ||
|
||||
embedLink?.type === "document"
|
||||
) {
|
||||
const anchorTag = svgRoot.ownerDocument!.createElementNS(SVG_NS, "a");
|
||||
anchorTag.setAttribute("href", normalizeLink(element.link || ""));
|
||||
anchorTag.setAttribute("target", "_blank");
|
||||
anchorTag.setAttribute("rel", "noopener noreferrer");
|
||||
anchorTag.style.borderRadius = `${radius}px`;
|
||||
|
||||
embeddableNode.appendChild(anchorTag);
|
||||
} else {
|
||||
const foreignObject = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"foreignObject",
|
||||
);
|
||||
foreignObject.style.width = `${element.width}px`;
|
||||
foreignObject.style.height = `${element.height}px`;
|
||||
foreignObject.style.border = "none";
|
||||
const div = foreignObject.ownerDocument!.createElementNS(SVG_NS, "div");
|
||||
div.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
|
||||
div.style.width = "100%";
|
||||
div.style.height = "100%";
|
||||
const iframe = div.ownerDocument!.createElement("iframe");
|
||||
iframe.src = embedLink?.link ?? "";
|
||||
iframe.style.width = "100%";
|
||||
iframe.style.height = "100%";
|
||||
iframe.style.border = "none";
|
||||
iframe.style.borderRadius = `${radius}px`;
|
||||
iframe.style.top = "0";
|
||||
iframe.style.left = "0";
|
||||
iframe.allowFullscreen = true;
|
||||
div.appendChild(iframe);
|
||||
foreignObject.appendChild(div);
|
||||
|
||||
embeddableNode.appendChild(foreignObject);
|
||||
}
|
||||
addToRoot(embeddableNode, element);
|
||||
break;
|
||||
}
|
||||
case "line":
|
||||
case "arrow": {
|
||||
const boundText = getBoundTextElement(element, elementsMap);
|
||||
const maskPath = svgRoot.ownerDocument!.createElementNS(SVG_NS, "mask");
|
||||
if (boundText) {
|
||||
maskPath.setAttribute("id", `mask-${element.id}`);
|
||||
const maskRectVisible = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
offsetX = offsetX || 0;
|
||||
offsetY = offsetY || 0;
|
||||
maskRectVisible.setAttribute("x", "0");
|
||||
maskRectVisible.setAttribute("y", "0");
|
||||
maskRectVisible.setAttribute("fill", "#fff");
|
||||
maskRectVisible.setAttribute(
|
||||
"width",
|
||||
`${element.width + 100 + offsetX}`,
|
||||
);
|
||||
maskRectVisible.setAttribute(
|
||||
"height",
|
||||
`${element.height + 100 + offsetY}`,
|
||||
);
|
||||
|
||||
maskPath.appendChild(maskRectVisible);
|
||||
const maskRectInvisible = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
const boundTextCoords = LinearElementEditor.getBoundTextElementPosition(
|
||||
element,
|
||||
boundText,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
const maskX = offsetX + boundTextCoords.x - element.x;
|
||||
const maskY = offsetY + boundTextCoords.y - element.y;
|
||||
|
||||
maskRectInvisible.setAttribute("x", maskX.toString());
|
||||
maskRectInvisible.setAttribute("y", maskY.toString());
|
||||
maskRectInvisible.setAttribute("fill", "#000");
|
||||
maskRectInvisible.setAttribute("width", `${boundText.width}`);
|
||||
maskRectInvisible.setAttribute("height", `${boundText.height}`);
|
||||
maskRectInvisible.setAttribute("opacity", "1");
|
||||
maskPath.appendChild(maskRectInvisible);
|
||||
}
|
||||
const group = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (boundText) {
|
||||
group.setAttribute("mask", `url(#mask-${element.id})`);
|
||||
}
|
||||
group.setAttribute("stroke-linecap", "round");
|
||||
|
||||
const shapes = ShapeCache.generateElementShape(element, renderConfig);
|
||||
shapes.forEach((shape) => {
|
||||
const node = roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
shape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
);
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
if (
|
||||
element.type === "line" &&
|
||||
isPathALoop(element.points) &&
|
||||
element.backgroundColor !== "transparent"
|
||||
) {
|
||||
node.setAttribute("fill-rule", "evenodd");
|
||||
}
|
||||
group.appendChild(node);
|
||||
});
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[group, maskPath],
|
||||
renderConfig.frameRendering,
|
||||
elementsMap,
|
||||
);
|
||||
if (g) {
|
||||
addToRoot(g, element);
|
||||
root.appendChild(g);
|
||||
} else {
|
||||
addToRoot(group, element);
|
||||
root.append(maskPath);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "freedraw": {
|
||||
const backgroundFillShape = ShapeCache.generateElementShape(
|
||||
element,
|
||||
renderConfig,
|
||||
);
|
||||
const node = backgroundFillShape
|
||||
? roughSVGDrawWithPrecision(
|
||||
rsvg,
|
||||
backgroundFillShape,
|
||||
MAX_DECIMALS_FOR_SVG_EXPORT,
|
||||
)
|
||||
: svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
node.setAttribute("stroke", "none");
|
||||
const path = svgRoot.ownerDocument!.createElementNS(SVG_NS, "path");
|
||||
path.setAttribute("fill", element.strokeColor);
|
||||
path.setAttribute("d", getFreeDrawSvgPath(element));
|
||||
node.appendChild(path);
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
break;
|
||||
}
|
||||
case "image": {
|
||||
const width = Math.round(element.width);
|
||||
const height = Math.round(element.height);
|
||||
const fileData =
|
||||
isInitializedImageElement(element) && files[element.fileId];
|
||||
if (fileData) {
|
||||
const symbolId = `image-${fileData.id}`;
|
||||
let symbol = svgRoot.querySelector(`#${symbolId}`);
|
||||
if (!symbol) {
|
||||
symbol = svgRoot.ownerDocument!.createElementNS(SVG_NS, "symbol");
|
||||
symbol.id = symbolId;
|
||||
|
||||
const image = svgRoot.ownerDocument!.createElementNS(SVG_NS, "image");
|
||||
|
||||
image.setAttribute("width", "100%");
|
||||
image.setAttribute("height", "100%");
|
||||
image.setAttribute("href", fileData.dataURL);
|
||||
|
||||
symbol.appendChild(image);
|
||||
|
||||
root.prepend(symbol);
|
||||
}
|
||||
|
||||
const use = svgRoot.ownerDocument!.createElementNS(SVG_NS, "use");
|
||||
use.setAttribute("href", `#${symbolId}`);
|
||||
|
||||
// in dark theme, revert the image color filter
|
||||
if (
|
||||
renderConfig.exportWithDarkMode &&
|
||||
fileData.mimeType !== MIME_TYPES.svg
|
||||
) {
|
||||
use.setAttribute("filter", IMAGE_INVERT_FILTER);
|
||||
}
|
||||
|
||||
use.setAttribute("width", `${width}`);
|
||||
use.setAttribute("height", `${height}`);
|
||||
use.setAttribute("opacity", `${opacity}`);
|
||||
|
||||
// We first apply `scale` transforms (horizontal/vertical mirroring)
|
||||
// on the <use> element, then apply translation and rotation
|
||||
// on the <g> element which wraps the <use>.
|
||||
// Doing this separately is a quick hack to to work around compositing
|
||||
// the transformations correctly (the transform-origin was not being
|
||||
// applied correctly).
|
||||
if (element.scale[0] !== 1 || element.scale[1] !== 1) {
|
||||
const translateX = element.scale[0] !== 1 ? -width : 0;
|
||||
const translateY = element.scale[1] !== 1 ? -height : 0;
|
||||
use.setAttribute(
|
||||
"transform",
|
||||
`scale(${element.scale[0]}, ${element.scale[1]}) translate(${translateX} ${translateY})`,
|
||||
);
|
||||
}
|
||||
|
||||
const g = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
g.appendChild(use);
|
||||
g.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
if (element.roundness) {
|
||||
const clipPath = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"clipPath",
|
||||
);
|
||||
clipPath.id = `image-clipPath-${element.id}`;
|
||||
|
||||
const clipRect = svgRoot.ownerDocument!.createElementNS(
|
||||
SVG_NS,
|
||||
"rect",
|
||||
);
|
||||
const radius = getCornerRadius(
|
||||
Math.min(element.width, element.height),
|
||||
element,
|
||||
);
|
||||
clipRect.setAttribute("width", `${element.width}`);
|
||||
clipRect.setAttribute("height", `${element.height}`);
|
||||
clipRect.setAttribute("rx", `${radius}`);
|
||||
clipRect.setAttribute("ry", `${radius}`);
|
||||
clipPath.appendChild(clipRect);
|
||||
addToRoot(clipPath, element);
|
||||
|
||||
g.setAttributeNS(SVG_NS, "clip-path", `url(#${clipPath.id})`);
|
||||
}
|
||||
|
||||
const clipG = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[g],
|
||||
renderConfig.frameRendering,
|
||||
elementsMap,
|
||||
);
|
||||
addToRoot(clipG || g, element);
|
||||
}
|
||||
break;
|
||||
}
|
||||
// frames are not rendered and only acts as a container
|
||||
case "frame":
|
||||
case "magicframe": {
|
||||
if (
|
||||
renderConfig.frameRendering.enabled &&
|
||||
renderConfig.frameRendering.outline
|
||||
) {
|
||||
const rect = document.createElementNS(SVG_NS, "rect");
|
||||
|
||||
rect.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
|
||||
rect.setAttribute("width", `${element.width}px`);
|
||||
rect.setAttribute("height", `${element.height}px`);
|
||||
// Rounded corners
|
||||
rect.setAttribute("rx", FRAME_STYLE.radius.toString());
|
||||
rect.setAttribute("ry", FRAME_STYLE.radius.toString());
|
||||
|
||||
rect.setAttribute("fill", "none");
|
||||
rect.setAttribute("stroke", FRAME_STYLE.strokeColor);
|
||||
rect.setAttribute("stroke-width", FRAME_STYLE.strokeWidth.toString());
|
||||
|
||||
addToRoot(rect, element);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
if (isTextElement(element)) {
|
||||
const node = svgRoot.ownerDocument!.createElementNS(SVG_NS, "g");
|
||||
if (opacity !== 1) {
|
||||
node.setAttribute("stroke-opacity", `${opacity}`);
|
||||
node.setAttribute("fill-opacity", `${opacity}`);
|
||||
}
|
||||
|
||||
node.setAttribute(
|
||||
"transform",
|
||||
`translate(${offsetX || 0} ${
|
||||
offsetY || 0
|
||||
}) rotate(${degree} ${cx} ${cy})`,
|
||||
);
|
||||
const lines = element.text.replace(/\r\n?/g, "\n").split("\n");
|
||||
const lineHeightPx = getLineHeightInPx(
|
||||
element.fontSize,
|
||||
element.lineHeight,
|
||||
);
|
||||
const horizontalOffset =
|
||||
element.textAlign === "center"
|
||||
? element.width / 2
|
||||
: element.textAlign === "right"
|
||||
? element.width
|
||||
: 0;
|
||||
const verticalOffset = getVerticalOffset(
|
||||
element.fontFamily,
|
||||
element.fontSize,
|
||||
lineHeightPx,
|
||||
);
|
||||
const direction = isRTL(element.text) ? "rtl" : "ltr";
|
||||
const textAnchor =
|
||||
element.textAlign === "center"
|
||||
? "middle"
|
||||
: element.textAlign === "right" || direction === "rtl"
|
||||
? "end"
|
||||
: "start";
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const text = svgRoot.ownerDocument!.createElementNS(SVG_NS, "text");
|
||||
text.textContent = lines[i];
|
||||
text.setAttribute("x", `${horizontalOffset}`);
|
||||
text.setAttribute("y", `${i * lineHeightPx + verticalOffset}`);
|
||||
text.setAttribute("font-family", getFontFamilyString(element));
|
||||
text.setAttribute("font-size", `${element.fontSize}px`);
|
||||
text.setAttribute("fill", element.strokeColor);
|
||||
text.setAttribute("text-anchor", textAnchor);
|
||||
text.setAttribute("style", "white-space: pre;");
|
||||
text.setAttribute("direction", direction);
|
||||
text.setAttribute("dominant-baseline", "alphabetic");
|
||||
node.appendChild(text);
|
||||
}
|
||||
|
||||
const g = maybeWrapNodesInFrameClipPath(
|
||||
element,
|
||||
root,
|
||||
[node],
|
||||
renderConfig.frameRendering,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
addToRoot(g || node, element);
|
||||
} else {
|
||||
// @ts-ignore
|
||||
throw new Error(`Unimplemented type ${element.type}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const renderSceneToSvg = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
elementsMap: RenderableElementsMap,
|
||||
rsvg: RoughSVG,
|
||||
svgRoot: SVGElement,
|
||||
files: BinaryFiles,
|
||||
renderConfig: SVGRenderConfig,
|
||||
) => {
|
||||
if (!svgRoot) {
|
||||
return;
|
||||
}
|
||||
|
||||
// render elements
|
||||
elements
|
||||
.filter((el) => !isIframeLikeElement(el))
|
||||
.forEach((element) => {
|
||||
if (!element.isDeleted) {
|
||||
try {
|
||||
renderElementToSvg(
|
||||
element,
|
||||
elementsMap,
|
||||
rsvg,
|
||||
svgRoot,
|
||||
files,
|
||||
element.x + renderConfig.offsetX,
|
||||
element.y + renderConfig.offsetY,
|
||||
renderConfig,
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// render embeddables on top
|
||||
elements
|
||||
.filter((el) => isIframeLikeElement(el))
|
||||
.forEach((element) => {
|
||||
if (!element.isDeleted) {
|
||||
try {
|
||||
renderElementToSvg(
|
||||
element,
|
||||
elementsMap,
|
||||
rsvg,
|
||||
svgRoot,
|
||||
files,
|
||||
element.x + renderConfig.offsetX,
|
||||
element.y + renderConfig.offsetY,
|
||||
renderConfig,
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -60,8 +60,10 @@ export class Fonts {
|
||||
return newElementWith(element, {
|
||||
...refreshTextDimensions(
|
||||
element,
|
||||
getContainerElement(element, this.scene.getNonDeletedElementsMap()),
|
||||
this.scene.getNonDeletedElementsMap(),
|
||||
getContainerElement(
|
||||
element,
|
||||
this.scene.getElementsMapIncludingDeleted(),
|
||||
),
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,9 +4,7 @@ import {
|
||||
NonDeletedElementsMap,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "../element/types";
|
||||
import { renderInteractiveSceneThrottled } from "../renderer/interactiveScene";
|
||||
import { renderStaticSceneThrottled } from "../renderer/staticScene";
|
||||
|
||||
import { cancelRender } from "../renderer/renderScene";
|
||||
import { AppState } from "../types";
|
||||
import { memoize, toBrandedType } from "../utils";
|
||||
import Scene from "./Scene";
|
||||
@@ -42,19 +40,13 @@ export class Renderer {
|
||||
const visibleElements: NonDeletedExcalidrawElement[] = [];
|
||||
for (const element of elementsMap.values()) {
|
||||
if (
|
||||
isElementInViewport(
|
||||
element,
|
||||
width,
|
||||
height,
|
||||
{
|
||||
zoom,
|
||||
offsetLeft,
|
||||
offsetTop,
|
||||
scrollX,
|
||||
scrollY,
|
||||
},
|
||||
elementsMap,
|
||||
)
|
||||
isElementInViewport(element, width, height, {
|
||||
zoom,
|
||||
offsetLeft,
|
||||
offsetTop,
|
||||
scrollX,
|
||||
scrollY,
|
||||
})
|
||||
) {
|
||||
visibleElements.push(element);
|
||||
}
|
||||
@@ -149,8 +141,7 @@ export class Renderer {
|
||||
// NOTE Doesn't destroy everything (scene, rc, etc.) because it may not be
|
||||
// safe to break TS contract here (for upstream cases)
|
||||
public destroy() {
|
||||
renderInteractiveSceneThrottled.cancel();
|
||||
renderStaticSceneThrottled.cancel();
|
||||
cancelRender();
|
||||
this.getRenderableElements.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,16 +80,29 @@ class Scene {
|
||||
private static sceneMapByElement = new WeakMap<ExcalidrawElement, Scene>();
|
||||
private static sceneMapById = new Map<string, Scene>();
|
||||
|
||||
static mapElementToScene(elementKey: ElementKey, scene: Scene) {
|
||||
static mapElementToScene(
|
||||
elementKey: ElementKey,
|
||||
scene: Scene,
|
||||
/**
|
||||
* needed because of frame exporting hack.
|
||||
* elementId:Scene mapping will be removed completely, soon.
|
||||
*/
|
||||
mapElementIds = true,
|
||||
) {
|
||||
if (isIdKey(elementKey)) {
|
||||
if (!mapElementIds) {
|
||||
return;
|
||||
}
|
||||
// for cases where we don't have access to the element object
|
||||
// (e.g. restore serialized appState with id references)
|
||||
this.sceneMapById.set(elementKey, scene);
|
||||
} else {
|
||||
this.sceneMapByElement.set(elementKey, scene);
|
||||
// if mapping element objects, also cache the id string when later
|
||||
// looking up by id alone
|
||||
this.sceneMapById.set(elementKey.id, scene);
|
||||
if (!mapElementIds) {
|
||||
// if mapping element objects, also cache the id string when later
|
||||
// looking up by id alone
|
||||
this.sceneMapById.set(elementKey.id, scene);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +256,7 @@ class Scene {
|
||||
return didChange;
|
||||
}
|
||||
|
||||
replaceAllElements(nextElements: ElementsMapOrArray) {
|
||||
replaceAllElements(nextElements: ElementsMapOrArray, mapElementIds = true) {
|
||||
this.elements =
|
||||
// ts doesn't like `Array.isArray` of `instanceof Map`
|
||||
nextElements instanceof Array
|
||||
@@ -256,7 +269,7 @@ class Scene {
|
||||
nextFrameLikes.push(element);
|
||||
}
|
||||
this.elementsMap.set(element.id, element);
|
||||
Scene.mapElementToScene(element, this);
|
||||
Scene.mapElementToScene(element, this, mapElementIds);
|
||||
});
|
||||
const nonDeletedElements = getNonDeletedElements(this.elements);
|
||||
this.nonDeletedElements = nonDeletedElements.elements;
|
||||
|
||||
@@ -11,8 +11,14 @@ import {
|
||||
getCommonBounds,
|
||||
getElementAbsoluteCoords,
|
||||
} from "../element/bounds";
|
||||
import { renderSceneToSvg } from "../renderer/staticSvgScene";
|
||||
import { arrayToMap, distance, getFontString, toBrandedType } from "../utils";
|
||||
import { renderSceneToSvg, renderStaticScene } from "../renderer/renderScene";
|
||||
import {
|
||||
arrayToMap,
|
||||
cloneJSON,
|
||||
distance,
|
||||
getFontString,
|
||||
toBrandedType,
|
||||
} from "../utils";
|
||||
import { AppState, BinaryFiles } from "../types";
|
||||
import {
|
||||
DEFAULT_EXPORT_PADDING,
|
||||
@@ -36,12 +42,35 @@ import {
|
||||
import { newTextElement } from "../element";
|
||||
import { Mutable } from "../utility-types";
|
||||
import { newElementWith } from "../element/mutateElement";
|
||||
import Scene from "./Scene";
|
||||
import { isFrameElement, isFrameLikeElement } from "../element/typeChecks";
|
||||
import { RenderableElementsMap } from "./types";
|
||||
import { renderStaticScene } from "../renderer/staticScene";
|
||||
|
||||
const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
||||
|
||||
// getContainerElement and getBoundTextElement and potentially other helpers
|
||||
// depend on `Scene` which will not be available when these pure utils are
|
||||
// called outside initialized Excalidraw editor instance or even if called
|
||||
// from inside Excalidraw if the elements were never cached by Scene (e.g.
|
||||
// for library elements).
|
||||
//
|
||||
// As such, before passing the elements down, we need to initialize a custom
|
||||
// Scene instance and assign them to it.
|
||||
//
|
||||
// FIXME This is a super hacky workaround and we'll need to rewrite this soon.
|
||||
const __createSceneForElementsHack__ = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
) => {
|
||||
const scene = new Scene();
|
||||
// we can't duplicate elements to regenerate ids because we need the
|
||||
// orig ids when embedding. So we do another hack of not mapping element
|
||||
// ids to Scene instances so that we don't override the editor elements
|
||||
// mapping.
|
||||
// We still need to clone the objects themselves to regen references.
|
||||
scene.replaceAllElements(cloneJSON(elements), false);
|
||||
return scene;
|
||||
};
|
||||
|
||||
const truncateText = (element: ExcalidrawTextElement, maxWidth: number) => {
|
||||
if (element.width <= maxWidth) {
|
||||
return element;
|
||||
@@ -184,6 +213,9 @@ export const exportToCanvas = async (
|
||||
return { canvas, scale: appState.exportScale };
|
||||
},
|
||||
) => {
|
||||
const tempScene = __createSceneForElementsHack__(elements);
|
||||
elements = tempScene.getNonDeletedElements();
|
||||
|
||||
const frameRendering = getFrameRenderingConfig(
|
||||
exportingFrame ?? null,
|
||||
appState.frameRendering ?? null,
|
||||
@@ -249,6 +281,8 @@ export const exportToCanvas = async (
|
||||
},
|
||||
});
|
||||
|
||||
tempScene.destroy();
|
||||
|
||||
return canvas;
|
||||
};
|
||||
|
||||
@@ -272,6 +306,9 @@ export const exportToSvg = async (
|
||||
exportingFrame?: ExcalidrawFrameLikeElement | null;
|
||||
},
|
||||
): Promise<SVGSVGElement> => {
|
||||
const tempScene = __createSceneForElementsHack__(elements);
|
||||
elements = tempScene.getNonDeletedElements();
|
||||
|
||||
const frameRendering = getFrameRenderingConfig(
|
||||
opts?.exportingFrame ?? null,
|
||||
appState.frameRendering ?? null,
|
||||
@@ -355,9 +392,8 @@ export const exportToSvg = async (
|
||||
const frameElements = getFrameLikeElements(elements);
|
||||
|
||||
let exportingFrameClipPath = "";
|
||||
const elementsMap = arrayToMap(elements);
|
||||
for (const frame of frameElements) {
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(frame, elementsMap);
|
||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(frame);
|
||||
const cx = (x2 - x1) / 2 - (frame.x - x1);
|
||||
const cy = (y2 - y1) / 2 - (frame.y - y1);
|
||||
|
||||
@@ -433,6 +469,8 @@ export const exportToSvg = async (
|
||||
},
|
||||
);
|
||||
|
||||
tempScene.destroy();
|
||||
|
||||
return svgRoot;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,21 +1,20 @@
|
||||
import { getCommonBounds } from "../element";
|
||||
import { InteractiveCanvasAppState } from "../types";
|
||||
import { ScrollBars } from "./types";
|
||||
import { RenderableElementsMap, ScrollBars } from "./types";
|
||||
import { getGlobalCSSVariable } from "../utils";
|
||||
import { getLanguage } from "../i18n";
|
||||
import { ExcalidrawElement } from "../element/types";
|
||||
|
||||
export const SCROLLBAR_MARGIN = 4;
|
||||
export const SCROLLBAR_WIDTH = 6;
|
||||
export const SCROLLBAR_COLOR = "rgba(0,0,0,0.3)";
|
||||
|
||||
export const getScrollBars = (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
elements: RenderableElementsMap,
|
||||
viewportWidth: number,
|
||||
viewportHeight: number,
|
||||
appState: InteractiveCanvasAppState,
|
||||
): ScrollBars => {
|
||||
if (!elements.length) {
|
||||
if (!elements.size) {
|
||||
return {
|
||||
horizontal: null,
|
||||
vertical: null,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
ElementsMap,
|
||||
ElementsMapOrArray,
|
||||
ExcalidrawElement,
|
||||
NonDeletedExcalidrawElement,
|
||||
@@ -45,24 +44,18 @@ export const excludeElementsInFramesFromSelection = <
|
||||
export const getElementsWithinSelection = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
selection: NonDeletedExcalidrawElement,
|
||||
elementsMap: ElementsMap,
|
||||
excludeElementsInFrames: boolean = true,
|
||||
) => {
|
||||
const [selectionX1, selectionY1, selectionX2, selectionY2] =
|
||||
getElementAbsoluteCoords(selection, elementsMap);
|
||||
getElementAbsoluteCoords(selection);
|
||||
|
||||
let elementsInSelection = elements.filter((element) => {
|
||||
let [elementX1, elementY1, elementX2, elementY2] = getElementBounds(
|
||||
element,
|
||||
elementsMap,
|
||||
);
|
||||
let [elementX1, elementY1, elementX2, elementY2] =
|
||||
getElementBounds(element);
|
||||
|
||||
const containingFrame = getContainingFrame(element, elementsMap);
|
||||
const containingFrame = getContainingFrame(element);
|
||||
if (containingFrame) {
|
||||
const [fx1, fy1, fx2, fy2] = getElementBounds(
|
||||
containingFrame,
|
||||
elementsMap,
|
||||
);
|
||||
const [fx1, fy1, fx2, fy2] = getElementBounds(containingFrame);
|
||||
|
||||
elementX1 = Math.max(fx1, elementX1);
|
||||
elementY1 = Math.max(fy1, elementY1);
|
||||
@@ -86,10 +79,10 @@ export const getElementsWithinSelection = (
|
||||
: elementsInSelection;
|
||||
|
||||
elementsInSelection = elementsInSelection.filter((element) => {
|
||||
const containingFrame = getContainingFrame(element, elementsMap);
|
||||
const containingFrame = getContainingFrame(element);
|
||||
|
||||
if (containingFrame) {
|
||||
return elementOverlapsWithFrame(element, containingFrame, elementsMap);
|
||||
return elementOverlapsWithFrame(element, containingFrame);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -102,7 +95,6 @@ export const getVisibleAndNonSelectedElements = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
selectedElements: readonly NonDeletedExcalidrawElement[],
|
||||
appState: AppState,
|
||||
elementsMap: ElementsMap,
|
||||
) => {
|
||||
const selectedElementsSet = new Set(
|
||||
selectedElements.map((element) => element.id),
|
||||
@@ -113,7 +105,6 @@ export const getVisibleAndNonSelectedElements = (
|
||||
appState.width,
|
||||
appState.height,
|
||||
appState,
|
||||
elementsMap,
|
||||
);
|
||||
|
||||
return !selectedElementsSet.has(element.id) && isVisible;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { RoughCanvas } from "roughjs/bin/canvas";
|
||||
import { Drawable } from "roughjs/bin/core";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawTextElement,
|
||||
NonDeletedElementsMap,
|
||||
NonDeletedExcalidrawElement,
|
||||
@@ -14,8 +13,6 @@ import {
|
||||
ElementsPendingErasure,
|
||||
InteractiveCanvasAppState,
|
||||
StaticCanvasAppState,
|
||||
SocketId,
|
||||
UserIdleState,
|
||||
} from "../types";
|
||||
import { MakeBrand } from "../utility-types";
|
||||
|
||||
@@ -49,11 +46,11 @@ export type SVGRenderConfig = {
|
||||
export type InteractiveCanvasRenderConfig = {
|
||||
// collab-related state
|
||||
// ---------------------------------------------------------------------------
|
||||
remoteSelectedElementIds: Map<ExcalidrawElement["id"], SocketId[]>;
|
||||
remotePointerViewportCoords: Map<SocketId, { x: number; y: number }>;
|
||||
remotePointerUserStates: Map<SocketId, UserIdleState>;
|
||||
remotePointerUsernames: Map<SocketId, string>;
|
||||
remotePointerButton: Map<SocketId, string | undefined>;
|
||||
remoteSelectedElementIds: { [elementId: string]: string[] };
|
||||
remotePointerViewportCoords: { [id: string]: { x: number; y: number } };
|
||||
remotePointerUserStates: { [id: string]: string };
|
||||
remotePointerUsernames: { [id: string]: string };
|
||||
remotePointerButton?: { [id: string]: string | undefined };
|
||||
selectionColor?: string;
|
||||
// extra options passed to the renderer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user