Compare commits

..

8 Commits

Author SHA1 Message Date
Aakansha Doshi 1ac4200cc0 tweak 2024-02-05 19:54:39 +05:30
Aakansha Doshi 2ca2c0f9fa fix 2024-02-05 19:34:48 +05:30
Aakansha Doshi f3b6e9b09f fix 2024-02-05 19:28:24 +05:30
Aakansha Doshi 1db2869906 persist file name to LS 2024-02-05 19:26:52 +05:30
Aakansha Doshi 1bb88cb5e9 fix 2024-02-05 15:43:44 +05:30
Aakansha Doshi 701e076cc1 fix snaps 2024-02-05 15:13:49 +05:30
Aakansha Doshi ad39506585 fix 2024-02-05 15:07:11 +05:30
Aakansha Doshi b2331ffd98 feat: remove name from appState and use in component directly 2024-02-05 15:05:01 +05:30
179 changed files with 3573 additions and 11586 deletions
+1 -2
View File
@@ -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>
);
+45 -258
View File
@@ -30,6 +30,7 @@ import {
} from "../packages/excalidraw/index";
import {
AppState,
LibraryItems,
ExcalidrawImperativeAPI,
BinaryFiles,
ExcalidrawInitialDataState,
@@ -47,7 +48,6 @@ import {
} from "../packages/excalidraw/utils";
import {
FIREBASE_STORAGE_PREFIXES,
isExcalidrawPlusSignedUser,
STORAGE_KEYS,
SYNC_BROWSER_TABS_TIMEOUT,
} from "./app_constants";
@@ -64,6 +64,7 @@ import {
loadScene,
} from "./data";
import {
getLibraryItemsFromStorage,
importFromLocalStorage,
importUsernameFromLocalStorage,
} from "./data/localStorage";
@@ -81,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";
@@ -107,20 +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 {
CommandPalette,
DEFAULT_CATEGORIES,
} from "../packages/excalidraw/components/CommandPalette/CommandPalette";
import {
GithubIcon,
XBrandIcon,
DiscordIcon,
ExcalLogo,
usersIcon,
exportToPlus,
share,
} from "../packages/excalidraw/components/icons";
import { getFileName } from "../packages/excalidraw/data/filename";
polyfill();
@@ -327,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(() => {
@@ -463,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 || "");
}
@@ -680,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(
@@ -705,46 +691,6 @@ const ExcalidrawWrapper = () => {
</div>
);
}
const ExcalidrawPlusCommand = {
label: "Excalidraw+",
category: DEFAULT_CATEGORIES.links,
predicate: true,
icon: <div style={{ width: 14 }}>{ExcalLogo}</div>,
keywords: ["plus", "cloud", "server"],
perform: () => {
window.open(
`${
import.meta.env.VITE_APP_PLUS_LP
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=command_palette`,
"_blank",
);
},
};
const ExcalidrawPlusAppCommand = {
label: "Sign up",
category: DEFAULT_CATEGORIES.links,
predicate: true,
icon: <div style={{ width: 14 }}>{ExcalLogo}</div>,
keywords: [
"excalidraw",
"plus",
"cloud",
"server",
"signin",
"login",
"signup",
],
perform: () => {
window.open(
`${
import.meta.env.VITE_APP_PLUS_APP
}?utm_source=excalidraw&utm_medium=app&utm_content=command_palette`,
"_blank",
);
},
};
return (
<div
style={{ height: "100%" }}
@@ -763,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 },
});
}}
/>
);
},
},
},
}}
@@ -794,6 +737,7 @@ const ExcalidrawWrapper = () => {
renderCustomStats={renderCustomStats}
detectScroll={false}
handleKeyboardGlobally={true}
onLibraryChange={onLibraryChange}
autoFocus={true}
theme={theme}
renderTopRightUI={(isMobile) => {
@@ -801,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" })
}
/>
);
}}
>
@@ -834,7 +775,7 @@ const ExcalidrawWrapper = () => {
excalidrawAPI.getSceneElements(),
excalidrawAPI.getAppState(),
excalidrawAPI.getFiles(),
excalidrawAPI.getName(),
getFileName(),
);
}}
>
@@ -939,160 +880,6 @@ const ExcalidrawWrapper = () => {
{errorMessage}
</ErrorDialog>
)}
<CommandPalette
customCommandPaletteItems={[
{
label: t("labels.liveCollaboration"),
category: DEFAULT_CATEGORIES.app,
keywords: [
"team",
"multiplayer",
"share",
"public",
"session",
"invite",
],
icon: usersIcon,
perform: () => {
setShareDialogState({
isOpen: true,
type: "collaborationOnly",
});
},
},
{
label: t("roomDialog.button_stopSession"),
category: DEFAULT_CATEGORIES.app,
predicate: () => !!collabAPI?.isCollaborating(),
keywords: [
"stop",
"session",
"end",
"leave",
"close",
"exit",
"collaboration",
],
perform: () => {
if (collabAPI) {
collabAPI.stopCollaboration();
if (!collabAPI.isCollaborating()) {
setShareDialogState({ isOpen: false });
}
}
},
},
{
label: t("labels.share"),
category: DEFAULT_CATEGORIES.app,
predicate: true,
icon: share,
keywords: [
"link",
"shareable",
"readonly",
"export",
"publish",
"snapshot",
"url",
"collaborate",
"invite",
],
perform: async () => {
setShareDialogState({ isOpen: true, type: "share" });
},
},
{
label: "GitHub",
icon: GithubIcon,
category: DEFAULT_CATEGORIES.links,
predicate: true,
keywords: [
"issues",
"bugs",
"requests",
"report",
"features",
"social",
"community",
],
perform: () => {
window.open(
"https://github.com/excalidraw/excalidraw",
"_blank",
"noopener noreferrer",
);
},
},
{
label: t("labels.followUs"),
icon: XBrandIcon,
category: DEFAULT_CATEGORIES.links,
predicate: true,
keywords: ["twitter", "contact", "social", "community"],
perform: () => {
window.open(
"https://x.com/excalidraw",
"_blank",
"noopener noreferrer",
);
},
},
{
label: t("labels.discordChat"),
category: DEFAULT_CATEGORIES.links,
predicate: true,
icon: DiscordIcon,
keywords: [
"chat",
"talk",
"contact",
"bugs",
"requests",
"report",
"feedback",
"suggestions",
"social",
"community",
],
perform: () => {
window.open(
"https://discord.gg/UexuTaE",
"_blank",
"noopener noreferrer",
);
},
},
...(isExcalidrawPlusSignedUser
? [
{
...ExcalidrawPlusAppCommand,
label: "Sign in / Go to Excalidraw+",
},
]
: [ExcalidrawPlusCommand, ExcalidrawPlusAppCommand]),
{
label: t("overwriteConfirm.action.excalidrawPlus.button"),
category: DEFAULT_CATEGORIES.export,
icon: exportToPlus,
predicate: true,
keywords: ["plus", "export", "save", "backup"],
perform: () => {
if (excalidrawAPI) {
exportToExcalidrawPlus(
excalidrawAPI.getSceneElements(),
excalidrawAPI.getAppState(),
excalidrawAPI.getFiles(),
excalidrawAPI.getName(),
);
}
},
},
CommandPalette.defaultItems.toggleTheme,
]}
/>
</Excalidraw>
</div>
);
+1 -5
View File
@@ -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 = {
+12 -52
View File
@@ -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>
)}
-35
View File
@@ -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);
}
}
}
-54
View File
@@ -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;
+11 -10
View File
@@ -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();
};
+1 -1
View File
@@ -20,7 +20,7 @@ export const AppMainMenu: React.FC<{
onSelect={() => props.onCollabDialogOpen()}
/>
)}
<MainMenu.DefaultItems.CommandPalette />
<MainMenu.DefaultItems.Help />
<MainMenu.DefaultItems.ClearCanvas />
<MainMenu.Separator />
@@ -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);
@@ -67,8 +67,6 @@ export class TopErrorBoundary extends React.Component<
window.open(
`https://github.com/excalidraw/excalidraw/issues/new?body=${body}`,
"_blank",
"noopener noreferrer",
);
}
+1 -61
View File
@@ -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);
}
}
+17 -1
View File
@@ -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 [];
}
};
+3 -5
View File
@@ -78,7 +78,7 @@
}
</style>
<!------------------------------------------------------------------------->
<% if (typeof PROD != 'undefined' && PROD == true) { %>
<% if ("%PROD%" === "true") { %>
<script>
// Redirect Excalidraw+ users which have auto-redirect enabled.
//
@@ -122,8 +122,7 @@
/>
<link rel="stylesheet" href="/fonts/fonts.css" type="text/css" />
<% if (typeof VITE_APP_DEV_DISABLE_LIVE_RELOAD != 'undefined' &&
VITE_APP_DEV_DISABLE_LIVE_RELOAD == true) { %>
<% if ("%VITE_APP_DEV_DISABLE_LIVE_RELOAD%"==="true" ) { %>
<script>
{
const _WebSocket = window.WebSocket;
@@ -197,8 +196,7 @@
</header>
<div id="root"></div>
<script type="module" src="index.tsx"></script>
<% if (typeof VITE_APP_DEV_DISABLE_LIVE_RELOAD != 'undefined' &&
VITE_APP_DEV_DISABLE_LIVE_RELOAD != true) { %>
<% if ("%VITE_APP_DEV_DISABLE_LIVE_RELOAD%" !== 'true') { %>
<!-- 100% privacy friendly analytics -->
<script>
// need to load this script dynamically bcs. of iframe embed tracking
-7
View File
@@ -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;
+1 -3
View File
@@ -25,9 +25,7 @@
"engines": {
"node": ">=18.0.0"
},
"dependencies": {
"vite-plugin-html": "3.2.2"
},
"dependencies": {},
"prettier": "@excalidraw/prettier-config",
"scripts": {
"build-node": "node ./scripts/build-node.js",
+14 -23
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useRef, useState } from "react";
import * as Popover from "@radix-ui/react-popover";
import { copyTextToSystemClipboard } from "../../packages/excalidraw/clipboard";
import { trackEvent } from "../../packages/excalidraw/analytics";
@@ -22,7 +22,6 @@ import { activeRoomLinkAtom, CollabAPI } from "../collab/Collab";
import { atom, useAtom, useAtomValue } from "jotai";
import "./ShareDialog.scss";
import { useUIAppState } from "../../packages/excalidraw/context/ui-appState";
type OnExportToBackend = () => void;
type ShareDialogType = "share" | "collaborationOnly";
@@ -70,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();
};
@@ -276,14 +275,6 @@ export const ShareDialog = (props: {
}) => {
const [shareDialogState, setShareDialogState] = useAtom(shareDialogStateAtom);
const { openDialog } = useUIAppState();
useEffect(() => {
if (openDialog) {
setShareDialogState({ isOpen: false });
}
}, [openDialog, setShareDialogState]);
if (!shareDialogState.isOpen) {
return null;
}
@@ -294,6 +285,6 @@ export const ShareDialog = (props: {
collabAPI={props.collabAPI}
onExportToBackend={props.onExportToBackend}
type={shareDialogState.type}
/>
></ShareDialogInner>
);
};
-4
View File
@@ -4,7 +4,6 @@ import svgrPlugin from "vite-plugin-svgr";
import { ViteEjsPlugin } from "vite-plugin-ejs";
import { VitePWA } from "vite-plugin-pwa";
import checker from "vite-plugin-checker";
import { createHtmlPlugin } from "vite-plugin-html";
// To load .env.local variables
const envVars = loadEnv("", `../`);
@@ -190,9 +189,6 @@ export default defineConfig({
],
},
}),
createHtmlPlugin({
minify: true,
}),
],
publicDir: "../public",
});
+1 -17
View File
@@ -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
@@ -58,5 +58,5 @@ export const actionAddToLibrary = register({
};
});
},
label: "labels.addToLibrary",
contextItemLabel: "labels.addToLibrary",
});
+2 -14
View File
@@ -15,13 +15,13 @@ import { updateFrameMembershipOfSelectedElements } from "../frame";
import { t } from "../i18n";
import { KEYS } from "../keys";
import { isSomeElementSelected } from "../scene";
import { AppClassProperties, AppState, UIAppState } from "../types";
import { AppClassProperties, AppState } from "../types";
import { arrayToMap, getShortcutKey } from "../utils";
import { register } from "./register";
const alignActionsPredicate = (
elements: readonly ExcalidrawElement[],
appState: UIAppState,
appState: AppState,
_: unknown,
app: AppClassProperties,
) => {
@@ -59,8 +59,6 @@ const alignSelectedElements = (
export const actionAlignTop = register({
name: "alignTop",
label: "labels.alignTop",
icon: AlignTopIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -92,8 +90,6 @@ export const actionAlignTop = register({
export const actionAlignBottom = register({
name: "alignBottom",
label: "labels.alignBottom",
icon: AlignBottomIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -125,8 +121,6 @@ export const actionAlignBottom = register({
export const actionAlignLeft = register({
name: "alignLeft",
label: "labels.alignLeft",
icon: AlignLeftIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -158,8 +152,6 @@ export const actionAlignLeft = register({
export const actionAlignRight = register({
name: "alignRight",
label: "labels.alignRight",
icon: AlignRightIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -191,8 +183,6 @@ export const actionAlignRight = register({
export const actionAlignVerticallyCentered = register({
name: "alignVerticallyCentered",
label: "labels.centerVertically",
icon: CenterVerticallyIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -220,8 +210,6 @@ export const actionAlignVerticallyCentered = register({
export const actionAlignHorizontallyCentered = register({
name: "alignHorizontallyCentered",
label: "labels.centerHorizontally",
icon: CenterHorizontallyIcon,
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState, _, app) => {
@@ -36,7 +36,7 @@ import { register } from "./register";
export const actionUnbindText = register({
name: "unbindText",
label: "labels.unbindText",
contextItemLabel: "labels.unbindText",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
@@ -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,
@@ -91,7 +88,7 @@ export const actionUnbindText = register({
export const actionBindText = register({
name: "bindText",
label: "labels.bindText",
contextItemLabel: "labels.bindText",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
@@ -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);
@@ -203,7 +196,7 @@ const pushContainerBelowText = (
export const actionWrapTextInContainer = register({
name: "wrapTextInContainer",
label: "labels.createContainerFromText",
contextItemLabel: "labels.createContainerFromText",
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
@@ -293,11 +286,7 @@ export const actionWrapTextInContainer = register({
},
false,
);
redrawTextBoundingBox(
textElement,
container,
app.scene.getNonDeletedElementsMap(),
);
redrawTextBoundingBox(textElement, container);
updatedElements = pushContainerBelowText(
[...updatedElements, container],
+1 -37
View File
@@ -1,14 +1,5 @@
import { ColorPicker } from "../components/ColorPicker/ColorPicker";
import {
handIcon,
MoonIcon,
SunIcon,
TrashIcon,
zoomAreaIcon,
ZoomInIcon,
ZoomOutIcon,
ZoomResetIcon,
} from "../components/icons";
import { ZoomInIcon, ZoomOutIcon } from "../components/icons";
import { ToolButton } from "../components/ToolButton";
import { CURSOR_TYPE, MIN_ZOOM, THEME, ZOOM_STEP } from "../constants";
import { getCommonBounds, getNonDeletedElements } from "../element";
@@ -34,8 +25,6 @@ import { setCursor } from "../cursor";
export const actionChangeViewBackgroundColor = register({
name: "changeViewBackgroundColor",
label: "labels.canvasBackground",
paletteName: "Change canvas background color",
trackEvent: false,
predicate: (elements, appState, props, app) => {
return (
@@ -70,9 +59,6 @@ export const actionChangeViewBackgroundColor = register({
export const actionClearCanvas = register({
name: "clearCanvas",
label: "labels.clearCanvas",
paletteName: "Clear canvas",
icon: TrashIcon,
trackEvent: { category: "canvas" },
predicate: (elements, appState, props, app) => {
return (
@@ -109,9 +95,7 @@ export const actionClearCanvas = register({
export const actionZoomIn = register({
name: "zoomIn",
label: "buttons.zoomIn",
viewMode: true,
icon: ZoomInIcon,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
return {
@@ -149,8 +133,6 @@ export const actionZoomIn = register({
export const actionZoomOut = register({
name: "zoomOut",
label: "buttons.zoomOut",
icon: ZoomOutIcon,
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
@@ -189,8 +171,6 @@ export const actionZoomOut = register({
export const actionResetZoom = register({
name: "resetZoom",
label: "buttons.resetZoom",
icon: ZoomResetIcon,
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_elements, appState, _, app) => {
@@ -360,8 +340,6 @@ export const zoomToFit = ({
// size, it won't be zoomed in.
export const actionZoomToFitSelectionInViewport = register({
name: "zoomToFitSelectionInViewport",
label: "labels.zoomToFitViewport",
icon: zoomAreaIcon,
trackEvent: { category: "canvas" },
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
@@ -385,8 +363,6 @@ export const actionZoomToFitSelectionInViewport = register({
export const actionZoomToFitSelection = register({
name: "zoomToFitSelection",
label: "helpDialog.zoomToSelection",
icon: zoomAreaIcon,
trackEvent: { category: "canvas" },
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
@@ -409,8 +385,6 @@ export const actionZoomToFitSelection = register({
export const actionZoomToFit = register({
name: "zoomToFit",
label: "helpDialog.zoomToFit",
icon: zoomAreaIcon,
viewMode: true,
trackEvent: { category: "canvas" },
perform: (elements, appState) =>
@@ -431,11 +405,6 @@ export const actionZoomToFit = register({
export const actionToggleTheme = register({
name: "toggleTheme",
label: (_, appState) => {
return appState.theme === "dark" ? "buttons.lightMode" : "buttons.darkMode";
},
keywords: ["toggle", "dark", "light", "mode", "theme"],
icon: (appState) => (appState.theme === THEME.LIGHT ? MoonIcon : SunIcon),
viewMode: true,
trackEvent: { category: "canvas" },
perform: (_, appState, value) => {
@@ -456,7 +425,6 @@ export const actionToggleTheme = register({
export const actionToggleEraserTool = register({
name: "toggleEraserTool",
label: "toolBar.eraser",
trackEvent: { category: "toolbar" },
perform: (elements, appState) => {
let activeTool: AppState["activeTool"];
@@ -491,11 +459,7 @@ export const actionToggleEraserTool = register({
export const actionToggleHandTool = register({
name: "toggleHandTool",
label: "toolBar.hand",
paletteName: "Toggle hand tool",
trackEvent: { category: "toolbar" },
icon: handIcon,
viewMode: false,
perform: (elements, appState, _, app) => {
let activeTool: AppState["activeTool"];
+11 -22
View File
@@ -13,12 +13,10 @@ import { exportCanvas, prepareElementsForExport } from "../data/index";
import { isTextElement } from "../element";
import { t } from "../i18n";
import { isFirefox } from "../constants";
import { DuplicateIcon, cutIcon, pngIcon, svgIcon } from "../components/icons";
import { getFileName } from "../data/filename";
export const actionCopy = register({
name: "copy",
label: "labels.copy",
icon: DuplicateIcon,
trackEvent: { category: "element" },
perform: async (elements, appState, event: ClipboardEvent | null, app) => {
const elementsToCopy = app.scene.getSelectedElements({
@@ -43,13 +41,13 @@ export const actionCopy = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.copy",
// don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined,
});
export const actionPaste = register({
name: "paste",
label: "labels.paste",
trackEvent: { category: "element" },
perform: async (elements, appState, data, app) => {
let types;
@@ -100,26 +98,24 @@ export const actionPaste = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.paste",
// don't supply a shortcut since we handle this conditionally via onCopy event
keyTest: undefined,
});
export const actionCut = register({
name: "cut",
label: "labels.cut",
icon: cutIcon,
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,
});
export const actionCopyAsSvg = register({
name: "copyAsSvg",
label: "labels.copyAsSvg",
icon: svgIcon,
trackEvent: { category: "element" },
perform: async (elements, appState, _data, app) => {
if (!app.canvas) {
@@ -143,7 +139,7 @@ export const actionCopyAsSvg = register({
{
...appState,
exportingFrame,
name: app.getName(),
name: app.props.name || getFileName(),
},
);
return {
@@ -163,13 +159,11 @@ export const actionCopyAsSvg = register({
predicate: (elements) => {
return probablySupportsClipboardWriteText && elements.length > 0;
},
keywords: ["svg", "clipboard", "copy"],
contextItemLabel: "labels.copyAsSvg",
});
export const actionCopyAsPng = register({
name: "copyAsPng",
label: "labels.copyAsPng",
icon: pngIcon,
trackEvent: { category: "element" },
perform: async (elements, appState, _data, app) => {
if (!app.canvas) {
@@ -192,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: {
@@ -224,13 +218,12 @@ export const actionCopyAsPng = register({
predicate: (elements) => {
return probablySupportsClipboardBlob && elements.length > 0;
},
contextItemLabel: "labels.copyAsPng",
keyTest: (event) => event.code === CODES.C && event.altKey && event.shiftKey,
keywords: ["png", "clipboard", "copy"],
});
export const copyText = register({
name: "copyText",
label: "labels.copyText",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements({
@@ -246,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,
};
@@ -266,5 +255,5 @@ export const copyText = register({
.some(isTextElement)
);
},
keywords: ["text", "clipboard", "copy"],
contextItemLabel: "labels.copyText",
});
@@ -72,10 +72,8 @@ const handleGroupEditingState = (
export const actionDeleteSelected = register({
name: "deleteSelectedElements",
label: "labels.delete",
icon: TrashIcon,
trackEvent: { category: "element", action: "delete" },
perform: (elements, appState, formData, app) => {
perform: (elements, appState) => {
if (appState.editingLinearElement) {
const {
elementId,
@@ -83,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;
}
@@ -170,6 +167,7 @@ export const actionDeleteSelected = register({
),
};
},
contextItemLabel: "labels.delete",
keyTest: (event, appState, elements) =>
(event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE) &&
!event[KEYS.CTRL_OR_CMD],
@@ -49,7 +49,6 @@ const distributeSelectedElements = (
export const distributeHorizontally = register({
name: "distributeHorizontally",
label: "labels.distributeHorizontally",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
return {
@@ -80,7 +79,6 @@ export const distributeHorizontally = register({
export const distributeVertically = register({
name: "distributeVertically",
label: "labels.distributeVertically",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
return {
@@ -34,17 +34,11 @@ import {
export const actionDuplicateSelection = register({
name: "duplicateSelection",
label: "labels.duplicateSelection",
icon: DuplicateIcon,
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;
@@ -62,6 +56,7 @@ export const actionDuplicateSelection = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.duplicateSelection",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.D,
PanelComponent: ({ elements, appState, updateData }) => (
<ToolButton
@@ -1,9 +1,7 @@
import { LockedIcon, UnlockedIcon } from "../components/icons";
import { newElementWith } from "../element/mutateElement";
import { isFrameLikeElement } from "../element/typeChecks";
import { ExcalidrawElement } from "../element/types";
import { KEYS } from "../keys";
import { getSelectedElements } from "../scene";
import { arrayToMap } from "../utils";
import { register } from "./register";
@@ -12,31 +10,11 @@ const shouldLock = (elements: readonly ExcalidrawElement[]) =>
export const actionToggleElementLock = register({
name: "toggleElementLock",
label: (elements, appState, app) => {
const selected = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: false,
});
if (selected.length === 1 && !isFrameLikeElement(selected[0])) {
return selected[0].locked
? "labels.elementLock.unlock"
: "labels.elementLock.lock";
}
return shouldLock(selected)
? "labels.elementLock.lockAll"
: "labels.elementLock.unlockAll";
},
icon: (appState, elements) => {
const selectedElements = getSelectedElements(elements, appState);
return shouldLock(selectedElements) ? LockedIcon : UnlockedIcon;
},
trackEvent: { category: "element" },
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
return (
selectedElements.length > 0 &&
!selectedElements.some((element) => element.locked && element.frameId)
return !selectedElements.some(
(element) => element.locked && element.frameId,
);
},
perform: (elements, appState, _, app) => {
@@ -69,6 +47,21 @@ export const actionToggleElementLock = register({
commitToHistory: true,
};
},
contextItemLabel: (elements, appState, app) => {
const selected = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: false,
});
if (selected.length === 1 && !isFrameLikeElement(selected[0])) {
return selected[0].locked
? "labels.elementLock.unlock"
: "labels.elementLock.lock";
}
return shouldLock(selected)
? "labels.elementLock.lockAll"
: "labels.elementLock.unlockAll";
},
keyTest: (event, appState, elements, app) => {
return (
event.key.toLocaleLowerCase() === KEYS.L &&
@@ -84,16 +77,10 @@ export const actionToggleElementLock = register({
export const actionUnlockAllElements = register({
name: "unlockAllElements",
paletteName: "Unlock all elements",
trackEvent: { category: "canvas" },
viewMode: false,
icon: UnlockedIcon,
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
selectedElements.length === 0 &&
elements.some((element) => element.locked)
);
predicate: (elements) => {
return elements.some((element) => element.locked);
},
perform: (elements, appState) => {
const lockedElements = elements.filter((el) => el.locked);
@@ -114,5 +101,5 @@ export const actionUnlockAllElements = register({
commitToHistory: true,
};
},
label: "labels.elementLock.unlockAll",
contextItemLabel: "labels.elementLock.unlockAll",
});
+15 -16
View File
@@ -1,4 +1,4 @@
import { ExportIcon, questionCircle, saveAs } from "../components/icons";
import { questionCircle, saveAs } from "../components/icons";
import { ProjectName } from "../components/ProjectName";
import { ToolButton } from "../components/ToolButton";
import { Tooltip } from "../components/Tooltip";
@@ -17,21 +17,24 @@ 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";
export const actionChangeProjectName = register({
name: "changeProjectName",
label: "labels.fileTitle",
trackEvent: false,
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}
/>
),
@@ -39,7 +42,6 @@ export const actionChangeProjectName = register({
export const actionChangeExportScale = register({
name: "changeExportScale",
label: "imageExportDialog.scale",
trackEvent: { category: "export", action: "scale" },
perform: (_elements, appState, value) => {
return {
@@ -89,7 +91,6 @@ export const actionChangeExportScale = register({
export const actionChangeExportBackground = register({
name: "changeExportBackground",
label: "imageExportDialog.label.withBackground",
trackEvent: { category: "export", action: "toggleBackground" },
perform: (_elements, appState, value) => {
return {
@@ -109,7 +110,6 @@ export const actionChangeExportBackground = register({
export const actionChangeExportEmbedScene = register({
name: "changeExportEmbedScene",
label: "imageExportDialog.tooltip.embedScene",
trackEvent: { category: "export", action: "embedScene" },
perform: (_elements, appState, value) => {
return {
@@ -132,8 +132,6 @@ export const actionChangeExportEmbedScene = register({
export const actionSaveToActiveFile = register({
name: "saveToActiveFile",
label: "buttons.save",
icon: ExportIcon,
trackEvent: { category: "export" },
predicate: (elements, appState, props, app) => {
return (
@@ -151,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,
@@ -187,8 +190,6 @@ export const actionSaveToActiveFile = register({
export const actionSaveFileToDisk = register({
name: "saveFileToDisk",
label: "exportDialog.disk_title",
icon: ExportIcon,
viewMode: true,
trackEvent: { category: "export" },
perform: async (elements, appState, value, app) => {
@@ -200,7 +201,7 @@ export const actionSaveFileToDisk = register({
fileHandle: null,
},
app.files,
app.getName(),
app.props.name || getFileName(),
);
return {
commitToHistory: false,
@@ -238,7 +239,6 @@ export const actionSaveFileToDisk = register({
export const actionLoadScene = register({
name: "loadScene",
label: "buttons.load",
trackEvent: { category: "export" },
predicate: (elements, appState, props, app) => {
return (
@@ -276,7 +276,6 @@ export const actionLoadScene = register({
export const actionExportWithDarkMode = register({
name: "exportWithDarkMode",
label: "imageExportDialog.label.darkMode",
trackEvent: { category: "export", action: "toggleTheme" },
perform: (_elements, appState, value) => {
return {
@@ -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";
@@ -19,7 +19,6 @@ import { resetCursor } from "../cursor";
export const actionFinalize = register({
name: "finalize",
label: "",
trackEvent: false,
perform: (
elements,
@@ -27,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)) {
@@ -40,7 +37,6 @@ export const actionFinalize = register({
element,
startBindingElement,
endBindingElement,
elementsMap,
);
}
return {
@@ -129,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,
);
}
}
@@ -192,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,
},
+8 -12
View File
@@ -4,6 +4,7 @@ import { getNonDeletedElements } from "../element";
import {
ExcalidrawElement,
NonDeleted,
NonDeletedElementsMap,
NonDeletedSceneElementsMap,
} from "../element/types";
import { resizeMultipleElements } from "../element/resizeElements";
@@ -17,12 +18,9 @@ import {
unbindLinearElements,
} from "../element/binding";
import { updateFrameMembershipOfSelectedElements } from "../frame";
import { flipHorizontal, flipVertical } from "../components/icons";
export const actionFlipHorizontal = register({
name: "flipHorizontal",
label: "labels.flipHorizontal",
icon: flipHorizontal,
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
return {
@@ -41,12 +39,11 @@ export const actionFlipHorizontal = register({
};
},
keyTest: (event) => event.shiftKey && event.code === CODES.H,
contextItemLabel: "labels.flipHorizontal",
});
export const actionFlipVertical = register({
name: "flipVertical",
label: "labels.flipVertical",
icon: flipVertical,
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
return {
@@ -66,11 +63,12 @@ export const actionFlipVertical = register({
},
keyTest: (event) =>
event.shiftKey && event.code === CODES.V && !event[KEYS.CTRL_OR_CMD],
contextItemLabel: "labels.flipVertical",
});
const flipSelectedElements = (
elements: readonly ExcalidrawElement[],
elementsMap: NonDeletedSceneElementsMap,
elementsMap: NonDeletedElementsMap | NonDeletedSceneElementsMap,
appState: Readonly<AppState>,
flipDirection: "horizontal" | "vertical",
) => {
@@ -85,7 +83,6 @@ const flipSelectedElements = (
const updatedElements = flipElements(
selectedElements,
elements,
elementsMap,
appState,
flipDirection,
@@ -100,8 +97,7 @@ const flipSelectedElements = (
const flipElements = (
selectedElements: NonDeleted<ExcalidrawElement>[],
elements: readonly ExcalidrawElement[],
elementsMap: NonDeletedSceneElementsMap,
elementsMap: NonDeletedElementsMap | NonDeletedSceneElementsMap,
appState: AppState,
flipDirection: "horizontal" | "vertical",
): ExcalidrawElement[] => {
@@ -117,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;
};
+5 -12
View File
@@ -3,17 +3,13 @@ import { ExcalidrawElement } from "../element/types";
import { removeAllElementsFromFrame } from "../frame";
import { getFrameChildren } from "../frame";
import { KEYS } from "../keys";
import { AppClassProperties, AppState, UIAppState } from "../types";
import { AppClassProperties, AppState } from "../types";
import { updateActiveTool } from "../utils";
import { setCursorForShape } from "../cursor";
import { register } from "./register";
import { isFrameLikeElement } from "../element/typeChecks";
import { frameToolIcon } from "../components/icons";
const isSingleFrameSelected = (
appState: UIAppState,
app: AppClassProperties,
) => {
const isSingleFrameSelected = (appState: AppState, app: AppClassProperties) => {
const selectedElements = app.scene.getSelectedElements(appState);
return (
@@ -23,7 +19,6 @@ const isSingleFrameSelected = (
export const actionSelectAllElementsInFrame = register({
name: "selectAllElementsInFrame",
label: "labels.selectAllElementsInFrame",
trackEvent: { category: "canvas" },
perform: (elements, appState, _, app) => {
const selectedElement =
@@ -54,13 +49,13 @@ export const actionSelectAllElementsInFrame = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.selectAllElementsInFrame",
predicate: (elements, appState, _, app) =>
isSingleFrameSelected(appState, app),
});
export const actionRemoveAllElementsFromFrame = register({
name: "removeAllElementsFromFrame",
label: "labels.removeAllElementsFromFrame",
trackEvent: { category: "history" },
perform: (elements, appState, _, app) => {
const selectedElement =
@@ -85,13 +80,13 @@ export const actionRemoveAllElementsFromFrame = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.removeAllElementsFromFrame",
predicate: (elements, appState, _, app) =>
isSingleFrameSelected(appState, app),
});
export const actionupdateFrameRendering = register({
name: "updateFrameRendering",
label: "labels.updateFrameRendering",
viewMode: true,
trackEvent: { category: "canvas" },
perform: (elements, appState) => {
@@ -107,15 +102,13 @@ export const actionupdateFrameRendering = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.updateFrameRendering",
checked: (appState: AppState) => appState.frameRendering.enabled,
});
export const actionSetFrameAsActiveTool = register({
name: "setFrameAsActiveTool",
label: "toolBar.frame",
trackEvent: { category: "toolbar" },
icon: frameToolIcon,
viewMode: false,
perform: (elements, appState, _, app) => {
const nextActiveTool = updateActiveTool(appState, {
type: "frame",
+3 -12
View File
@@ -61,8 +61,6 @@ const enableActionGroup = (
export const actionGroup = register({
name: "group",
label: "labels.group",
icon: (appState) => <GroupIcon theme={appState.theme} />,
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements({
@@ -159,6 +157,7 @@ export const actionGroup = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.group",
predicate: (elements, appState, _, app) =>
enableActionGroup(elements, appState, app),
keyTest: (event) =>
@@ -178,13 +177,9 @@ export const actionGroup = register({
export const actionUngroup = register({
name: "ungroup",
label: "labels.ungroup",
icon: (appState) => <UngroupIcon theme={appState.theme} />,
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const groupIds = getSelectedGroupIds(appState);
const elementsMap = arrayToMap(elements);
if (groupIds.length === 0) {
return { appState, elements, commitToHistory: false };
}
@@ -231,12 +226,7 @@ export const actionUngroup = register({
if (frame) {
nextElements = replaceAllElementsInFrame(
nextElements,
getElementsInResizingFrame(
nextElements,
frame,
appState,
elementsMap,
),
getElementsInResizingFrame(nextElements, frame, appState),
frame,
app,
);
@@ -266,6 +256,7 @@ export const actionUngroup = register({
event.shiftKey &&
event[KEYS.CTRL_OR_CMD] &&
event.key === KEYS.G.toUpperCase(),
contextItemLabel: "labels.ungroup",
predicate: (elements, appState) => getSelectedGroupIds(appState).length > 0,
PanelComponent: ({ elements, appState, updateData }) => (
@@ -63,10 +63,7 @@ type ActionCreator = (history: History) => Action;
export const createUndoAction: ActionCreator = (history) => ({
name: "undo",
label: "buttons.undo",
icon: UndoIcon,
trackEvent: { category: "history" },
viewMode: false,
perform: (elements, appState) =>
writeData(elements, appState, () => history.undoOnce()),
keyTest: (event) =>
@@ -87,10 +84,7 @@ export const createUndoAction: ActionCreator = (history) => ({
export const createRedoAction: ActionCreator = (history) => ({
name: "redo",
label: "buttons.redo",
icon: RedoIcon,
trackEvent: { category: "history" },
viewMode: false,
perform: (elements, appState) =>
writeData(elements, appState, () => history.redoOnce()),
keyTest: (event) =>
@@ -1,4 +1,3 @@
import { DEFAULT_CATEGORIES } from "../components/CommandPalette/CommandPalette";
import { LinearElementEditor } from "../element/linearElementEditor";
import { isLinearElement } from "../element/typeChecks";
import { ExcalidrawLinearElement } from "../element/types";
@@ -6,16 +5,6 @@ import { register } from "./register";
export const actionToggleLinearEditor = register({
name: "toggleLinearEditor",
category: DEFAULT_CATEGORIES.elements,
label: (elements, appState, app) => {
const selectedElement = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
})[0] as ExcalidrawLinearElement;
return appState.editingLinearElement?.elementId === selectedElement?.id
? "labels.lineEditor.exit"
: "labels.lineEditor.edit";
},
trackEvent: {
category: "element",
},
@@ -35,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,
@@ -44,4 +33,13 @@ export const actionToggleLinearEditor = register({
commitToHistory: false,
};
},
contextItemLabel: (elements, appState, app) => {
const selectedElement = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
})[0] as ExcalidrawLinearElement;
return appState.editingLinearElement?.elementId === selectedElement.id
? "labels.lineEditor.exit"
: "labels.lineEditor.edit";
},
});
@@ -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",
label: (elements, appState) => getContextMenuLabel(elements, appState),
icon: LinkIcon,
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,
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 -5
View File
@@ -1,4 +1,4 @@
import { HamburgerMenuIcon, HelpIconThin, palette } from "../components/icons";
import { HamburgerMenuIcon, palette } from "../components/icons";
import { ToolButton } from "../components/ToolButton";
import { t } from "../i18n";
import { showSelectedShapeActions, getNonDeletedElements } from "../element";
@@ -7,7 +7,6 @@ import { KEYS } from "../keys";
export const actionToggleCanvasMenu = register({
name: "toggleCanvasMenu",
label: "buttons.menu",
trackEvent: { category: "menu" },
perform: (_, appState) => ({
appState: {
@@ -29,7 +28,6 @@ export const actionToggleCanvasMenu = register({
export const actionToggleEditMenu = register({
name: "toggleEditMenu",
label: "buttons.edit",
trackEvent: { category: "menu" },
perform: (_elements, appState) => ({
appState: {
@@ -55,8 +53,6 @@ export const actionToggleEditMenu = register({
export const actionShortcuts = register({
name: "toggleShortcuts",
label: "welcomeScreen.defaults.helpHint",
icon: HelpIconThin,
viewMode: true,
trackEvent: { category: "menu", action: "toggleHelpDialog" },
perform: (_elements, appState, _, { focusContainer }) => {
+23 -70
View File
@@ -1,19 +1,13 @@
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",
label: "Go to a collaborator",
viewMode: true,
trackEvent: { category: "collab" },
perform: (_elements, appState, collaborator: Collaborator) => {
@@ -45,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
@@ -91,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}
/>
);
},
});
@@ -49,7 +49,6 @@ import {
ArrowheadCircleOutlineIcon,
ArrowheadDiamondIcon,
ArrowheadDiamondOutlineIcon,
fontSizeIcon,
} from "../components/icons";
import {
DEFAULT_FONT_FAMILY,
@@ -210,7 +209,6 @@ const changeFontSize = (
redrawTextBoundingBox(
newElement,
app.scene.getContainerElement(oldElement),
app.scene.getNonDeletedElementsMap(),
);
newElement = offsetElementAfterFontResize(oldElement, newElement);
@@ -239,7 +237,6 @@ const changeFontSize = (
export const actionChangeStrokeColor = register({
name: "changeStrokeColor",
label: "labels.stroke",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -290,7 +287,6 @@ export const actionChangeStrokeColor = register({
export const actionChangeBackgroundColor = register({
name: "changeBackgroundColor",
label: "labels.changeBackground",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -334,7 +330,6 @@ export const actionChangeBackgroundColor = register({
export const actionChangeFillStyle = register({
name: "changeFillStyle",
label: "labels.fill",
trackEvent: false,
perform: (elements, appState, value, app) => {
trackEvent(
@@ -412,7 +407,6 @@ export const actionChangeFillStyle = register({
export const actionChangeStrokeWidth = register({
name: "changeStrokeWidth",
label: "labels.strokeWidth",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -466,7 +460,6 @@ export const actionChangeStrokeWidth = register({
export const actionChangeSloppiness = register({
name: "changeSloppiness",
label: "labels.sloppiness",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -518,7 +511,6 @@ export const actionChangeSloppiness = register({
export const actionChangeStrokeStyle = register({
name: "changeStrokeStyle",
label: "labels.strokeStyle",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -569,7 +561,6 @@ export const actionChangeStrokeStyle = register({
export const actionChangeOpacity = register({
name: "changeOpacity",
label: "labels.opacity",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -611,7 +602,6 @@ export const actionChangeOpacity = register({
export const actionChangeFontSize = register({
name: "changeFontSize",
label: "labels.fontSize",
trackEvent: false,
perform: (elements, appState, value, app) => {
return changeFontSize(elements, appState, app, () => value, value);
@@ -682,8 +672,6 @@ export const actionChangeFontSize = register({
export const actionDecreaseFontSize = register({
name: "decreaseFontSize",
label: "labels.decreaseFontSize",
icon: fontSizeIcon,
trackEvent: false,
perform: (elements, appState, value, app) => {
return changeFontSize(elements, appState, app, (element) =>
@@ -706,8 +694,6 @@ export const actionDecreaseFontSize = register({
export const actionIncreaseFontSize = register({
name: "increaseFontSize",
label: "labels.increaseFontSize",
icon: fontSizeIcon,
trackEvent: false,
perform: (elements, appState, value, app) => {
return changeFontSize(elements, appState, app, (element) =>
@@ -726,7 +712,6 @@ export const actionIncreaseFontSize = register({
export const actionChangeFontFamily = register({
name: "changeFontFamily",
label: "labels.fontFamily",
trackEvent: false,
perform: (elements, appState, value, app) => {
return {
@@ -745,7 +730,6 @@ export const actionChangeFontFamily = register({
redrawTextBoundingBox(
newElement,
app.scene.getContainerElement(oldElement),
app.scene.getNonDeletedElementsMap(),
);
return newElement;
}
@@ -830,7 +814,6 @@ export const actionChangeFontFamily = register({
export const actionChangeTextAlign = register({
name: "changeTextAlign",
label: "Change text alignment",
trackEvent: false,
perform: (elements, appState, value, app) => {
return {
@@ -846,7 +829,6 @@ export const actionChangeTextAlign = register({
redrawTextBoundingBox(
newElement,
app.scene.getContainerElement(oldElement),
app.scene.getNonDeletedElementsMap(),
);
return newElement;
}
@@ -920,7 +902,6 @@ export const actionChangeTextAlign = register({
export const actionChangeVerticalAlign = register({
name: "changeVerticalAlign",
label: "Change vertical alignment",
trackEvent: { category: "element" },
perform: (elements, appState, value, app) => {
return {
@@ -937,7 +918,6 @@ export const actionChangeVerticalAlign = register({
redrawTextBoundingBox(
newElement,
app.scene.getContainerElement(oldElement),
app.scene.getNonDeletedElementsMap(),
);
return newElement;
}
@@ -1010,7 +990,6 @@ export const actionChangeVerticalAlign = register({
export const actionChangeRoundness = register({
name: "changeRoundness",
label: "Change edge roundness",
trackEvent: false,
perform: (elements, appState, value) => {
return {
@@ -1149,7 +1128,6 @@ const getArrowheadOptions = (flip: boolean) => {
export const actionChangeArrowhead = register({
name: "changeArrowhead",
label: "Change arrowheads",
trackEvent: false,
perform: (
elements,
@@ -6,14 +6,10 @@ import { ExcalidrawElement } from "../element/types";
import { isLinearElement } from "../element/typeChecks";
import { LinearElementEditor } from "../element/linearElementEditor";
import { excludeElementsInFramesFromSelection } from "../scene/selection";
import { selectAllIcon } from "../components/icons";
export const actionSelectAll = register({
name: "selectAll",
label: "labels.selectAll",
icon: selectAllIcon,
trackEvent: { category: "canvas" },
viewMode: false,
perform: (elements, appState, value, app) => {
if (appState.editingLinearElement) {
return false;
@@ -47,11 +43,12 @@ 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,
};
},
contextItemLabel: "labels.selectAll",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.key === KEYS.A,
});
+3 -10
View File
@@ -25,15 +25,12 @@ import {
} from "../element/typeChecks";
import { getSelectedElements } from "../scene";
import { ExcalidrawTextElement } from "../element/types";
import { paintIcon } from "../components/icons";
// `copiedStyles` is exported only for tests.
export let copiedStyles: string = "{}";
export const actionCopyStyles = register({
name: "copyStyles",
label: "labels.copyStyles",
icon: paintIcon,
trackEvent: { category: "element" },
perform: (elements, appState, formData, app) => {
const elementsCopied = [];
@@ -57,14 +54,13 @@ export const actionCopyStyles = register({
commitToHistory: false,
};
},
contextItemLabel: "labels.copyStyles",
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.C,
});
export const actionPasteStyles = register({
name: "pasteStyles",
label: "labels.pasteStyles",
icon: paintIcon,
trackEvent: { category: "element" },
perform: (elements, appState, formData, app) => {
const elementsCopied = JSON.parse(copiedStyles);
@@ -132,11 +128,7 @@ export const actionPasteStyles = register({
element.id === newElement.containerId,
) || null;
}
redrawTextBoundingBox(
newElement,
container,
app.scene.getNonDeletedElementsMap(),
);
redrawTextBoundingBox(newElement, container);
}
if (
@@ -163,6 +155,7 @@ export const actionPasteStyles = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.pasteStyles",
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.V,
});
@@ -5,7 +5,6 @@ import { AppState } from "../types";
export const actionToggleGridMode = register({
name: "gridMode",
label: "labels.showGrid",
viewMode: true,
trackEvent: {
category: "canvas",
@@ -25,5 +24,6 @@ export const actionToggleGridMode = register({
predicate: (element, appState, props) => {
return typeof props.gridModeEnabled === "undefined";
},
contextItemLabel: "labels.showGrid",
keyTest: (event) => event[KEYS.CTRL_OR_CMD] && event.code === CODES.QUOTE,
});
@@ -1,12 +1,9 @@
import { magnetIcon } from "../components/icons";
import { CODES, KEYS } from "../keys";
import { register } from "./register";
export const actionToggleObjectsSnapMode = register({
name: "objectsSnapMode",
label: "buttons.objectsSnapMode",
icon: magnetIcon,
viewMode: false,
viewMode: true,
trackEvent: {
category: "canvas",
predicate: (appState) => !appState.objectsSnapModeEnabled,
@@ -25,6 +22,7 @@ export const actionToggleObjectsSnapMode = register({
predicate: (elements, appState, appProps) => {
return typeof appProps.objectsSnapModeEnabled === "undefined";
},
contextItemLabel: "buttons.objectsSnapMode",
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.S,
});
@@ -1,12 +1,8 @@
import { register } from "./register";
import { CODES, KEYS } from "../keys";
import { abacusIcon } from "../components/icons";
export const actionToggleStats = register({
name: "stats",
label: "stats.title",
icon: abacusIcon,
paletteName: "Toggle stats",
viewMode: true,
trackEvent: { category: "menu" },
perform(elements, appState) {
@@ -19,6 +15,7 @@ export const actionToggleStats = register({
};
},
checked: (appState) => appState.showStats,
contextItemLabel: "stats.title",
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.SLASH,
});
@@ -1,12 +1,8 @@
import { eyeIcon } from "../components/icons";
import { CODES, KEYS } from "../keys";
import { register } from "./register";
export const actionToggleViewMode = register({
name: "viewMode",
label: "labels.viewMode",
paletteName: "Toggle view mode",
icon: eyeIcon,
viewMode: true,
trackEvent: {
category: "canvas",
@@ -25,6 +21,7 @@ export const actionToggleViewMode = register({
predicate: (elements, appState, appProps) => {
return typeof appProps.viewModeEnabled === "undefined";
},
contextItemLabel: "labels.viewMode",
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.R,
});
@@ -1,12 +1,8 @@
import { coffeeIcon } from "../components/icons";
import { CODES, KEYS } from "../keys";
import { register } from "./register";
export const actionToggleZenMode = register({
name: "zenMode",
label: "buttons.zenMode",
icon: coffeeIcon,
paletteName: "Toggle zen mode",
viewMode: true,
trackEvent: {
category: "canvas",
@@ -25,6 +21,7 @@ export const actionToggleZenMode = register({
predicate: (elements, appState, appProps) => {
return typeof appProps.zenModeEnabled === "undefined";
},
contextItemLabel: "buttons.zenMode",
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.Z,
});
+4 -8
View File
@@ -19,8 +19,6 @@ import { isDarwin } from "../constants";
export const actionSendBackward = register({
name: "sendBackward",
label: "labels.sendBackward",
icon: SendBackwardIcon,
trackEvent: { category: "element" },
perform: (elements, appState) => {
return {
@@ -29,6 +27,7 @@ export const actionSendBackward = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.sendBackward",
keyPriority: 40,
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] &&
@@ -48,8 +47,6 @@ export const actionSendBackward = register({
export const actionBringForward = register({
name: "bringForward",
label: "labels.bringForward",
icon: BringForwardIcon,
trackEvent: { category: "element" },
perform: (elements, appState) => {
return {
@@ -58,6 +55,7 @@ export const actionBringForward = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.bringForward",
keyPriority: 40,
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] &&
@@ -77,8 +75,6 @@ export const actionBringForward = register({
export const actionSendToBack = register({
name: "sendToBack",
label: "labels.sendToBack",
icon: SendToBackIcon,
trackEvent: { category: "element" },
perform: (elements, appState) => {
return {
@@ -87,6 +83,7 @@ export const actionSendToBack = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.sendToBack",
keyTest: (event) =>
isDarwin
? event[KEYS.CTRL_OR_CMD] &&
@@ -113,8 +110,6 @@ export const actionSendToBack = register({
export const actionBringToFront = register({
name: "bringToFront",
label: "labels.bringToFront",
icon: BringToFrontIcon,
trackEvent: { category: "element" },
perform: (elements, appState) => {
@@ -124,6 +119,7 @@ export const actionBringToFront = register({
commitToHistory: true,
};
},
contextItemLabel: "labels.bringToFront",
keyTest: (event) =>
isDarwin
? event[KEYS.CTRL_OR_CMD] &&
+1 -1
View File
@@ -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";
+3 -34
View File
@@ -36,22 +36,9 @@ export type ShortcutName =
| "flipVertical"
| "hyperlink"
| "toggleElementLock"
| "resetZoom"
| "zoomOut"
| "zoomIn"
| "zoomToFit"
| "zoomToFitSelectionInViewport"
| "zoomToFitSelection"
| "toggleEraserTool"
| "toggleHandTool"
| "setFrameAsActiveTool"
| "saveFileToDisk"
| "saveToActiveFile"
| "toggleShortcuts"
>
| "saveScene"
| "imageExport"
| "commandPalette";
| "imageExport";
const shortcutMap: Record<ShortcutName, string[]> = {
toggleTheme: [getShortcutKey("Shift+Alt+D")],
@@ -59,10 +46,6 @@ const shortcutMap: Record<ShortcutName, string[]> = {
loadScene: [getShortcutKey("CtrlOrCmd+O")],
clearCanvas: [getShortcutKey("CtrlOrCmd+Delete")],
imageExport: [getShortcutKey("CtrlOrCmd+Shift+E")],
commandPalette: [
getShortcutKey("CtrlOrCmd+/"),
getShortcutKey("CtrlOrCmd+Shift+P"),
],
cut: [getShortcutKey("CtrlOrCmd+X")],
copy: [getShortcutKey("CtrlOrCmd+C")],
paste: [getShortcutKey("CtrlOrCmd+V")],
@@ -100,24 +83,10 @@ const shortcutMap: Record<ShortcutName, string[]> = {
viewMode: [getShortcutKey("Alt+R")],
hyperlink: [getShortcutKey("CtrlOrCmd+K")],
toggleElementLock: [getShortcutKey("CtrlOrCmd+Shift+L")],
resetZoom: [getShortcutKey("CtrlOrCmd+0")],
zoomOut: [getShortcutKey("CtrlOrCmd+-")],
zoomIn: [getShortcutKey("CtrlOrCmd++")],
zoomToFitSelection: [getShortcutKey("Shift+3")],
zoomToFit: [getShortcutKey("Shift+1")],
zoomToFitSelectionInViewport: [getShortcutKey("Shift+2")],
toggleEraserTool: [getShortcutKey("E")],
toggleHandTool: [getShortcutKey("H")],
setFrameAsActiveTool: [getShortcutKey("F")],
saveFileToDisk: [getShortcutKey("CtrlOrCmd+S")],
saveToActiveFile: [getShortcutKey("CtrlOrCmd+S")],
toggleShortcuts: [getShortcutKey("?")],
};
export const getShortcutFromShortcutName = (name: ShortcutName, idx = 0) => {
export const getShortcutFromShortcutName = (name: ShortcutName) => {
const shortcuts = shortcutMap[name];
// if multiple shortcuts available, take the first one
return shortcuts && shortcuts.length > 0
? shortcuts[idx] || shortcuts[0]
: "";
return shortcuts && shortcuts.length > 0 ? shortcuts[0] : "";
};
+9 -23
View File
@@ -5,16 +5,10 @@ import {
AppState,
ExcalidrawProps,
BinaryFiles,
UIAppState,
} from "../types";
import { MarkOptional } from "../utility-types";
export type ActionSource =
| "ui"
| "keyboard"
| "contextMenu"
| "api"
| "commandPalette";
export type ActionSource = "ui" | "keyboard" | "contextMenu" | "api";
/** if false, the action should be prevented */
export type ActionResult =
@@ -130,8 +124,7 @@ export type ActionName =
| "setFrameAsActiveTool"
| "setEmbeddableAsActiveTool"
| "createContainerFromText"
| "wrapTextInContainer"
| "commandPalette";
| "wrapTextInContainer";
export type PanelComponentProps = {
elements: readonly ExcalidrawElement[];
@@ -144,20 +137,6 @@ export type PanelComponentProps = {
export interface Action {
name: ActionName;
label:
| string
| ((
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
app: AppClassProperties,
) => string);
keywords?: string[];
icon?:
| React.ReactNode
| ((
appState: UIAppState,
elements: readonly ExcalidrawElement[],
) => React.ReactNode);
PanelComponent?: React.FC<PanelComponentProps>;
perform: ActionFn;
keyPriority?: number;
@@ -167,6 +146,13 @@ export interface Action {
elements: readonly ExcalidrawElement[],
app: AppClassProperties,
) => boolean;
contextItemLabel?:
| string
| ((
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
app: AppClassProperties,
) => string);
predicate?: (
elements: readonly ExcalidrawElement[],
appState: AppState,
-2
View File
@@ -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 },
+5 -224
View File
@@ -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();
}
};
+5 -5
View File
@@ -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"));
}
};
+20 -56
View File
@@ -1,7 +1,6 @@
import { useState } from "react";
import { ActionManager } from "../actions/manager";
import {
ExcalidrawElement,
ExcalidrawElementType,
NonDeletedElementsMap,
NonDeletedSceneElementsMap,
@@ -46,40 +45,6 @@ import {
import { KEYS } from "../keys";
import { useTunnels } from "../context/tunnels";
export const canChangeStrokeColor = (
appState: UIAppState,
targetElements: ExcalidrawElement[],
) => {
let commonSelectedType: ExcalidrawElementType | null =
targetElements[0]?.type || null;
for (const element of targetElements) {
if (element.type !== commonSelectedType) {
commonSelectedType = null;
break;
}
}
return (
(hasStrokeColor(appState.activeTool.type) &&
appState.activeTool.type !== "image" &&
commonSelectedType !== "image" &&
commonSelectedType !== "frame" &&
commonSelectedType !== "magicframe") ||
targetElements.some((element) => hasStrokeColor(element.type))
);
};
export const canChangeBackgroundColor = (
appState: UIAppState,
targetElements: ExcalidrawElement[],
) => {
return (
hasBackground(appState.activeTool.type) ||
targetElements.some((element) => hasBackground(element.type))
);
};
export const SelectedShapeActions = ({
appState,
elementsMap,
@@ -110,17 +75,35 @@ export const SelectedShapeActions = ({
(element) =>
hasBackground(element.type) && !isTransparent(element.backgroundColor),
);
const showChangeBackgroundIcons =
hasBackground(appState.activeTool.type) ||
targetElements.some((element) => hasBackground(element.type));
const showLinkIcon =
targetElements.length === 1 || isSingleElementBoundContainer;
let commonSelectedType: ExcalidrawElementType | null =
targetElements[0]?.type || null;
for (const element of targetElements) {
if (element.type !== commonSelectedType) {
commonSelectedType = null;
break;
}
}
return (
<div className="panelColumn">
<div>
{canChangeStrokeColor(appState, targetElements) &&
{((hasStrokeColor(appState.activeTool.type) &&
appState.activeTool.type !== "image" &&
commonSelectedType !== "image" &&
commonSelectedType !== "frame" &&
commonSelectedType !== "magicframe") ||
targetElements.some((element) => hasStrokeColor(element.type))) &&
renderAction("changeStrokeColor")}
</div>
{canChangeBackgroundColor(appState, targetElements) && (
{showChangeBackgroundIcons && (
<div>{renderAction("changeBackgroundColor")}</div>
)}
{showFillIcons && renderAction("changeFillStyle")}
@@ -323,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)}
+125 -267
View File
@@ -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,11 +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 { getShortcutFromShortcutName } from "../actions/shortcuts";
import { getFileName } from "../data/filename";
const AppContext = React.createContext<AppClassProperties>(null!);
const AppPropsContext = React.createContext<AppProps>(null!);
@@ -478,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;
@@ -621,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,
@@ -632,7 +630,6 @@ class App extends React.Component<AppProps, AppState> {
zenModeEnabled,
objectsSnapModeEnabled,
gridSize: gridModeEnabled ? GRID_SIZE : null,
name,
width: window.innerWidth,
height: window.innerHeight,
};
@@ -664,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);
},
@@ -954,7 +950,6 @@ class App extends React.Component<AppProps, AppState> {
normalizedWidth,
normalizedHeight,
this.state,
this.scene.getNonDeletedElementsMap(),
);
const hasBeenInitialized = this.initializedEmbeds.has(el.id);
@@ -1130,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(
@@ -1289,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
@@ -1415,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;
@@ -1475,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}>
@@ -1539,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}
@@ -1553,7 +1537,6 @@ class App extends React.Component<AppProps, AppState> {
isMagicFrameElement(firstSelectedElement) && (
<ElementCanvasButtons
element={firstSelectedElement}
elementsMap={elementsMap}
>
<ElementCanvasButton
title={t("labels.convertToCode")}
@@ -1574,7 +1557,6 @@ class App extends React.Component<AppProps, AppState> {
?.status === "done" && (
<ElementCanvasButtons
element={firstSelectedElement}
elementsMap={elementsMap}
>
<ElementCanvasButton
title={t("labels.copySource")}
@@ -1742,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,
},
@@ -2141,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") {
@@ -2178,7 +2160,6 @@ class App extends React.Component<AppProps, AppState> {
zenModeEnabled,
gridSize,
theme,
name,
errorMessage,
});
},
@@ -2468,7 +2449,6 @@ class App extends React.Component<AppProps, AppState> {
isSomeElementSelected.clearCache();
selectGroupsForSelectedElements.clearCache();
touchTimeout = 0;
document.documentElement.style.overscrollBehaviorX = "";
}
private onResize = withBatchedUpdates(() => {
@@ -2605,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 });
}
@@ -2762,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,
);
}
}
@@ -3126,11 +3112,7 @@ class App extends React.Component<AppProps, AppState> {
newElement,
this.scene.getElementsMapIncludingDeleted(),
);
redrawTextBoundingBox(
newElement,
container,
this.scene.getElementsMapIncludingDeleted(),
);
redrawTextBoundingBox(newElement, container);
}
});
@@ -3213,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 };
}
}),
);
@@ -3685,29 +3661,17 @@ class App extends React.Component<AppProps, AppState> {
tab,
force,
}: {
name: SidebarName | null;
name: SidebarName;
tab?: SidebarTabName;
force?: boolean;
}): boolean => {
let nextName;
if (force === undefined) {
nextName =
this.state.openSidebar?.name === name &&
this.state.openSidebar?.tab === tab
? null
: name;
nextName = this.state.openSidebar?.name === name ? null : name;
} else {
nextName = force ? name : null;
}
const nextState: AppState["openSidebar"] = nextName
? { name: nextName }
: null;
if (nextState && tab) {
nextState.tab = tab;
}
this.setState({ openSidebar: nextState });
this.setState({ openSidebar: nextName ? { name: nextName, tab } : null });
return !!nextName;
};
@@ -3747,21 +3711,6 @@ class App extends React.Component<AppProps, AppState> {
});
}
if (
event[KEYS.CTRL_OR_CMD] &&
event.key === KEYS.P &&
!event.shiftKey &&
!event.altKey
) {
this.setToast({
message: t("commandPalette.shortcutHint", {
shortcut: getShortcutFromShortcutName("commandPalette"),
}),
});
event.preventDefault();
return;
}
if (event[KEYS.CTRL_OR_CMD] && event.key.toLowerCase() === KEYS.V) {
IS_PLAIN_PASTE = event.shiftKey;
clearTimeout(IS_PLAIN_PASTE_TIMER);
@@ -3873,7 +3822,7 @@ class App extends React.Component<AppProps, AppState> {
y: element.y + offsetY,
});
updateBoundElements(element, this.scene.getNonDeletedElementsMap(), {
updateBoundElements(element, {
simultaneouslyUpdated: selectedElements,
});
});
@@ -3896,6 +3845,7 @@ class App extends React.Component<AppProps, AppState> {
this.setState({
editingLinearElement: new LinearElementEditor(
selectedElement,
this.scene,
),
});
}
@@ -4046,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: [] });
}
});
@@ -4155,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();
@@ -4234,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,
@@ -4280,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 }) => {
@@ -4419,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,
@@ -4427,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;
});
}
@@ -4617,9 +4552,17 @@ 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 (
this.state.editingLinearElement &&
this.state.editingLinearElement.elementId === selectedElements[0].id
) {
return;
}
}
@@ -4672,7 +4615,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
sceneX,
sceneY,
this.scene.getNonDeletedElementsMap(),
);
if (container) {
@@ -4684,7 +4626,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
this.frameNameBoundsCache,
[sceneX, sceneY],
this.scene.getNonDeletedElementsMap(),
)
) {
const midPoint = getContainerCenter(
@@ -4725,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,
@@ -4756,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,
@@ -4770,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,
@@ -4792,11 +4729,7 @@ class App extends React.Component<AppProps, AppState> {
}
if (!customEvent?.defaultPrevented) {
const target = isLocalLink(url) ? "_self" : "_blank";
const newWindow = window.open(
undefined,
target,
"noopener noreferrer",
);
const newWindow = window.open(undefined, target);
// https://mathiasbynens.github.io/rel-noopener/
if (newWindow) {
newWindow.opener = null;
@@ -4811,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;
@@ -4919,7 +4851,6 @@ class App extends React.Component<AppProps, AppState> {
y: scenePointerY,
},
event,
this.scene.getNonDeletedElementsMap(),
);
this.setState((prevState) => {
@@ -4959,7 +4890,6 @@ class App extends React.Component<AppProps, AppState> {
scenePointerX,
scenePointerY,
this.state,
this.scene.getNonDeletedElementsMap(),
);
if (
@@ -5110,7 +5040,6 @@ class App extends React.Component<AppProps, AppState> {
scenePointerY,
this.state.zoom,
event.pointerType,
this.scene.getNonDeletedElementsMap(),
);
if (
elementWithTransformHandleType &&
@@ -5158,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 (
@@ -5340,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) {
@@ -5360,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,
@@ -5795,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 {
@@ -6098,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(
@@ -6110,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({
@@ -6134,7 +6050,6 @@ class App extends React.Component<AppProps, AppState> {
getResizeOffsetXY(
pointerDownState.resize.handleType,
selectedElements,
elementsMap,
pointerDownState.origin.x,
pointerDownState.origin.y,
),
@@ -6159,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;
@@ -6416,7 +6330,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
sceneX,
sceneY,
this.scene.getNonDeletedElementsMap(),
);
if (hasBoundTextElement(element)) {
@@ -6497,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({
@@ -6766,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);
@@ -6913,7 +6824,6 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getNonDeletedElements(),
selectedElements,
this.state,
this.scene.getNonDeletedElementsMap(),
),
);
}
@@ -6937,7 +6847,6 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getNonDeletedElements(),
selectedElements,
this.state,
this.scene.getNonDeletedElementsMap(),
),
);
}
@@ -7037,7 +6946,6 @@ class App extends React.Component<AppProps, AppState> {
return true;
}
}
const elementsMap = this.scene.getNonDeletedElementsMap();
if (this.state.selectedLinearElement) {
const linearElementEditor =
@@ -7048,7 +6956,6 @@ class App extends React.Component<AppProps, AppState> {
this.state.selectedLinearElement,
pointerCoords,
this.state,
elementsMap,
)
) {
const ret = LinearElementEditor.addMidpoint(
@@ -7056,7 +6963,6 @@ class App extends React.Component<AppProps, AppState> {
pointerCoords,
this.state,
!event[KEYS.CTRL_OR_CMD],
elementsMap,
);
if (!ret) {
return;
@@ -7215,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 });
@@ -7403,7 +7308,6 @@ class App extends React.Component<AppProps, AppState> {
event,
this.state,
this.setState.bind(this),
this.scene.getNonDeletedElementsMap(),
);
// regular box-select
} else {
@@ -7434,7 +7338,6 @@ class App extends React.Component<AppProps, AppState> {
const elementsWithinSelection = getElementsWithinSelection(
elements,
draggingElement,
this.scene.getNonDeletedElementsMap(),
);
this.setState((prevState) => {
@@ -7477,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 &&
@@ -7563,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) {
@@ -7578,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({
@@ -7603,8 +7507,6 @@ class App extends React.Component<AppProps, AppState> {
childEvent,
this.state.selectedLinearElement,
this.state,
this.scene.getNonDeletedElements(),
elementsMap,
);
const { startBindingElement, endBindingElement } =
@@ -7615,7 +7517,6 @@ class App extends React.Component<AppProps, AppState> {
element,
startBindingElement,
endBindingElement,
elementsMap,
);
}
@@ -7755,7 +7656,6 @@ class App extends React.Component<AppProps, AppState> {
this.state,
this.scene,
pointerCoords,
elementsMap,
);
}
this.setState({ suggestedBindings: [], startBoundElement: null });
@@ -7773,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) => ({
@@ -7820,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, {
@@ -7940,7 +7837,6 @@ class App extends React.Component<AppProps, AppState> {
const elementsInsideFrame = getElementsInNewFrame(
this.scene.getElementsIncludingDeleted(),
draggingElement,
this.scene.getNonDeletedElementsMap(),
);
this.scene.replaceAllElements(
@@ -7991,7 +7887,6 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getElementsIncludingDeleted(),
frame,
this.state,
elementsMap,
),
frame,
this,
@@ -8013,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,
),
});
}
}
@@ -8126,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,
};
});
@@ -8200,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,
}));
}
@@ -8264,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") {
@@ -8509,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);
@@ -8758,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:
@@ -8786,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 &&
@@ -8813,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 });
}
@@ -8909,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;
}
}
}
@@ -8985,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({
@@ -9042,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 });
}
};
@@ -9101,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),
@@ -9173,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;
@@ -9212,7 +9074,6 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getNonDeletedElements(),
draggingElement as ExcalidrawFrameLikeElement,
this.state,
this.scene.getNonDeletedElementsMap(),
),
});
}
@@ -9332,7 +9193,6 @@ class App extends React.Component<AppProps, AppState> {
this.scene.getNonDeletedElements(),
frame,
this.state,
this.scene.getNonDeletedElementsMap(),
).forEach((element) => elementsToHighlight.add(element));
});
@@ -9629,6 +9489,7 @@ class App extends React.Component<AppProps, AppState> {
// -----------------------------------------------------------------------------
// TEST HOOKS
// -----------------------------------------------------------------------------
declare global {
interface Window {
h: {
@@ -9641,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;
+12 -3
View File
@@ -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"
@@ -1,137 +0,0 @@
@import "../../css/variables.module.scss";
$verticalBreakpoint: 861px;
.excalidraw {
.command-palette-dialog {
user-select: none;
.Modal__content {
height: auto;
max-height: 100%;
@media screen and (min-width: $verticalBreakpoint) {
max-height: 750px;
height: 100%;
}
.Island {
height: 100%;
padding: 1.5rem;
}
.Dialog__content {
height: 100%;
display: flex;
flex-direction: column;
}
}
.shortcuts-wrapper {
display: flex;
justify-content: center;
align-items: center;
margin-top: 12px;
gap: 1.5rem;
}
.shortcut {
display: flex;
justify-content: center;
align-items: center;
height: 16px;
font-size: 10px;
gap: 0.25rem;
.shortcut-wrapper {
display: flex;
}
.shortcut-plus {
margin: 0px 4px;
}
.shortcut-key {
padding: 0px 4px;
height: 16px;
border-radius: 4px;
display: flex;
justify-content: center;
align-items: center;
background-color: var(--color-primary-light);
}
.shortcut-desc {
margin-left: 4px;
color: var(--color-gray-50);
}
}
.commands {
overflow-y: auto;
box-sizing: border-box;
margin-top: 12px;
color: var(--popup-text-color);
user-select: none;
.command-category {
display: flex;
flex-direction: column;
padding: 12px 0px;
margin-right: 0.25rem;
}
.command-category-title {
font-size: 1rem;
font-weight: 600;
margin-bottom: 6px;
display: flex;
align-items: center;
}
.command-item {
color: var(--popup-text-color);
height: 2.5rem;
display: flex;
justify-content: space-between;
align-items: center;
box-sizing: border-box;
padding: 0 0.5rem;
border-radius: var(--border-radius-lg);
cursor: pointer;
&:active {
background-color: var(--color-surface-low);
}
.name {
display: flex;
align-items: center;
gap: 0.25rem;
}
}
.item-selected {
background-color: var(--color-surface-mid);
}
.item-disabled {
opacity: 0.3;
cursor: not-allowed;
}
.no-match {
display: flex;
justify-content: center;
align-items: center;
margin-top: 36px;
}
}
.icon {
width: 16px;
height: 16px;
margin-right: 6px;
}
}
}
@@ -1,916 +0,0 @@
import { useEffect, useRef, useState } from "react";
import {
useApp,
useAppProps,
useExcalidrawActionManager,
useExcalidrawSetAppState,
} from "../App";
import { KEYS } from "../../keys";
import { Dialog } from "../Dialog";
import { TextField } from "../TextField";
import clsx from "clsx";
import { getSelectedElements } from "../../scene";
import { Action } from "../../actions/types";
import { TranslationKeys, t } from "../../i18n";
import {
ShortcutName,
getShortcutFromShortcutName,
} from "../../actions/shortcuts";
import { DEFAULT_SIDEBAR, EVENT } from "../../constants";
import {
LockedIcon,
UnlockedIcon,
clockIcon,
searchIcon,
boltIcon,
bucketFillIcon,
ExportImageIcon,
mermaidLogoIcon,
brainIconThin,
LibraryIcon,
} from "../icons";
import fuzzy from "fuzzy";
import { useUIAppState } from "../../context/ui-appState";
import { AppProps, AppState, UIAppState } from "../../types";
import {
capitalizeString,
getShortcutKey,
isWritableElement,
} from "../../utils";
import { atom, useAtom } from "jotai";
import { deburr } from "../../deburr";
import { MarkRequired } from "../../utility-types";
import { InlineIcon } from "../InlineIcon";
import { SHAPES } from "../../shapes";
import { canChangeBackgroundColor, canChangeStrokeColor } from "../Actions";
import { useStableCallback } from "../../hooks/useStableCallback";
import { actionClearCanvas, actionLink } from "../../actions";
import { jotaiStore } from "../../jotai";
import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
import { CommandPaletteItem } from "./types";
import * as defaultItems from "./defaultCommandPaletteItems";
import "./CommandPalette.scss";
const lastUsedPaletteItem = atom<CommandPaletteItem | null>(null);
export const DEFAULT_CATEGORIES = {
app: "App",
export: "Export",
tools: "Tools",
editor: "Editor",
elements: "Elements",
links: "Links",
};
const getCategoryOrder = (category: string) => {
switch (category) {
case DEFAULT_CATEGORIES.app:
return 1;
case DEFAULT_CATEGORIES.export:
return 2;
case DEFAULT_CATEGORIES.editor:
return 3;
case DEFAULT_CATEGORIES.tools:
return 4;
case DEFAULT_CATEGORIES.elements:
return 5;
case DEFAULT_CATEGORIES.links:
return 6;
default:
return 10;
}
};
const CommandShortcutHint = ({
shortcut,
className,
children,
}: {
shortcut: string;
className?: string;
children?: React.ReactNode;
}) => {
const shortcuts = shortcut.replace("++", "+$").split("+");
return (
<div className={clsx("shortcut", className)}>
{shortcuts.map((item, idx) => {
return (
<div className="shortcut-wrapper" key={item}>
<div className="shortcut-key">{item === "$" ? "+" : item}</div>
</div>
);
})}
<div className="shortcut-desc">{children}</div>
</div>
);
};
const isCommandPaletteToggleShortcut = (event: KeyboardEvent) => {
return (
!event.altKey &&
event[KEYS.CTRL_OR_CMD] &&
((event.shiftKey && event.key.toLowerCase() === KEYS.P) ||
event.key === KEYS.SLASH)
);
};
type CommandPaletteProps = {
customCommandPaletteItems?: CommandPaletteItem[];
};
export const CommandPalette = Object.assign(
(props: CommandPaletteProps) => {
const uiAppState = useUIAppState();
const setAppState = useExcalidrawSetAppState();
useEffect(() => {
const commandPaletteShortcut = (event: KeyboardEvent) => {
if (isCommandPaletteToggleShortcut(event)) {
event.preventDefault();
event.stopPropagation();
setAppState((appState) => ({
openDialog:
appState.openDialog?.name === "commandPalette"
? null
: { name: "commandPalette" },
}));
}
};
window.addEventListener(EVENT.KEYDOWN, commandPaletteShortcut, {
capture: true,
});
return () =>
window.removeEventListener(EVENT.KEYDOWN, commandPaletteShortcut, {
capture: true,
});
}, [setAppState]);
if (uiAppState.openDialog?.name !== "commandPalette") {
return null;
}
return <CommandPaletteInner {...props} />;
},
{
defaultItems,
},
);
function CommandPaletteInner({
customCommandPaletteItems,
}: CommandPaletteProps) {
const app = useApp();
const uiAppState = useUIAppState();
const setAppState = useExcalidrawSetAppState();
const appProps = useAppProps();
const actionManager = useExcalidrawActionManager();
const [lastUsed, setLastUsed] = useAtom(lastUsedPaletteItem);
const [allCommands, setAllCommands] = useState<
MarkRequired<CommandPaletteItem, "haystack" | "order">[] | null
>(null);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!uiAppState || !app.scene || !actionManager) {
return;
}
const getActionLabel = (action: Action) => {
let label = "";
if (action.label) {
if (typeof action.label === "function") {
label = t(
action.label(
app.scene.getNonDeletedElements(),
uiAppState as AppState,
app,
) as unknown as TranslationKeys,
);
} else {
label = t(action.label as unknown as TranslationKeys);
}
}
return label;
};
const getActionIcon = (action: Action) => {
if (typeof action.icon === "function") {
return action.icon(uiAppState, app.scene.getNonDeletedElements());
}
return action.icon;
};
let commandsFromActions: CommandPaletteItem[] = [];
const actionToCommand = (
action: Action,
category: string,
transformer?: (
command: CommandPaletteItem,
action: Action,
) => CommandPaletteItem,
): CommandPaletteItem => {
const command: CommandPaletteItem = {
label: getActionLabel(action),
icon: getActionIcon(action),
category,
shortcut: getShortcutFromShortcutName(action.name as ShortcutName),
keywords: action.keywords,
predicate: action.predicate,
viewMode: action.viewMode,
perform: () => {
actionManager.executeAction(action, "commandPalette");
},
};
return transformer ? transformer(command, action) : command;
};
if (uiAppState && app.scene && actionManager) {
const elementsCommands: CommandPaletteItem[] = [
actionManager.actions.group,
actionManager.actions.ungroup,
actionManager.actions.cut,
actionManager.actions.copy,
actionManager.actions.deleteSelectedElements,
actionManager.actions.copyStyles,
actionManager.actions.pasteStyles,
actionManager.actions.sendBackward,
actionManager.actions.sendToBack,
actionManager.actions.bringForward,
actionManager.actions.bringToFront,
actionManager.actions.alignTop,
actionManager.actions.alignBottom,
actionManager.actions.alignLeft,
actionManager.actions.alignRight,
actionManager.actions.alignVerticallyCentered,
actionManager.actions.alignHorizontallyCentered,
actionManager.actions.duplicateSelection,
actionManager.actions.flipHorizontal,
actionManager.actions.flipVertical,
actionManager.actions.zoomToFitSelection,
actionManager.actions.zoomToFitSelectionInViewport,
actionManager.actions.increaseFontSize,
actionManager.actions.decreaseFontSize,
actionManager.actions.toggleLinearEditor,
actionLink,
].map((action: Action) =>
actionToCommand(
action,
DEFAULT_CATEGORIES.elements,
(command, action) => ({
...command,
predicate: action.predicate
? action.predicate
: (elements, appState, appProps, app) => {
const selectedElements = getSelectedElements(
elements,
appState,
);
return selectedElements.length > 0;
},
}),
),
);
const toolCommands: CommandPaletteItem[] = [
actionManager.actions.toggleHandTool,
actionManager.actions.setFrameAsActiveTool,
].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.tools));
const editorCommands: CommandPaletteItem[] = [
actionManager.actions.undo,
actionManager.actions.redo,
actionManager.actions.zoomIn,
actionManager.actions.zoomOut,
actionManager.actions.resetZoom,
actionManager.actions.zoomToFit,
actionManager.actions.zenMode,
actionManager.actions.viewMode,
actionManager.actions.objectsSnapMode,
actionManager.actions.toggleShortcuts,
actionManager.actions.selectAll,
actionManager.actions.toggleElementLock,
actionManager.actions.unlockAllElements,
actionManager.actions.stats,
].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.editor));
const exportCommands: CommandPaletteItem[] = [
actionManager.actions.saveToActiveFile,
actionManager.actions.saveFileToDisk,
actionManager.actions.copyAsPng,
actionManager.actions.copyAsSvg,
].map((action) => actionToCommand(action, DEFAULT_CATEGORIES.export));
commandsFromActions = [
...elementsCommands,
...editorCommands,
{
label: getActionLabel(actionClearCanvas),
icon: getActionIcon(actionClearCanvas),
shortcut: getShortcutFromShortcutName(
actionClearCanvas.name as ShortcutName,
),
category: DEFAULT_CATEGORIES.editor,
keywords: ["delete", "destroy"],
viewMode: false,
perform: () => {
jotaiStore.set(activeConfirmDialogAtom, "clearCanvas");
},
},
{
label: t("buttons.exportImage"),
category: DEFAULT_CATEGORIES.export,
icon: ExportImageIcon,
shortcut: getShortcutFromShortcutName("imageExport"),
keywords: [
"export",
"image",
"png",
"jpeg",
"svg",
"clipboard",
"picture",
],
perform: () => {
setAppState({ openDialog: { name: "imageExport" } });
},
},
...exportCommands,
];
const additionalCommands: CommandPaletteItem[] = [
{
label: t("toolBar.library"),
category: DEFAULT_CATEGORIES.app,
icon: LibraryIcon,
viewMode: false,
perform: () => {
if (uiAppState.openSidebar) {
setAppState({
openSidebar: null,
});
} else {
setAppState({
openSidebar: {
name: DEFAULT_SIDEBAR.name,
tab: DEFAULT_SIDEBAR.defaultTab,
},
});
}
},
},
{
label: t("labels.changeStroke"),
keywords: ["color", "outline"],
category: DEFAULT_CATEGORIES.elements,
icon: bucketFillIcon,
viewMode: false,
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
selectedElements.length > 0 &&
canChangeStrokeColor(appState, selectedElements)
);
},
perform: () => {
setAppState((prevState) => ({
openMenu: prevState.openMenu === "shape" ? null : "shape",
openPopup: "elementStroke",
}));
},
},
{
label: t("labels.changeBackground"),
keywords: ["color", "fill"],
icon: bucketFillIcon,
category: DEFAULT_CATEGORIES.elements,
viewMode: false,
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
return (
selectedElements.length > 0 &&
canChangeBackgroundColor(appState, selectedElements)
);
},
perform: () => {
setAppState((prevState) => ({
openMenu: prevState.openMenu === "shape" ? null : "shape",
openPopup: "elementBackground",
}));
},
},
{
label: t("labels.canvasBackground"),
keywords: ["color"],
icon: bucketFillIcon,
category: DEFAULT_CATEGORIES.editor,
viewMode: false,
perform: () => {
setAppState((prevState) => ({
openMenu: prevState.openMenu === "canvas" ? null : "canvas",
openPopup: "canvasBackground",
}));
},
},
...SHAPES.reduce((acc: CommandPaletteItem[], shape) => {
const { value, icon, key, numericKey } = shape;
if (
appProps.UIOptions.tools?.[
value as Extract<
typeof value,
keyof AppProps["UIOptions"]["tools"]
>
] === false
) {
return acc;
}
const letter =
key && capitalizeString(typeof key === "string" ? key : key[0]);
const shortcut = letter || numericKey;
const command: CommandPaletteItem = {
label: t(`toolBar.${value}`),
category: DEFAULT_CATEGORIES.tools,
shortcut,
icon,
keywords: ["toolbar"],
viewMode: false,
perform: ({ event }) => {
if (value === "image") {
app.setActiveTool({
type: value,
insertOnCanvasDirectly: event.type === EVENT.KEYDOWN,
});
} else {
app.setActiveTool({ type: value });
}
},
};
acc.push(command);
return acc;
}, []),
...toolCommands,
{
label: t("toolBar.lock"),
category: DEFAULT_CATEGORIES.tools,
icon: uiAppState.activeTool.locked ? LockedIcon : UnlockedIcon,
shortcut: KEYS.Q.toLocaleUpperCase(),
viewMode: false,
perform: () => {
app.toggleLock();
},
},
{
label: `${t("labels.textToDiagram")}...`,
category: DEFAULT_CATEGORIES.tools,
icon: brainIconThin,
viewMode: false,
predicate: appProps.aiEnabled,
perform: () => {
setAppState((state) => ({
...state,
openDialog: {
name: "ttd",
tab: "text-to-diagram",
},
}));
},
},
{
label: `${t("toolBar.mermaidToExcalidraw")}...`,
category: DEFAULT_CATEGORIES.tools,
icon: mermaidLogoIcon,
viewMode: false,
predicate: appProps.aiEnabled,
perform: () => {
setAppState((state) => ({
...state,
openDialog: {
name: "ttd",
tab: "mermaid",
},
}));
},
},
// {
// label: `${t("toolBar.magicframe")}...`,
// category: DEFAULT_CATEGORIES.tools,
// icon: MagicIconThin,
// viewMode: false,
// predicate: appProps.aiEnabled,
// perform: () => {
// app.onMagicframeToolSelect();
// },
// },
];
const allCommands = [
...commandsFromActions,
...additionalCommands,
...(customCommandPaletteItems || []),
].map((command) => {
return {
...command,
icon: command.icon || boltIcon,
order: command.order ?? getCategoryOrder(command.category),
haystack: `${deburr(command.label)} ${
command.keywords?.join(" ") || ""
}`,
};
});
setAllCommands(allCommands);
setLastUsed(
allCommands.find((command) => command.label === lastUsed?.label) ??
null,
);
}
}, [
app,
appProps,
uiAppState,
actionManager,
setAllCommands,
lastUsed?.label,
setLastUsed,
setAppState,
customCommandPaletteItems,
]);
const [commandSearch, setCommandSearch] = useState("");
const [currentCommand, setCurrentCommand] =
useState<CommandPaletteItem | null>(null);
const [commandsByCategory, setCommandsByCategory] = useState<
Record<string, CommandPaletteItem[]>
>({});
const closeCommandPalette = (cb?: () => void) => {
setAppState(
{
openDialog: null,
},
cb,
);
setCommandSearch("");
};
const executeCommand = (
command: CommandPaletteItem,
event: React.MouseEvent | React.KeyboardEvent | KeyboardEvent,
) => {
if (uiAppState.openDialog?.name === "commandPalette") {
event.stopPropagation();
event.preventDefault();
document.body.classList.add("excalidraw-animations-disabled");
closeCommandPalette(() => {
command.perform({ actionManager, event });
setLastUsed(command);
requestAnimationFrame(() => {
document.body.classList.remove("excalidraw-animations-disabled");
});
});
}
};
const isCommandAvailable = useStableCallback(
(command: CommandPaletteItem) => {
if (command.viewMode === false && uiAppState.viewModeEnabled) {
return false;
}
return typeof command.predicate === "function"
? command.predicate(
app.scene.getNonDeletedElements(),
uiAppState as AppState,
appProps,
app,
)
: command.predicate === undefined || command.predicate;
},
);
const handleKeyDown = useStableCallback((event: KeyboardEvent) => {
const ignoreAlphanumerics =
isWritableElement(event.target) ||
isCommandPaletteToggleShortcut(event) ||
event.key === KEYS.ESCAPE;
if (
ignoreAlphanumerics &&
event.key !== KEYS.ARROW_UP &&
event.key !== KEYS.ARROW_DOWN &&
event.key !== KEYS.ENTER
) {
return;
}
const matchingCommands = Object.values(commandsByCategory).flat();
const shouldConsiderLastUsed =
lastUsed && !commandSearch && isCommandAvailable(lastUsed);
if (event.key === KEYS.ARROW_UP) {
event.preventDefault();
const index = matchingCommands.findIndex(
(item) => item.label === currentCommand?.label,
);
if (shouldConsiderLastUsed) {
if (index === 0) {
setCurrentCommand(lastUsed);
return;
}
if (currentCommand === lastUsed) {
const nextItem = matchingCommands[matchingCommands.length - 1];
if (nextItem) {
setCurrentCommand(nextItem);
}
return;
}
}
let nextIndex;
if (index === -1) {
nextIndex = matchingCommands.length - 1;
} else {
nextIndex =
index === 0
? matchingCommands.length - 1
: (index - 1) % matchingCommands.length;
}
const nextItem = matchingCommands[nextIndex];
if (nextItem) {
setCurrentCommand(nextItem);
}
return;
}
if (event.key === KEYS.ARROW_DOWN) {
event.preventDefault();
const index = matchingCommands.findIndex(
(item) => item.label === currentCommand?.label,
);
if (shouldConsiderLastUsed) {
if (!currentCommand || index === matchingCommands.length - 1) {
setCurrentCommand(lastUsed);
return;
}
if (currentCommand === lastUsed) {
const nextItem = matchingCommands[0];
if (nextItem) {
setCurrentCommand(nextItem);
}
return;
}
}
const nextIndex = (index + 1) % matchingCommands.length;
const nextItem = matchingCommands[nextIndex];
if (nextItem) {
setCurrentCommand(nextItem);
}
return;
}
if (event.key === KEYS.ENTER) {
if (currentCommand) {
setTimeout(() => {
executeCommand(currentCommand, event);
});
}
}
if (ignoreAlphanumerics) {
return;
}
// prevent regular editor shortcuts
event.stopPropagation();
// if alphanumeric keypress and we're not inside the input, focus it
if (/^[a-zA-Z0-9]$/.test(event.key)) {
inputRef?.current?.focus();
return;
}
event.preventDefault();
});
useEffect(() => {
window.addEventListener(EVENT.KEYDOWN, handleKeyDown, {
capture: true,
});
return () =>
window.removeEventListener(EVENT.KEYDOWN, handleKeyDown, {
capture: true,
});
}, [handleKeyDown]);
useEffect(() => {
if (!allCommands) {
return;
}
const getNextCommandsByCategory = (commands: CommandPaletteItem[]) => {
const nextCommandsByCategory: Record<string, CommandPaletteItem[]> = {};
for (const command of commands) {
if (nextCommandsByCategory[command.category]) {
nextCommandsByCategory[command.category].push(command);
} else {
nextCommandsByCategory[command.category] = [command];
}
}
return nextCommandsByCategory;
};
let matchingCommands = allCommands
.filter(isCommandAvailable)
.sort((a, b) => a.order - b.order);
const showLastUsed =
!commandSearch && lastUsed && isCommandAvailable(lastUsed);
if (!commandSearch) {
setCommandsByCategory(
getNextCommandsByCategory(
showLastUsed
? matchingCommands.filter(
(command) => command.label !== lastUsed?.label,
)
: matchingCommands,
),
);
setCurrentCommand(showLastUsed ? lastUsed : matchingCommands[0] || null);
return;
}
const _query = deburr(commandSearch.replace(/[<>-_| ]/g, ""));
matchingCommands = fuzzy
.filter(_query, matchingCommands, {
extract: (command) => command.haystack,
})
.sort((a, b) => b.score - a.score)
.map((item) => item.original);
setCommandsByCategory(getNextCommandsByCategory(matchingCommands));
setCurrentCommand(matchingCommands[0] ?? null);
}, [commandSearch, allCommands, isCommandAvailable, lastUsed]);
return (
<Dialog
onCloseRequest={() => closeCommandPalette()}
closeOnClickOutside
title={false}
size={720}
autofocus
className="command-palette-dialog"
>
<TextField
value={commandSearch}
placeholder={t("commandPalette.search.placeholder")}
onChange={(value) => {
setCommandSearch(value);
}}
selectOnRender
ref={inputRef}
/>
{!app.device.viewport.isMobile && (
<div className="shortcuts-wrapper">
<CommandShortcutHint shortcut="↑↓">
{t("commandPalette.shortcuts.select")}
</CommandShortcutHint>
<CommandShortcutHint shortcut="↵">
{t("commandPalette.shortcuts.confirm")}
</CommandShortcutHint>
<CommandShortcutHint shortcut={getShortcutKey("Esc")}>
{t("commandPalette.shortcuts.close")}
</CommandShortcutHint>
</div>
)}
<div className="commands">
{lastUsed && !commandSearch && (
<div className="command-category">
<div className="command-category-title">
{t("commandPalette.recents")}
<div
className="icon"
style={{
marginLeft: "6px",
}}
>
{clockIcon}
</div>
</div>
<CommandItem
command={lastUsed}
isSelected={lastUsed.label === currentCommand?.label}
onClick={(event) => executeCommand(lastUsed, event)}
disabled={!isCommandAvailable(lastUsed)}
onMouseMove={() => setCurrentCommand(lastUsed)}
showShortcut={!app.device.viewport.isMobile}
appState={uiAppState}
/>
</div>
)}
{Object.keys(commandsByCategory).length > 0 ? (
Object.keys(commandsByCategory).map((category, idx) => {
return (
<div className="command-category" key={category}>
<div className="command-category-title">{category}</div>
{commandsByCategory[category].map((command) => (
<CommandItem
key={command.label}
command={command}
isSelected={command.label === currentCommand?.label}
onClick={(event) => executeCommand(command, event)}
onMouseMove={() => setCurrentCommand(command)}
showShortcut={!app.device.viewport.isMobile}
appState={uiAppState}
/>
))}
</div>
);
})
) : allCommands ? (
<div className="no-match">
<div className="icon">{searchIcon}</div>{" "}
{t("commandPalette.search.noMatch")}
</div>
) : null}
</div>
</Dialog>
);
}
const CommandItem = ({
command,
isSelected,
disabled,
onMouseMove,
onClick,
showShortcut,
appState,
}: {
command: CommandPaletteItem;
isSelected: boolean;
disabled?: boolean;
onMouseMove: () => void;
onClick: (event: React.MouseEvent) => void;
showShortcut: boolean;
appState: UIAppState;
}) => {
const noop = () => {};
return (
<div
className={clsx("command-item", {
"item-selected": isSelected,
"item-disabled": disabled,
})}
ref={(ref) => {
if (isSelected && !disabled) {
ref?.scrollIntoView?.({
block: "nearest",
});
}
}}
onClick={disabled ? noop : onClick}
onMouseMove={disabled ? noop : onMouseMove}
title={disabled ? t("commandPalette.itemNotAvailable") : ""}
>
<div className="name">
{command.icon && (
<InlineIcon
icon={
typeof command.icon === "function"
? command.icon(appState)
: command.icon
}
/>
)}
{command.label}
</div>
{showShortcut && command.shortcut && (
<CommandShortcutHint shortcut={command.shortcut} />
)}
</div>
);
};
@@ -1,11 +0,0 @@
import { actionToggleTheme } from "../../actions";
import { CommandPaletteItem } from "./types";
export const toggleTheme: CommandPaletteItem = {
...actionToggleTheme,
category: "App",
label: "Toggle theme",
perform: ({ actionManager }) => {
actionManager.executeAction(actionToggleTheme, "commandPalette");
},
};
@@ -1,26 +0,0 @@
import { ActionManager } from "../../actions/manager";
import { Action } from "../../actions/types";
import { UIAppState } from "../../types";
export type CommandPaletteItem = {
label: string;
/** additional keywords to match against
* (appended to haystack, not displayed) */
keywords?: string[];
/**
* string we should match against when searching
* (deburred name + keywords)
*/
haystack?: string;
icon?: React.ReactNode | ((appState: UIAppState) => React.ReactNode);
category: string;
order?: number;
predicate?: boolean | Action["predicate"];
shortcut?: string;
/** if false, command will not show while in view mode */
viewMode?: boolean;
perform: (data: {
actionManager: ActionManager;
event: React.MouseEvent | React.KeyboardEvent | KeyboardEvent;
}) => void;
};
@@ -78,17 +78,17 @@ export const ContextMenu = React.memo(
const actionName = item.name;
let label = "";
if (item.label) {
if (typeof item.label === "function") {
if (item.contextItemLabel) {
if (typeof item.contextItemLabel === "function") {
label = t(
item.label(
item.contextItemLabel(
elements,
appState,
actionManager.app,
) as unknown as TranslationKeys,
);
} else {
label = t(item.label as unknown as TranslationKeys);
label = t(item.contextItemLabel as unknown as TranslationKeys);
}
}
@@ -37,12 +37,6 @@
width: 1.5rem;
height: 1.5rem;
}
& + .Dialog__content {
--offset: 28px;
height: calc(100% - var(--offset)) !important;
margin-top: var(--offset) !important;
}
}
.Dialog--fullscreen {
+14 -18
View File
@@ -1,6 +1,7 @@
import clsx from "clsx";
import React, { useEffect, useState } from "react";
import { useCallbackRefState } from "../hooks/useCallbackRefState";
import { t } from "../i18n";
import {
useExcalidrawContainer,
useDevice,
@@ -8,14 +9,13 @@ import {
} from "./App";
import { KEYS } from "../keys";
import "./Dialog.scss";
import { back, CloseIcon } from "./icons";
import { Island } from "./Island";
import { Modal } from "./Modal";
import { queryFocusableElements } from "../utils";
import { useSetAtom } from "jotai";
import { isLibraryMenuOpenAtom } from "./LibraryMenu";
import { jotaiScope } from "../jotai";
import { t } from "../i18n";
import { CloseIcon } from "./icons";
export type DialogSize = number | "small" | "regular" | "wide" | undefined;
@@ -58,12 +58,10 @@ export const Dialog = (props: DialogProps) => {
const focusableElements = queryFocusableElements(islandNode);
setTimeout(() => {
if (focusableElements.length > 0 && props.autofocus !== false) {
// If there's an element other than close, focus it.
(focusableElements[1] || focusableElements[0]).focus();
}
});
if (focusableElements.length > 0 && props.autofocus !== false) {
// If there's an element other than close, focus it.
(focusableElements[1] || focusableElements[0]).focus();
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === KEYS.TAB) {
@@ -117,16 +115,14 @@ export const Dialog = (props: DialogProps) => {
<span className="Dialog__titleContent">{props.title}</span>
</h2>
)}
{isFullscreen && (
<button
className="Dialog__close"
onClick={onClose}
title={t("buttons.close")}
aria-label={t("buttons.close")}
>
{CloseIcon}
</button>
)}
<button
className="Dialog__close"
onClick={onClose}
title={t("buttons.close")}
aria-label={t("buttons.close")}
>
{isFullscreen ? back : CloseIcon}
</button>
<div className="Dialog__content">{props.children}</div>
</Island>
</Modal>
@@ -10,10 +10,6 @@
background-color: var(--back-color);
border-color: var(--border-color);
&:hover {
transition: all 150ms ease-out;
}
.Spinner {
--spinner-color: var(--color-surface-lowest);
position: absolute;
@@ -207,6 +203,8 @@
user-select: none;
transition: all 150ms ease-out;
&--size-large {
font-weight: 600;
font-size: 0.875rem;
@@ -7,7 +7,6 @@ import "./HelpDialog.scss";
import { ExternalLinkIcon } from "./icons";
import { probablySupportsClipboardBlob } from "../clipboard";
import { isDarwin, isFirefox, isWindows } from "../constants";
import { getShortcutFromShortcutName } from "../actions/shortcuts";
const Header = () => (
<div className="HelpDialog__header">
@@ -279,17 +278,6 @@ export const HelpDialog = ({ onClose }: { onClose?: () => void }) => {
label={t("stats.title")}
shortcuts={[getShortcutKey("Alt+/")]}
/>
<Shortcut
label={t("commandPalette.title")}
shortcuts={
isFirefox
? [getShortcutFromShortcutName("commandPalette")]
: [
getShortcutFromShortcutName("commandPalette"),
getShortcutFromShortcutName("commandPalette", 1),
]
}
/>
</ShortcutIsland>
<ShortcutIsland
className="HelpDialog__island--editor"
@@ -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>
);
@@ -1,4 +1,4 @@
export const InlineIcon = ({ icon }: { icon: React.ReactNode }) => {
export const InlineIcon = ({ icon }: { icon: JSX.Element }) => {
return (
<span
style={{
@@ -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()}
/>
);
};
+3 -18
View File
@@ -23,20 +23,6 @@
.Island {
padding: 2.5rem;
border: 0;
box-shadow: none;
border-radius: 0;
}
&.animations-disabled {
.Modal__background {
animation: none;
}
.Modal__content {
animation: none;
opacity: 1;
}
}
}
@@ -49,7 +35,7 @@
z-index: 1;
background-color: rgba(#121212, 0.2);
animation: Modal__background__fade-in 0.1s linear forwards;
animation: Modal__background__fade-in 0.125s linear forwards;
}
.Modal__content {
@@ -61,8 +47,7 @@
opacity: 0;
transform: translateY(10px);
animation: Modal__content_fade-in 0.025s ease-out 0s forwards;
animation: Modal__content_fade-in 0.1s ease-out 0.05s forwards;
position: relative;
overflow-y: auto;
@@ -71,7 +56,7 @@
border: 1px solid var(--dialog-border-color);
box-shadow: var(--modal-shadow);
border-radius: 0.75rem;
border-radius: 6px;
box-sizing: border-box;
&:focus {
+1 -8
View File
@@ -5,7 +5,6 @@ import clsx from "clsx";
import { KEYS } from "../keys";
import { AppState } from "../types";
import { useCreatePortalContainer } from "../hooks/useCreatePortalContainer";
import { useRef } from "react";
export const Modal: React.FC<{
className?: string;
@@ -21,10 +20,6 @@ export const Modal: React.FC<{
className: "excalidraw-modal-container",
});
const animationsDisabledRef = useRef(
document.body.classList.contains("excalidraw-animations-disabled"),
);
if (!modalRoot) {
return null;
}
@@ -39,9 +34,7 @@ export const Modal: React.FC<{
return createPortal(
<div
className={clsx("Modal", props.className, {
"animations-disabled": animationsDisabledRef.current,
})}
className={clsx("Modal", props.className)}
role="dialog"
aria-modal="true"
onKeyDown={handleKeydown}
+26 -12
View File
@@ -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();
};
@@ -85,7 +85,7 @@ describe("Sidebar", () => {
});
});
it("should toggle sidebar using excalidrawAPI.toggleSidebar()", async () => {
it("should toggle sidebar using props.toggleMenu()", async () => {
const { container } = await render(
<Excalidraw>
<Sidebar name="customSidebar">
@@ -158,20 +158,6 @@ describe("Sidebar", () => {
const sidebars = container.querySelectorAll(".sidebar");
expect(sidebars.length).toBe(1);
});
// closing sidebar using `{ name: null }`
// -------------------------------------------------------------------------
expect(window.h.app.toggleSidebar({ name: "customSidebar" })).toBe(true);
await waitFor(() => {
const node = container.querySelector("#test-sidebar-content");
expect(node).not.toBe(null);
});
expect(window.h.app.toggleSidebar({ name: null })).toBe(false);
await waitFor(() => {
const node = container.querySelector("#test-sidebar-content");
expect(node).toBe(null);
});
});
});
@@ -343,70 +329,4 @@ describe("Sidebar", () => {
);
});
});
describe("Sidebar.tab", () => {
it("should toggle sidebars tabs correctly", async () => {
const { container } = await render(
<Excalidraw>
<Sidebar name="custom" docked>
<Sidebar.Tabs>
<Sidebar.Tab tab="library">Library</Sidebar.Tab>
<Sidebar.Tab tab="comments">Comments</Sidebar.Tab>
</Sidebar.Tabs>
</Sidebar>
</Excalidraw>,
);
await withExcalidrawDimensions(
{ width: 1920, height: 1080 },
async () => {
expect(
container.querySelector<HTMLElement>(
"[role=tabpanel][data-testid=library]",
),
).toBeNull();
// open library sidebar
expect(
window.h.app.toggleSidebar({ name: "custom", tab: "library" }),
).toBe(true);
expect(
container.querySelector<HTMLElement>(
"[role=tabpanel][data-testid=library]",
),
).not.toBeNull();
// switch to comments tab
expect(
window.h.app.toggleSidebar({ name: "custom", tab: "comments" }),
).toBe(true);
expect(
container.querySelector<HTMLElement>(
"[role=tabpanel][data-testid=comments]",
),
).not.toBeNull();
// toggle sidebar closed
expect(
window.h.app.toggleSidebar({ name: "custom", tab: "comments" }),
).toBe(false);
expect(
container.querySelector<HTMLElement>(
"[role=tabpanel][data-testid=comments]",
),
).toBeNull();
// toggle sidebar open
expect(
window.h.app.toggleSidebar({ name: "custom", tab: "comments" }),
).toBe(true);
expect(
container.querySelector<HTMLElement>(
"[role=tabpanel][data-testid=comments]",
),
).not.toBeNull();
},
);
});
});
});
@@ -10,7 +10,7 @@ export const SidebarTab = ({
children: React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>) => {
return (
<RadixTabs.Content {...rest} value={tab} data-testid={tab}>
<RadixTabs.Content {...rest} value={tab}>
{children}
</RadixTabs.Content>
);
@@ -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
View File
@@ -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 && (
+14 -94
View File
@@ -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);
+91 -137
View File
@@ -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,32 +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?.();
}
};
const option = {
// so that we can stop propagation of the event before it reaches
// event handlers that were bound before this one
capture: true,
};
document.addEventListener(EVENT.KEYDOWN, onKeyDown, option);
return () => {
document.removeEventListener(EVENT.KEYDOWN, onKeyDown, option);
};
}, [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]);
};
+7 -266
View File
@@ -85,7 +85,7 @@ export const PlusPromoIcon = createIcon(
// tabler-icons: book
export const LibraryIcon = createIcon(
<g strokeWidth="1.25">
<g strokeWidth="1.5">
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0" />
<path d="M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0" />
@@ -386,16 +386,6 @@ export const ZoomOutIcon = createIcon(
modifiedTablerIconProps,
);
export const ZoomResetIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M21 21l-6 -6" />
<path d="M3.268 12.043a7.017 7.017 0 0 0 6.634 4.957a7.012 7.012 0 0 0 7.043 -6.131a7 7 0 0 0 -5.314 -7.672a7.021 7.021 0 0 0 -8.241 4.403" />
<path d="M3 4v4h4" />
</g>,
tablerIconProps,
);
export const TrashIcon = createIcon(
<path
strokeWidth="1.25"
@@ -472,16 +462,6 @@ export const HelpIcon = createIcon(
tablerIconProps,
);
export const HelpIconThin = createIcon(
<g strokeWidth="1.25">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<circle cx="12" cy="12" r="9"></circle>
<line x1="12" y1="17" x2="12" y2="17.01"></line>
<path d="M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"></path>
</g>,
tablerIconProps,
);
export const ExternalLinkIcon = createIcon(
<path
strokeWidth="1.25"
@@ -559,16 +539,6 @@ export const palette = createIcon(
"M204.3 5C104.9 24.4 24.8 104.3 5.2 203.4c-37 187 131.7 326.4 258.8 306.7 41.2-6.4 61.4-54.6 42.5-91.7-23.1-45.4 9.9-98.4 60.9-98.4h79.7c35.8 0 64.8-29.6 64.9-65.3C511.5 97.1 368.1-26.9 204.3 5zM96 320c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm32-128c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128-64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128 64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32z",
);
export const bucketFillIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M5 16l1.465 1.638a2 2 0 1 1 -3.015 .099l1.55 -1.737z" />
<path d="M13.737 9.737c2.299 -2.3 3.23 -5.095 2.081 -6.245c-1.15 -1.15 -3.945 -.217 -6.244 2.082c-2.3 2.299 -3.231 5.095 -2.082 6.244c1.15 1.15 3.946 .218 6.245 -2.081z" />
<path d="M7.492 11.818c.362 .362 .768 .676 1.208 .934l6.895 4.047c1.078 .557 2.255 -.075 3.692 -1.512c1.437 -1.437 2.07 -2.614 1.512 -3.692c-.372 -.718 -1.72 -3.017 -4.047 -6.895a6.015 6.015 0 0 0 -.934 -1.208" />
</g>,
tablerIconProps,
);
export const ExportImageIcon = createIcon(
<g strokeWidth="1.25">
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
@@ -634,25 +604,11 @@ 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 },
);
export const exportToPlus = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M8 9h-1a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-8a2 2 0 0 0 -2 -2h-1" />
<path d="M12 14v-11" />
<path d="M9 6l3 -3l3 3" />
</g>,
tablerIconProps,
);
export const shareWindows = createIcon(
<>
<path
@@ -974,6 +930,11 @@ export const CloseIcon = createIcon(
modifiedTablerIconProps,
);
export const back = createIcon(
"M34.52 239.03L228.87 44.69c9.37-9.37 24.57-9.37 33.94 0l22.67 22.67c9.36 9.36 9.37 24.52.04 33.9L131.49 256l154.02 154.75c9.34 9.38 9.32 24.54-.04 33.9l-22.67 22.67c-9.37 9.37-24.57 9.37-33.94 0L34.52 272.97c-9.37-9.37-9.37-24.57 0-33.94z",
{ width: 320, height: 512, style: { marginLeft: "-0.2rem" }, mirror: true },
);
export const clone = createIcon(
"M464 0c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48H176c-26.51 0-48-21.49-48-48V48c0-26.51 21.49-48 48-48h288M176 416c-44.112 0-80-35.888-80-80V128H48c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48h288c26.51 0 48-21.49 48-48v-48H176z",
{ mirror: true },
@@ -1507,19 +1468,6 @@ export const FontSizeExtraLargeIcon = createIcon(
modifiedTablerIconProps,
);
export const fontSizeIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M3 7v-2h13v2" />
<path d="M10 5v14" />
<path d="M12 19h-4" />
<path d="M15 13v-1h6v1" />
<path d="M18 12v7" />
<path d="M17 19h2" />
</g>,
tablerIconProps,
);
export const FontFamilyNormalIcon = createIcon(
<>
<g
@@ -1697,17 +1645,6 @@ export const copyIcon = createIcon(
tablerIconProps,
);
export const cutIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M7 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
<path d="M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0" />
<path d="M9.15 14.85l8.85 -10.85" />
<path d="M6 4l8.85 10.85" />
</g>,
tablerIconProps,
);
export const helpIcon = createIcon(
<>
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
@@ -1832,17 +1769,6 @@ export const MagicIcon = createIcon(
tablerIconProps,
);
export const MagicIconThin = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" />
<path d="M6 21l15 -15l-3 -3l-15 15l3 3" />
<path d="M15 6l3 3" />
<path d="M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
<path d="M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2" />
</g>,
tablerIconProps,
);
export const OpenAIIcon = createIcon(
<g stroke="currentColor" fill="none">
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
@@ -1868,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" />
@@ -1899,19 +1825,6 @@ export const brainIcon = createIcon(
tablerIconProps,
);
export const brainIconThin = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8" />
<path d="M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8" />
<path d="M17.5 16a3.5 3.5 0 0 0 0 -7h-.5" />
<path d="M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0" />
<path d="M6.5 16a3.5 3.5 0 0 1 0 -7h.5" />
<path d="M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10" />
</g>,
tablerIconProps,
);
export const searchIcon = createIcon(
<g strokeWidth={1.5}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
@@ -1920,175 +1833,3 @@ export const searchIcon = createIcon(
</g>,
tablerIconProps,
);
export const clockIcon = createIcon(
<g strokeWidth={1.5}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M20.984 12.53a9 9 0 1 0 -7.552 8.355" />
<path d="M12 7v5l3 3" />
<path d="M19 16l-2 3h4l-2 3" />
</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,
);
export const boltIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M13 3l0 7l6 0l-8 11l0 -7l-6 0l8 -11" />
</g>,
tablerIconProps,
);
export const selectAllIcon = createIcon(
<g>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M8 8m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z" />
<path d="M12 20v.01" />
<path d="M16 20v.01" />
<path d="M8 20v.01" />
<path d="M4 20v.01" />
<path d="M4 16v.01" />
<path d="M4 12v.01" />
<path d="M4 8v.01" />
<path d="M4 4v.01" />
<path d="M8 4v.01" />
<path d="M12 4v.01" />
<path d="M16 4v.01" />
<path d="M20 4v.01" />
<path d="M20 8v.01" />
<path d="M20 12v.01" />
<path d="M20 16v.01" />
<path d="M20 20v.01" />
</g>,
tablerIconProps,
);
export const abacusIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M5 3v18" />
<path d="M19 21v-18" />
<path d="M5 7h14" />
<path d="M5 15h14" />
<path d="M8 13v4" />
<path d="M11 13v4" />
<path d="M16 13v4" />
<path d="M14 5v4" />
<path d="M11 5v4" />
<path d="M8 5v4" />
<path d="M3 21h18" />
</g>,
tablerIconProps,
);
export const flipVertical = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M3 12l18 0" />
<path d="M7 16l10 0l-10 5l0 -5" />
<path d="M7 8l10 0l-10 -5l0 5" />
</g>,
tablerIconProps,
);
export const flipHorizontal = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M12 3l0 18" />
<path d="M16 7l0 10l5 0l-5 -10" />
<path d="M8 7l0 10l-5 0l5 -10" />
</g>,
tablerIconProps,
);
export const paintIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M5 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z" />
<path d="M19 6h1a2 2 0 0 1 2 2a5 5 0 0 1 -5 5l-5 0v2" />
<path d="M10 15m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z" />
</g>,
tablerIconProps,
);
export const zoomAreaIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0" />
<path d="M22 22l-3 -3" />
<path d="M6 18h-1a2 2 0 0 1 -2 -2v-1" />
<path d="M3 11v-1" />
<path d="M3 6v-1a2 2 0 0 1 2 -2h1" />
<path d="M10 3h1" />
<path d="M15 3h1a2 2 0 0 1 2 2v1" />
</g>,
tablerIconProps,
);
export const svgIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
<path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4" />
<path d="M4 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75" />
<path d="M10 15l2 6l2 -6" />
<path d="M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3" />
</g>,
tablerIconProps,
);
export const pngIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M14 3v4a1 1 0 0 0 1 1h4" />
<path d="M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4" />
<path d="M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3" />
<path d="M5 18h1.5a1.5 1.5 0 0 0 0 -3h-1.5v6" />
<path d="M11 21v-6l3 6v-6" />
</g>,
tablerIconProps,
);
export const magnetIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M4 13v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a2 2 0 0 0 6 0v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a8 8 0 0 1 -16 0" />
<path d="M4 8l5 0" />
<path d="M15 8l4 0" />
</g>,
tablerIconProps,
);
export const coffeeIcon = createIcon(
<g strokeWidth={1.25}>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<path d="M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1" />
<path d="M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2" />
<path d="M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2" />
<path d="M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z" />
<path d="M16.746 16.726a3 3 0 1 0 .252 -5.555" />
</g>,
tablerIconProps,
);
@@ -7,7 +7,6 @@ import {
useAppProps,
} from "../App";
import {
boltIcon,
ExportIcon,
ExportImageIcon,
HelpIcon,
@@ -28,6 +27,8 @@ import {
actionShortcuts,
actionToggleTheme,
} from "../../actions";
import "./DefaultItems.scss";
import clsx from "clsx";
import { useSetAtom } from "jotai";
import { activeConfirmDialogAtom } from "../ActiveConfirmDialog";
@@ -36,8 +37,6 @@ import { useUIAppState } from "../../context/ui-appState";
import { openConfirmModal } from "../OverwriteConfirm/OverwriteConfirmState";
import Trans from "../Trans";
import "./DefaultItems.scss";
export const LoadScene = () => {
const { t } = useI18n();
const actionManager = useExcalidrawActionManager();
@@ -118,24 +117,6 @@ export const SaveAsImage = () => {
};
SaveAsImage.displayName = "SaveAsImage";
export const CommandPalette = () => {
const setAppState = useExcalidrawSetAppState();
const { t } = useI18n();
return (
<DropdownMenuItem
icon={boltIcon}
data-testid="command-palette-button"
onSelect={() => setAppState({ openDialog: { name: "commandPalette" } })}
shortcut={getShortcutFromShortcutName("commandPalette")}
aria-label={t("commandPalette.title")}
>
{t("commandPalette.title")}
</DropdownMenuItem>
);
};
CommandPalette.displayName = "CommandPalette";
export const Help = () => {
const { t } = useI18n();
+1 -15
View File
@@ -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,
+17 -13
View File
@@ -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 (
+11
View File
@@ -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()}`
);
};
+7 -16
View File
@@ -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 -3
View File
@@ -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], {
+40 -471
View File
@@ -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]);
};
+8 -2
View File
@@ -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",
});
});
});
+3 -14
View File
@@ -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);
-93
View File
@@ -1,93 +0,0 @@
// taken from lodash (MIT)
// https://github.com/lodash/lodash/blob/67389a8c78975d97505fa15aa79bec6397749807/lodash.js#L14180
const rsComboMarksRange = "\\u0300-\\u036f";
const reComboHalfMarksRange = "\\ufe20-\\ufe2f";
const rsComboSymbolsRange = "\\u20d0-\\u20ff";
const rsComboRange =
rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;
const rsCombo = `[${rsComboRange}]`;
const reComboMark = RegExp(rsCombo, "g");
const reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
// NOTE below letter replacements are modified from lodash to always convert
// to single-letter form by phonetic similarity to keep indexing identical.
// Doing this is only useful for search highlighting, and only insofar
// we use a library that can highlight the original source string using
// the matching indices. As such, we'll likely need to write our own highlighter
// anyway. Ultimately, we'll want to write our own matcher altogether
// so we don't have to do any deburring, which will be the most correct
// solution.
//
// prettier-ignore
const deburredLetters = {
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
// normaly Ae/ae
'\xc6': 'E', '\xe6': 'e',
// normally Th/th
'\xde': 'T', '\xfe': 't',
// normally ss
'\xdf': 's',
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
// normally IJ/ij
'\u0132': 'I', '\u0133': 'i',
// normally OE/oe
'\u0152': 'E', '\u0153': 'e',
// normally "'n"
'\u0149': "n",
'\u017f': 's'
};
export const deburr = (str: string) => {
return str
.replace(reLatin, (key: string) => {
return deburredLetters[key as keyof typeof deburredLetters] || key;
})
.replace(reComboMark, "");
};
@@ -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,4 +1,4 @@
@import "../../css/variables.module.scss";
@import "../css/variables.module.scss";
.excalidraw-hyperlinkContainer {
display: flex;

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