Merge branch 'master' into arnost/scroll-in-read-only-links

This commit is contained in:
Arnost Pleskot 2023-07-31 09:26:14 +02:00 committed by GitHub
commit af6e64ffc2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
171 changed files with 9637 additions and 13847 deletions

View file

@ -1,30 +1,29 @@
import { register } from "./register";
import { getSelectedElements } from "../scene";
import { getNonDeletedElements } from "../element";
import { deepCopyElement } from "../element/newElement";
import { randomId } from "../random";
import { t } from "../i18n";
import { LIBRARY_DISABLED_TYPES } from "../constants";
export const actionAddToLibrary = register({
name: "addToLibrary",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
includeElementsInFrames: true,
},
);
if (selectedElements.some((element) => element.type === "image")) {
return {
commitToHistory: false,
appState: {
...appState,
errorMessage: "Support for adding images to the library coming soon!",
},
};
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
includeElementsInFrames: true,
});
for (const type of LIBRARY_DISABLED_TYPES) {
if (selectedElements.some((element) => element.type === type)) {
return {
commitToHistory: false,
appState: {
...appState,
errorMessage: t(`errors.libraryElementTypeError.${type}`),
},
};
}
}
return app.library

View file

@ -13,19 +13,18 @@ import { ExcalidrawElement } from "../element/types";
import { updateFrameMembershipOfSelectedElements } from "../frame";
import { t } from "../i18n";
import { KEYS } from "../keys";
import { getSelectedElements, isSomeElementSelected } from "../scene";
import { AppState } from "../types";
import { isSomeElementSelected } from "../scene";
import { AppClassProperties, AppState } from "../types";
import { arrayToMap, getShortcutKey } from "../utils";
import { register } from "./register";
const alignActionsPredicate = (
elements: readonly ExcalidrawElement[],
appState: AppState,
_: unknown,
app: AppClassProperties,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const selectedElements = app.scene.getSelectedElements(appState);
return (
selectedElements.length > 1 &&
// TODO enable aligning frames when implemented properly
@ -36,12 +35,10 @@ const alignActionsPredicate = (
const alignSelectedElements = (
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
app: AppClassProperties,
alignment: Alignment,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const selectedElements = app.scene.getSelectedElements(appState);
const updatedElements = alignElements(selectedElements, alignment);
@ -50,6 +47,7 @@ const alignSelectedElements = (
return updateFrameMembershipOfSelectedElements(
elements.map((element) => updatedElementsMap.get(element.id) || element),
appState,
app,
);
};
@ -57,10 +55,10 @@ export const actionAlignTop = register({
name: "alignTop",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "start",
axis: "y",
}),
@ -69,9 +67,9 @@ export const actionAlignTop = register({
},
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_UP,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={AlignTopIcon}
onClick={() => updateData(null)}
@ -88,10 +86,10 @@ export const actionAlignBottom = register({
name: "alignBottom",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "end",
axis: "y",
}),
@ -100,9 +98,9 @@ export const actionAlignBottom = register({
},
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_DOWN,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={AlignBottomIcon}
onClick={() => updateData(null)}
@ -119,10 +117,10 @@ export const actionAlignLeft = register({
name: "alignLeft",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "start",
axis: "x",
}),
@ -131,9 +129,9 @@ export const actionAlignLeft = register({
},
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_LEFT,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={AlignLeftIcon}
onClick={() => updateData(null)}
@ -150,10 +148,10 @@ export const actionAlignRight = register({
name: "alignRight",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "end",
axis: "x",
}),
@ -162,9 +160,9 @@ export const actionAlignRight = register({
},
keyTest: (event) =>
event[KEYS.CTRL_OR_CMD] && event.shiftKey && event.key === KEYS.ARROW_RIGHT,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={AlignRightIcon}
onClick={() => updateData(null)}
@ -181,19 +179,19 @@ export const actionAlignVerticallyCentered = register({
name: "alignVerticallyCentered",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "center",
axis: "y",
}),
commitToHistory: true,
};
},
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={CenterVerticallyIcon}
onClick={() => updateData(null)}
@ -208,19 +206,19 @@ export const actionAlignHorizontallyCentered = register({
name: "alignHorizontallyCentered",
trackEvent: { category: "element" },
predicate: alignActionsPredicate,
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: alignSelectedElements(elements, appState, {
elements: alignSelectedElements(elements, appState, app, {
position: "center",
axis: "x",
}),
commitToHistory: true,
};
},
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!alignActionsPredicate(elements, appState)}
hidden={!alignActionsPredicate(elements, appState, null, app)}
type="button"
icon={CenterHorizontallyIcon}
onClick={() => updateData(null)}

View file

@ -4,7 +4,7 @@ import {
VERTICAL_ALIGN,
TEXT_ALIGN,
} from "../constants";
import { getNonDeletedElements, isTextElement, newElement } from "../element";
import { isTextElement, newElement } from "../element";
import { mutateElement } from "../element/mutateElement";
import {
computeBoundTextPosition,
@ -29,7 +29,6 @@ import {
ExcalidrawTextContainer,
ExcalidrawTextElement,
} from "../element/types";
import { getSelectedElements } from "../scene";
import { AppState } from "../types";
import { Mutable } from "../utility-types";
import { getFontString } from "../utils";
@ -39,16 +38,13 @@ export const actionUnbindText = register({
name: "unbindText",
contextItemLabel: "labels.unbindText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
return selectedElements.some((element) => hasBoundTextElement(element));
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
selectedElements.forEach((element) => {
const boundTextElement = getBoundTextElement(element);
if (boundTextElement) {
@ -93,8 +89,8 @@ export const actionBindText = register({
name: "bindText",
contextItemLabel: "labels.bindText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
if (selectedElements.length === 2) {
const textElement =
@ -117,11 +113,8 @@ export const actionBindText = register({
}
return false;
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
let textElement: ExcalidrawTextElement;
let container: ExcalidrawTextContainer;
@ -201,16 +194,13 @@ export const actionWrapTextInContainer = register({
name: "wrapTextInContainer",
contextItemLabel: "labels.createContainerFromText",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
const areTextElements = selectedElements.every((el) => isTextElement(el));
return selectedElements.length > 0 && areTextElements;
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
let updatedElements: readonly ExcalidrawElement[] = elements.slice();
const containerIds: Mutable<AppState["selectedElementIds"]> = {};

View file

@ -6,7 +6,7 @@ import { getCommonBounds, getNonDeletedElements } from "../element";
import { ExcalidrawElement } from "../element/types";
import { t } from "../i18n";
import { CODES, KEYS } from "../keys";
import { getNormalizedZoom, getSelectedElements } from "../scene";
import { getNormalizedZoom } from "../scene";
import { centerScrollOn } from "../scene/scroll";
import { getStateForZoom } from "../scene/zoom";
import { AppState, NormalizedZoomValue } from "../types";
@ -302,11 +302,8 @@ export const zoomToFit = ({
export const actionZoomToFitSelectionInViewport = register({
name: "zoomToFitSelectionInViewport",
trackEvent: { category: "canvas" },
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
return zoomToFit({
targetElements: selectedElements.length ? selectedElements : elements,
appState,
@ -325,11 +322,8 @@ export const actionZoomToFitSelectionInViewport = register({
export const actionZoomToFitSelection = register({
name: "zoomToFitSelection",
trackEvent: { category: "canvas" },
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
return zoomToFit({
targetElements: selectedElements.length ? selectedElements : elements,
appState,
@ -402,6 +396,7 @@ export const actionToggleEraserTool = register({
...appState,
selectedElementIds: {},
selectedGroupIds: {},
activeEmbeddable: null,
activeTool,
},
commitToHistory: true,
@ -436,6 +431,7 @@ export const actionToggleHandTool = register({
...appState,
selectedElementIds: {},
selectedGroupIds: {},
activeEmbeddable: null,
activeTool,
},
commitToHistory: true,

View file

@ -7,7 +7,6 @@ import {
probablySupportsClipboardWriteText,
} from "../clipboard";
import { actionDeleteSelected } from "./actionDeleteSelected";
import { getSelectedElements } from "../scene/selection";
import { exportCanvas } from "../data/index";
import { getNonDeletedElements, isTextElement } from "../element";
import { t } from "../i18n";
@ -16,7 +15,8 @@ export const actionCopy = register({
name: "copy",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const elementsToCopy = getSelectedElements(elements, appState, {
const elementsToCopy = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
includeElementsInFrames: true,
});
@ -75,14 +75,11 @@ export const actionCopyAsSvg = register({
commitToHistory: false,
};
}
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
includeElementsInFrames: true,
},
);
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
includeElementsInFrames: true,
});
try {
await exportCanvas(
"clipboard-svg",
@ -122,14 +119,11 @@ export const actionCopyAsPng = register({
commitToHistory: false,
};
}
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
includeElementsInFrames: true,
},
);
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
includeElementsInFrames: true,
});
try {
await exportCanvas(
"clipboard",
@ -177,14 +171,11 @@ export const actionCopyAsPng = register({
export const copyText = register({
name: "copyText",
trackEvent: { category: "element" },
perform: (elements, appState) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
},
);
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
});
const text = selectedElements
.reduce((acc: string[], element) => {
@ -199,12 +190,15 @@ export const copyText = register({
commitToHistory: false,
};
},
predicate: (elements, appState) => {
predicate: (elements, appState, _, app) => {
return (
probablySupportsClipboardWriteText &&
getSelectedElements(elements, appState, {
includeBoundTextElement: true,
}).some(isTextElement)
app.scene
.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
})
.some(isTextElement)
);
},
contextItemLabel: "labels.copyText",

View file

@ -158,6 +158,7 @@ export const actionDeleteSelected = register({
...nextAppState,
activeTool: updateActiveTool(appState, { type: "selection" }),
multiElement: null,
activeEmbeddable: null,
},
commitToHistory: isSomeElementSelected(
getNonDeletedElements(elements),

View file

@ -9,19 +9,13 @@ import { ExcalidrawElement } from "../element/types";
import { updateFrameMembershipOfSelectedElements } from "../frame";
import { t } from "../i18n";
import { CODES, KEYS } from "../keys";
import { getSelectedElements, isSomeElementSelected } from "../scene";
import { AppState } from "../types";
import { isSomeElementSelected } from "../scene";
import { AppClassProperties, AppState } from "../types";
import { arrayToMap, getShortcutKey } from "../utils";
import { register } from "./register";
const enableActionGroup = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const enableActionGroup = (appState: AppState, app: AppClassProperties) => {
const selectedElements = app.scene.getSelectedElements(appState);
return (
selectedElements.length > 1 &&
// TODO enable distributing frames when implemented properly
@ -32,12 +26,10 @@ const enableActionGroup = (
const distributeSelectedElements = (
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
app: AppClassProperties,
distribution: Distribution,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const selectedElements = app.scene.getSelectedElements(appState);
const updatedElements = distributeElements(selectedElements, distribution);
@ -46,16 +38,17 @@ const distributeSelectedElements = (
return updateFrameMembershipOfSelectedElements(
elements.map((element) => updatedElementsMap.get(element.id) || element),
appState,
app,
);
};
export const distributeHorizontally = register({
name: "distributeHorizontally",
trackEvent: { category: "element" },
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: distributeSelectedElements(elements, appState, {
elements: distributeSelectedElements(elements, appState, app, {
space: "between",
axis: "x",
}),
@ -64,9 +57,9 @@ export const distributeHorizontally = register({
},
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.H,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!enableActionGroup(elements, appState)}
hidden={!enableActionGroup(appState, app)}
type="button"
icon={DistributeHorizontallyIcon}
onClick={() => updateData(null)}
@ -82,10 +75,10 @@ export const distributeHorizontally = register({
export const distributeVertically = register({
name: "distributeVertically",
trackEvent: { category: "element" },
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
appState,
elements: distributeSelectedElements(elements, appState, {
elements: distributeSelectedElements(elements, appState, app, {
space: "between",
axis: "y",
}),
@ -94,9 +87,9 @@ export const distributeVertically = register({
},
keyTest: (event) =>
!event[KEYS.CTRL_OR_CMD] && event.altKey && event.code === CODES.V,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!enableActionGroup(elements, appState)}
hidden={!enableActionGroup(appState, app)}
type="button"
icon={DistributeVerticallyIcon}
onClick={() => updateData(null)}

View file

@ -275,6 +275,7 @@ const duplicateElements = (
},
getNonDeletedElements(finalElements),
appState,
null,
),
};
};

View file

@ -1,7 +1,6 @@
import { newElementWith } from "../element/mutateElement";
import { ExcalidrawElement } from "../element/types";
import { KEYS } from "../keys";
import { getSelectedElements } from "../scene";
import { arrayToMap } from "../utils";
import { register } from "./register";
@ -11,14 +10,15 @@ const shouldLock = (elements: readonly ExcalidrawElement[]) =>
export const actionToggleElementLock = register({
name: "toggleElementLock",
trackEvent: { category: "element" },
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
return !selectedElements.some(
(element) => element.locked && element.frameId,
);
},
perform: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState, {
perform: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
includeElementsInFrames: true,
});
@ -46,8 +46,9 @@ export const actionToggleElementLock = register({
commitToHistory: true,
};
},
contextItemLabel: (elements, appState) => {
const selected = getSelectedElements(elements, appState, {
contextItemLabel: (elements, appState, app) => {
const selected = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: false,
});
if (selected.length === 1 && selected[0].type !== "frame") {
@ -60,12 +61,13 @@ export const actionToggleElementLock = register({
? "labels.elementLock.lockAll"
: "labels.elementLock.unlockAll";
},
keyTest: (event, appState, elements) => {
keyTest: (event, appState, elements, app) => {
return (
event.key.toLocaleLowerCase() === KEYS.L &&
event[KEYS.CTRL_OR_CMD] &&
event.shiftKey &&
getSelectedElements(elements, appState, {
app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: false,
}).length > 0
);

View file

@ -65,7 +65,7 @@ export const actionChangeExportScale = register({
);
const scaleButtonTitle = `${t(
"buttons.scale",
"imageExportDialog.label.scale",
)} ${s}x (${width}x${height})`;
return (
@ -102,7 +102,7 @@ export const actionChangeExportBackground = register({
checked={appState.exportBackground}
onChange={(checked) => updateData(checked)}
>
{t("labels.withBackground")}
{t("imageExportDialog.label.withBackground")}
</CheckboxItem>
),
});
@ -121,8 +121,8 @@ export const actionChangeExportEmbedScene = register({
checked={appState.exportEmbedScene}
onChange={(checked) => updateData(checked)}
>
{t("labels.exportEmbedScene")}
<Tooltip label={t("labels.exportEmbedScene_details")} long={true}>
{t("imageExportDialog.label.embedScene")}
<Tooltip label={t("imageExportDialog.tooltip.embedScene")} long={true}>
<div className="excalidraw-tooltip-icon">{questionCircle}</div>
</Tooltip>
</CheckboxItem>
@ -277,7 +277,7 @@ export const actionExportWithDarkMode = register({
onChange={(theme: Theme) => {
updateData(theme === THEME.DARK);
}}
title={t("labels.toggleExportColorScheme")}
title={t("imageExportDialog.label.darkMode")}
/>
</div>
),

View file

@ -160,6 +160,7 @@ export const actionFinalize = register({
multiPointElement
? appState.activeTool
: activeTool,
activeEmbeddable: null,
draggingElement: null,
multiElement: null,
editingElement: null,

View file

@ -17,11 +17,12 @@ import { updateFrameMembershipOfSelectedElements } from "../frame";
export const actionFlipHorizontal = register({
name: "flipHorizontal",
trackEvent: { category: "element" },
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
elements: updateFrameMembershipOfSelectedElements(
flipSelectedElements(elements, appState, "horizontal"),
appState,
app,
),
appState,
commitToHistory: true,
@ -34,11 +35,12 @@ export const actionFlipHorizontal = register({
export const actionFlipVertical = register({
name: "flipVertical",
trackEvent: { category: "element" },
perform: (elements, appState) => {
perform: (elements, appState, _, app) => {
return {
elements: updateFrameMembershipOfSelectedElements(
flipSelectedElements(elements, appState, "vertical"),
appState,
app,
),
appState,
commitToHistory: true,

View file

@ -3,19 +3,12 @@ import { ExcalidrawElement } from "../element/types";
import { removeAllElementsFromFrame } from "../frame";
import { getFrameElements } from "../frame";
import { KEYS } from "../keys";
import { getSelectedElements } from "../scene";
import { AppState } from "../types";
import { AppClassProperties, AppState } from "../types";
import { setCursorForShape, updateActiveTool } from "../utils";
import { register } from "./register";
const isSingleFrameSelected = (
elements: readonly ExcalidrawElement[],
appState: AppState,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
);
const isSingleFrameSelected = (appState: AppState, app: AppClassProperties) => {
const selectedElements = app.scene.getSelectedElements(appState);
return selectedElements.length === 1 && selectedElements[0].type === "frame";
};
@ -23,11 +16,8 @@ const isSingleFrameSelected = (
export const actionSelectAllElementsInFrame = register({
name: "selectAllElementsInFrame",
trackEvent: { category: "canvas" },
perform: (elements, appState) => {
const selectedFrame = getSelectedElements(
getNonDeletedElements(elements),
appState,
)[0];
perform: (elements, appState, _, app) => {
const selectedFrame = app.scene.getSelectedElements(appState)[0];
if (selectedFrame && selectedFrame.type === "frame") {
const elementsInFrame = getFrameElements(
@ -55,17 +45,15 @@ export const actionSelectAllElementsInFrame = register({
};
},
contextItemLabel: "labels.selectAllElementsInFrame",
predicate: (elements, appState) => isSingleFrameSelected(elements, appState),
predicate: (elements, appState, _, app) =>
isSingleFrameSelected(appState, app),
});
export const actionRemoveAllElementsFromFrame = register({
name: "removeAllElementsFromFrame",
trackEvent: { category: "history" },
perform: (elements, appState) => {
const selectedFrame = getSelectedElements(
getNonDeletedElements(elements),
appState,
)[0];
perform: (elements, appState, _, app) => {
const selectedFrame = app.scene.getSelectedElements(appState)[0];
if (selectedFrame && selectedFrame.type === "frame") {
return {
@ -87,7 +75,8 @@ export const actionRemoveAllElementsFromFrame = register({
};
},
contextItemLabel: "labels.removeAllElementsFromFrame",
predicate: (elements, appState) => isSingleFrameSelected(elements, appState),
predicate: (elements, appState, _, app) =>
isSingleFrameSelected(appState, app),
});
export const actionupdateFrameRendering = register({

View file

@ -4,7 +4,7 @@ import { arrayToMap, getShortcutKey } from "../utils";
import { register } from "./register";
import { UngroupIcon, GroupIcon } from "../components/icons";
import { newElementWith } from "../element/mutateElement";
import { getSelectedElements, isSomeElementSelected } from "../scene";
import { isSomeElementSelected } from "../scene";
import {
getSelectedGroupIds,
selectGroup,
@ -22,7 +22,7 @@ import {
ExcalidrawFrameElement,
ExcalidrawTextElement,
} from "../element/types";
import { AppState } from "../types";
import { AppClassProperties, AppState } from "../types";
import { isBoundToContainer } from "../element/typeChecks";
import {
getElementsInResizingFrame,
@ -51,14 +51,12 @@ const allElementsInSameGroup = (elements: readonly ExcalidrawElement[]) => {
const enableActionGroup = (
elements: readonly ExcalidrawElement[],
appState: AppState,
app: AppClassProperties,
) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
},
);
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
});
return (
selectedElements.length >= 2 && !allElementsInSameGroup(selectedElements)
);
@ -68,13 +66,10 @@ export const actionGroup = register({
name: "group",
trackEvent: { category: "element" },
perform: (elements, appState, _, app) => {
const selectedElements = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
},
);
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
});
if (selectedElements.length < 2) {
// nothing to group
return { appState, elements, commitToHistory: false };
@ -164,12 +159,13 @@ export const actionGroup = register({
};
},
contextItemLabel: "labels.group",
predicate: (elements, appState) => enableActionGroup(elements, appState),
predicate: (elements, appState, _, app) =>
enableActionGroup(elements, appState, app),
keyTest: (event) =>
!event.shiftKey && event[KEYS.CTRL_OR_CMD] && event.key === KEYS.G,
PanelComponent: ({ elements, appState, updateData }) => (
PanelComponent: ({ elements, appState, updateData, app }) => (
<ToolButton
hidden={!enableActionGroup(elements, appState)}
hidden={!enableActionGroup(elements, appState, app)}
type="button"
icon={<GroupIcon theme={appState.theme} />}
onClick={() => updateData(null)}
@ -191,7 +187,7 @@ export const actionUngroup = register({
let nextElements = [...elements];
const selectedElements = getSelectedElements(nextElements, appState);
const selectedElements = app.scene.getSelectedElements(appState);
const frames = selectedElements
.filter((element) => element.frameId)
.map((element) =>
@ -219,6 +215,7 @@ export const actionUngroup = register({
{ ...appState, selectedGroupIds: {} },
getNonDeletedElements(nextElements),
appState,
null,
);
frames.forEach((frame) => {

View file

@ -1,8 +1,6 @@
import { getNonDeletedElements } from "../element";
import { LinearElementEditor } from "../element/linearElementEditor";
import { isLinearElement } from "../element/typeChecks";
import { ExcalidrawLinearElement } from "../element/types";
import { getSelectedElements } from "../scene";
import { register } from "./register";
export const actionToggleLinearEditor = register({
@ -10,21 +8,18 @@ export const actionToggleLinearEditor = register({
trackEvent: {
category: "element",
},
predicate: (elements, appState) => {
const selectedElements = getSelectedElements(elements, appState);
predicate: (elements, appState, _, app) => {
const selectedElements = app.scene.getSelectedElements(appState);
if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
return true;
}
return false;
},
perform(elements, appState, _, app) {
const selectedElement = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
},
)[0] as ExcalidrawLinearElement;
const selectedElement = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
includeBoundTextElement: true,
})[0] as ExcalidrawLinearElement;
const editingLinearElement =
appState.editingLinearElement?.elementId === selectedElement.id
@ -38,14 +33,11 @@ export const actionToggleLinearEditor = register({
commitToHistory: false,
};
},
contextItemLabel: (elements, appState) => {
const selectedElement = getSelectedElements(
getNonDeletedElements(elements),
appState,
{
includeBoundTextElement: true,
},
)[0] as ExcalidrawLinearElement;
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";

View file

@ -42,6 +42,7 @@ export const actionSelectAll = register({
},
getNonDeletedElements(elements),
appState,
app,
),
commitToHistory: true,
};

View file

@ -90,6 +90,7 @@ export class ActionManager {
event,
this.getAppState(),
this.getElementsIncludingDeleted(),
this.app,
),
);
@ -168,6 +169,7 @@ export class ActionManager {
appState={this.getAppState()}
updateData={updateData}
appProps={this.app.props}
app={this.app}
data={data}
/>
);

View file

@ -121,6 +121,7 @@ export type ActionName =
| "removeAllElementsFromFrame"
| "updateFrameRendering"
| "setFrameAsActiveTool"
| "setEmbeddableAsActiveTool"
| "createContainerFromText"
| "wrapTextInContainer";
@ -130,6 +131,7 @@ export type PanelComponentProps = {
updateData: (formData?: any) => void;
appProps: ExcalidrawProps;
data?: Record<string, any>;
app: AppClassProperties;
};
export interface Action {
@ -141,12 +143,14 @@ export interface Action {
event: React.KeyboardEvent | KeyboardEvent,
appState: AppState,
elements: readonly ExcalidrawElement[],
app: AppClassProperties,
) => boolean;
contextItemLabel?:
| string
| ((
elements: readonly ExcalidrawElement[],
appState: Readonly<AppState>,
app: AppClassProperties,
) => string);
predicate?: (
elements: readonly ExcalidrawElement[],

View file

@ -11,7 +11,7 @@ export const trackEvent = (
// Uncomment the next line to track locally
// console.log("Track Event", { category, action, label, value });
if (typeof window === "undefined" || process.env.JEST_WORKER_ID) {
if (typeof window === "undefined" || import.meta.env.VITE_WORKER_ID) {
return;
}

View file

@ -38,6 +38,7 @@ export const getDefaultAppState = (): Omit<
currentItemStrokeWidth: DEFAULT_ELEMENT_PROPS.strokeWidth,
currentItemTextAlign: DEFAULT_TEXT_ALIGN,
cursorButton: "up",
activeEmbeddable: null,
draggingElement: null,
editingElement: null,
editingGroupId: null,
@ -139,6 +140,7 @@ const APP_STATE_STORAGE_CONF = (<
currentItemStrokeWidth: { browser: true, export: false, server: false },
currentItemTextAlign: { browser: true, export: false, server: false },
cursorButton: { browser: true, export: false, server: false },
activeEmbeddable: { browser: false, export: false, server: false },
draggingElement: { browser: false, export: false, server: false },
editingElement: { browser: false, export: false, server: false },
editingGroupId: { browser: true, export: false, server: false },

View file

@ -6,7 +6,6 @@ import {
import {
DEFAULT_FONT_FAMILY,
DEFAULT_FONT_SIZE,
ENV,
VERTICAL_ALIGN,
} from "./constants";
import { newElement, newLinearElement, newTextElement } from "./element";
@ -384,7 +383,7 @@ const chartTypeBar = (
y,
groupId,
backgroundColor,
process.env.NODE_ENV === ENV.DEVELOPMENT,
import.meta.env.DEV,
),
];
};
@ -473,7 +472,7 @@ const chartTypeLine = (
y,
groupId,
backgroundColor,
process.env.NODE_ENV === ENV.DEVELOPMENT,
import.meta.env.DEV,
),
line,
...lines,

View file

@ -21,7 +21,7 @@ export type ColorPickerColor =
export type ColorTuple = readonly [string, string, string, string, string];
export type ColorPalette = Merge<
Record<ColorPickerColor, ColorTuple>,
{ black: string; white: string; transparent: string }
{ black: "#1e1e1e"; white: "#ffffff"; transparent: "transparent" }
>;
// used general type instead of specific type (ColorPalette) to support custom colors

View file

@ -36,7 +36,7 @@ import {
import "./Actions.scss";
import DropdownMenu from "./dropdownMenu/DropdownMenu";
import { extraToolsIcon, frameToolIcon } from "./icons";
import { EmbedIcon, extraToolsIcon, frameToolIcon } from "./icons";
import { KEYS } from "../keys";
export const SelectedShapeActions = ({
@ -266,6 +266,7 @@ export const ShapesSwitcher = ({
});
setAppState({
activeTool: nextActiveTool,
activeEmbeddable: null,
multiElement: null,
selectedElementIds: {},
});
@ -283,39 +284,72 @@ export const ShapesSwitcher = ({
<div className="App-toolbar__divider" />
{/* TEMP HACK because dropdown doesn't work well inside mobile toolbar */}
{device.isMobile ? (
<ToolButton
className={clsx("Shape", { fillable: false })}
type="radio"
icon={frameToolIcon}
checked={activeTool.type === "frame"}
name="editor-current-shape"
title={`${capitalizeString(
t("toolBar.frame"),
)} ${KEYS.F.toLocaleUpperCase()}`}
keyBindingLabel={KEYS.F.toLocaleUpperCase()}
aria-label={capitalizeString(t("toolBar.frame"))}
aria-keyshortcuts={KEYS.F.toLocaleUpperCase()}
data-testid={`toolbar-frame`}
onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") {
setAppState({
penDetected: true,
penMode: true,
<>
<ToolButton
className={clsx("Shape", { fillable: false })}
type="radio"
icon={frameToolIcon}
checked={activeTool.type === "frame"}
name="editor-current-shape"
title={`${capitalizeString(
t("toolBar.frame"),
)} ${KEYS.F.toLocaleUpperCase()}`}
keyBindingLabel={KEYS.F.toLocaleUpperCase()}
aria-label={capitalizeString(t("toolBar.frame"))}
aria-keyshortcuts={KEYS.F.toLocaleUpperCase()}
data-testid={`toolbar-frame`}
onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") {
setAppState({
penDetected: true,
penMode: true,
});
}
}}
onChange={({ pointerType }) => {
trackEvent("toolbar", "frame", "ui");
const nextActiveTool = updateActiveTool(appState, {
type: "frame",
});
}
}}
onChange={({ pointerType }) => {
trackEvent("toolbar", "frame", "ui");
const nextActiveTool = updateActiveTool(appState, {
type: "frame",
});
setAppState({
activeTool: nextActiveTool,
multiElement: null,
selectedElementIds: {},
});
}}
/>
setAppState({
activeTool: nextActiveTool,
multiElement: null,
selectedElementIds: {},
activeEmbeddable: null,
});
}}
/>
<ToolButton
className={clsx("Shape", { fillable: false })}
type="radio"
icon={EmbedIcon}
checked={activeTool.type === "embeddable"}
name="editor-current-shape"
title={capitalizeString(t("toolBar.embeddable"))}
aria-label={capitalizeString(t("toolBar.embeddable"))}
data-testid={`toolbar-embeddable`}
onPointerDown={({ pointerType }) => {
if (!appState.penDetected && pointerType === "pen") {
setAppState({
penDetected: true,
penMode: true,
});
}
}}
onChange={({ pointerType }) => {
trackEvent("toolbar", "embeddable", "ui");
const nextActiveTool = updateActiveTool(appState, {
type: "embeddable",
});
setAppState({
activeTool: nextActiveTool,
multiElement: null,
selectedElementIds: {},
activeEmbeddable: null,
});
}}
/>
</>
) : (
<DropdownMenu open={isExtraToolsMenuOpen}>
<DropdownMenu.Trigger
@ -347,6 +381,22 @@ export const ShapesSwitcher = ({
>
{t("toolBar.frame")}
</DropdownMenu.Item>
<DropdownMenu.Item
onSelect={() => {
const nextActiveTool = updateActiveTool(appState, {
type: "embeddable",
});
setAppState({
activeTool: nextActiveTool,
multiElement: null,
selectedElementIds: {},
});
}}
icon={EmbedIcon}
data-testid="toolbar-embeddable"
>
{t("toolBar.embeddable")}
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu>
)}

View file

@ -4,8 +4,9 @@ import { reseed } from "../random";
import { render, queryByTestId } from "../tests/test-utils";
import ExcalidrawApp from "../excalidraw-app";
import { vi } from "vitest";
const renderScene = jest.spyOn(Renderer, "renderScene");
const renderScene = vi.spyOn(Renderer, "renderScene");
describe("Test <App/>", () => {
beforeEach(async () => {

File diff suppressed because it is too large Load diff

View file

@ -8,7 +8,7 @@ import {
} from "./colorPickerUtils";
import HotkeyLabel from "./HotkeyLabel";
import { ColorPaletteCustom } from "../../colors";
import { t } from "../../i18n";
import { TranslationKeys, t } from "../../i18n";
interface PickerColorListProps {
palette: ColorPaletteCustom;
@ -48,7 +48,11 @@ const PickerColorList = ({
(Array.isArray(value) ? value[activeShade] : value) || "transparent";
const keybinding = colorPickerHotkeyBindings[index];
const label = t(`colors.${key.replace(/\d+/, "")}`, null, "");
const label = t(
`colors.${key.replace(/\d+/, "")}` as unknown as TranslationKeys,
null,
"",
);
return (
<button

View file

@ -1,6 +1,6 @@
import clsx from "clsx";
import { Popover } from "./Popover";
import { t } from "../i18n";
import { t, TranslationKeys } from "../i18n";
import "./ContextMenu.scss";
import {
@ -82,9 +82,15 @@ export const ContextMenu = React.memo(
let label = "";
if (item.contextItemLabel) {
if (typeof item.contextItemLabel === "function") {
label = t(item.contextItemLabel(elements, appState));
label = t(
item.contextItemLabel(
elements,
appState,
actionManager.app,
) as unknown as TranslationKeys,
);
} else {
label = t(item.contextItemLabel);
label = t(item.contextItemLabel as unknown as TranslationKeys);
}
}

View file

@ -58,7 +58,7 @@ export const EyeDropper: React.FC<{
return;
}
let currentColor = COLOR_PALETTE.black;
let currentColor: string = COLOR_PALETTE.black;
let isHoldingPointerDown = false;
const ctx = app.canvas.getContext("2d")!;

View file

@ -1,7 +1,5 @@
import { t } from "../i18n";
import { NonDeletedExcalidrawElement } from "../element/types";
import { getSelectedElements } from "../scene";
import { Device, UIAppState } from "../types";
import { AppClassProperties, Device, UIAppState } from "../types";
import {
isImageElement,
isLinearElement,
@ -15,17 +13,12 @@ import "./HintViewer.scss";
interface HintViewerProps {
appState: UIAppState;
elements: readonly NonDeletedExcalidrawElement[];
isMobile: boolean;
device: Device;
app: AppClassProperties;
}
const getHints = ({
appState,
elements,
isMobile,
device,
}: HintViewerProps) => {
const getHints = ({ appState, isMobile, device, app }: HintViewerProps) => {
const { activeTool, isResizing, isRotating, lastPointerDownWith } = appState;
const multiMode = appState.multiElement !== null;
@ -51,11 +44,15 @@ const getHints = ({
return t("hints.text");
}
if (activeTool.type === "embeddable") {
return t("hints.embeddable");
}
if (appState.activeTool.type === "image" && appState.pendingImageElementId) {
return t("hints.placeImage");
}
const selectedElements = getSelectedElements(elements, appState);
const selectedElements = app.scene.getSelectedElements(appState);
if (
isResizing &&
@ -115,15 +112,15 @@ const getHints = ({
export const HintViewer = ({
appState,
elements,
isMobile,
device,
app,
}: HintViewerProps) => {
let hint = getHints({
appState,
elements,
isMobile,
device,
app,
});
if (!hint) {
return null;

View file

@ -72,6 +72,7 @@ interface LayerUIProps {
onExportImage: AppClassProperties["onExportImage"];
renderWelcomeScreen: boolean;
children?: React.ReactNode;
app: AppClassProperties;
}
const DefaultMainMenu: React.FC<{
@ -127,6 +128,7 @@ const LayerUI = ({
onExportImage,
renderWelcomeScreen,
children,
app,
}: LayerUIProps) => {
const device = useDevice();
const tunnels = useInitializeTunnels();
@ -240,9 +242,9 @@ const LayerUI = ({
>
<HintViewer
appState={appState}
elements={elements}
isMobile={device.isMobile}
device={device}
app={app}
/>
{heading}
<Stack.Row gap={1}>
@ -401,6 +403,7 @@ const LayerUI = ({
)}
{device.isMobile && (
<MobileMenu
app={app}
appState={appState}
elements={elements}
actionManager={actionManager}

View file

@ -29,6 +29,7 @@ import "./LibraryMenu.scss";
import { LibraryMenuControlButtons } from "./LibraryMenuControlButtons";
import { isShallowEqual } from "../utils";
import { NonDeletedExcalidrawElement } from "../element/types";
import { LIBRARY_DISABLED_TYPES } from "../constants";
export const isLibraryMenuOpenAtom = atom(false);
@ -68,11 +69,12 @@ export const LibraryMenuContent = ({
libraryItems: LibraryItems,
) => {
trackEvent("element", "addToLibrary", "ui");
if (processedElements.some((element) => element.type === "image")) {
return setAppState({
errorMessage:
"Support for adding images to the library coming soon!",
});
for (const type of LIBRARY_DISABLED_TYPES) {
if (processedElements.some((element) => element.type === type)) {
return setAppState({
errorMessage: t(`errors.libraryElementTypeError.${type}`),
});
}
}
const nextItems: LibraryItems = [
{
@ -197,6 +199,7 @@ export const LibraryMenu = () => {
setAppState({
selectedElementIds: {},
selectedGroupIds: {},
activeEmbeddable: null,
});
}, [setAppState]);

View file

@ -16,7 +16,7 @@ const LibraryMenuBrowseButton = ({
return (
<a
className="library-menu-browse-button"
href={`${process.env.REACT_APP_LIBRARY_URL}?target=${
href={`${import.meta.env.VITE_APP_LIBRARY_URL}?target=${
window.name || "_blank"
}&referrer=${referrer}&useHash=true&token=${id}&theme=${theme}&version=${
VERSIONS.excalidrawLibrary

View file

@ -12,6 +12,11 @@
box-sizing: border-box;
border-radius: var(--border-radius-lg);
svg {
// to prevent clicks on links and such
pointer-events: none;
}
&--hover {
border-color: var(--color-primary);
}

View file

@ -1,5 +1,11 @@
import React from "react";
import { AppState, Device, ExcalidrawProps, UIAppState } from "../types";
import {
AppClassProperties,
AppState,
Device,
ExcalidrawProps,
UIAppState,
} from "../types";
import { ActionManager } from "../actions/manager";
import { t } from "../i18n";
import Stack from "./Stack";
@ -41,6 +47,7 @@ type MobileMenuProps = {
renderSidebars: () => JSX.Element | null;
device: Device;
renderWelcomeScreen: boolean;
app: AppClassProperties;
};
export const MobileMenu = ({
@ -58,6 +65,7 @@ export const MobileMenu = ({
renderSidebars,
device,
renderWelcomeScreen,
app,
}: MobileMenuProps) => {
const {
WelcomeScreenCenterTunnel,
@ -119,9 +127,9 @@ export const MobileMenu = ({
</Section>
<HintViewer
appState={appState}
elements={elements}
isMobile={true}
device={device}
app={app}
/>
</FixedSideContainer>
);

View file

@ -319,7 +319,7 @@ const PublishLibrary = ({
formData.append("twitterHandle", libraryData.twitterHandle);
formData.append("website", libraryData.website);
fetch(`${process.env.REACT_APP_LIBRARY_BACKEND}/submit`, {
fetch(`${import.meta.env.VITE_APP_LIBRARY_BACKEND}/submit`, {
method: "post",
body: formData,
})

View file

@ -3,7 +3,7 @@ import { t } from "../i18n";
import { useExcalidrawContainer } from "./App";
export const Section: React.FC<{
heading: string;
heading: "canvasActions" | "selectedShapeActions" | "shapes";
children?: React.ReactNode | ((heading: React.ReactNode) => React.ReactNode);
className?: string;
}> = ({ heading, children, ...props }) => {

View file

@ -10,6 +10,7 @@ import {
waitFor,
withExcalidrawDimensions,
} from "../../tests/test-utils";
import { vi } from "vitest";
export const assertSidebarDockButton = async <T extends boolean>(
hasDockButton: T,
@ -205,7 +206,7 @@ describe("Sidebar", () => {
});
it("<Sidebar.Header> should render close button", async () => {
const onStateChange = jest.fn();
const onStateChange = vi.fn();
const CustomExcalidraw = () => {
return (
<Excalidraw

View file

@ -53,7 +53,7 @@ export const SidebarInner = forwardRef(
}: SidebarProps & Omit<React.RefAttributes<HTMLDivElement>, "onSelect">,
ref: React.ForwardedRef<HTMLDivElement>,
) => {
if (process.env.NODE_ENV === "development" && onDock && docked == null) {
if (import.meta.env.DEV && onDock && docked == null) {
console.warn(
"Sidebar: `docked` must be set when `onDock` is supplied for the sidebar to be user-dockable. To hide this message, either pass `docked` or remove `onDock`",
);

View file

@ -3,6 +3,7 @@ import { render } from "@testing-library/react";
import fallbackLangData from "../locales/en.json";
import Trans from "./Trans";
import { TranslationKeys } from "../i18n";
describe("Test <Trans/>", () => {
it("should translate the the strings correctly", () => {
@ -18,24 +19,27 @@ describe("Test <Trans/>", () => {
const { getByTestId } = render(
<>
<div data-testid="test1">
<Trans i18nKey="transTest.key1" audience="world" />
<Trans
i18nKey={"transTest.key1" as unknown as TranslationKeys}
audience="world"
/>
</div>
<div data-testid="test2">
<Trans
i18nKey="transTest.key2"
i18nKey={"transTest.key2" as unknown as TranslationKeys}
link={(el) => <a href="https://example.com">{el}</a>}
/>
</div>
<div data-testid="test3">
<Trans
i18nKey="transTest.key3"
i18nKey={"transTest.key3" as unknown as TranslationKeys}
link={(el) => <a href="https://example.com">{el}</a>}
location="the button"
/>
</div>
<div data-testid="test4">
<Trans
i18nKey="transTest.key4"
i18nKey={"transTest.key4" as unknown as TranslationKeys}
link={(el) => <a href="https://example.com">{el}</a>}
location="the button"
bold={(el) => <strong>{el}</strong>}
@ -43,7 +47,7 @@ describe("Test <Trans/>", () => {
</div>
<div data-testid="test5">
<Trans
i18nKey="transTest.key5"
i18nKey={"transTest.key5" as unknown as TranslationKeys}
connect-link={(el) => <a href="https://example.com">{el}</a>}
/>
</div>

View file

@ -1,6 +1,6 @@
import React from "react";
import { useI18n } from "../i18n";
import { TranslationKeys, useI18n } from "../i18n";
// Used for splitting i18nKey into tokens in Trans component
// Example:
@ -153,7 +153,7 @@ const Trans = ({
children,
...props
}: {
i18nKey: string;
i18nKey: TranslationKeys;
[key: string]: React.ReactNode | ((el: React.ReactNode) => React.ReactNode);
}) => {
const { t } = useI18n();

View file

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Test <App/> should show error modal when using brave and measureText API is not working 1`] = `
exports[`Test <App/> > should show error modal when using brave and measureText API is not working 1`] = `
<div
data-testid="brave-measure-text-error"
>

View file

@ -396,6 +396,14 @@ export const TrashIcon = createIcon(
modifiedTablerIconProps,
);
export const EmbedIcon = createIcon(
<g strokeWidth="1.25">
<polyline points="12 16 18 10 12 4" />
<polyline points="8 4 2 10 8 16" />
</g>,
modifiedTablerIconProps,
);
export const DuplicateIcon = createIcon(
<g strokeWidth="1.25">
<path d="M14.375 6.458H8.958a2.5 2.5 0 0 0-2.5 2.5v5.417a2.5 2.5 0 0 0 2.5 2.5h5.417a2.5 2.5 0 0 0 2.5-2.5V8.958a2.5 2.5 0 0 0-2.5-2.5Z" />

View file

@ -4,6 +4,7 @@ import {
useExcalidrawSetAppState,
useExcalidrawActionManager,
useExcalidrawElements,
useAppProps,
} from "../App";
import {
ExportIcon,
@ -198,13 +199,20 @@ export const ChangeCanvasBackground = () => {
const { t } = useI18n();
const appState = useUIAppState();
const actionManager = useExcalidrawActionManager();
const appProps = useAppProps();
if (appState.viewModeEnabled) {
if (
appState.viewModeEnabled ||
!appProps.UIOptions.canvasActions.changeViewBackgroundColor
) {
return null;
}
return (
<div style={{ marginTop: "0.5rem" }}>
<div style={{ fontSize: ".75rem", marginBottom: ".5rem" }}>
<div
data-testid="canvas-background-label"
style={{ fontSize: ".75rem", marginBottom: ".5rem" }}
>
{t("labels.canvasBackground")}
</div>
<div style={{ padding: "0 0.625rem" }}>

View file

@ -71,8 +71,18 @@ export enum EVENT {
// custom events
EXCALIDRAW_LINK = "excalidraw-link",
MENU_ITEM_SELECT = "menu.itemSelect",
MESSAGE = "message",
}
export const YOUTUBE_STATES = {
UNSTARTED: -1,
ENDED: 0,
PLAYING: 1,
PAUSED: 2,
BUFFERING: 3,
CUED: 5,
} as const;
export const ENV = {
TEST: "test",
DEVELOPMENT: "development",
@ -92,7 +102,7 @@ export const FONT_FAMILY = {
export const THEME = {
LIGHT: "light",
DARK: "dark",
};
} as const;
export const FRAME_STYLE = {
strokeColor: "#bbb" as ExcalidrawElement["strokeColor"],
@ -300,3 +310,5 @@ export const DEFAULT_SIDEBAR = {
name: "default",
defaultTab: LIBRARY_SIDEBAR_TAB,
} as const;
export const LIBRARY_DISABLED_TYPES = new Set(["embeddable", "image"] as const);

View file

@ -77,6 +77,19 @@
position: absolute;
}
&__embeddable {
width: 100%;
height: 100%;
border: 0;
}
&__embeddable-container {
position: absolute;
z-index: 2;
transform-origin: top left;
pointer-events: none;
}
&.theme--dark {
// The percentage is inspired by
// https://material.io/design/color/dark-theme.html#properties, which
@ -661,3 +674,33 @@
}
}
}
.excalidraw__embeddable-container {
.excalidraw__embeddable-container__inner {
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
border-radius: var(--embeddable-radius);
}
.excalidraw__embeddable__outer {
width: 100%;
height: 100%;
& > * {
border-radius: var(--embeddable-radius);
}
}
.excalidraw__embeddable-hint {
position: absolute;
z-index: 1;
background: rgba(0, 0, 0, 0.5);
padding: 1rem 1.6rem;
border-radius: 12px;
color: #fff;
font-weight: bold;
letter-spacing: 0.6px;
font-family: "Assistant";
}
}

View file

@ -3,6 +3,7 @@ import {
ExcalidrawSelectionElement,
ExcalidrawTextElement,
FontFamilyValues,
PointBinding,
StrokeRoundness,
} from "../element/types";
import {
@ -64,6 +65,7 @@ export const AllowedExcalidrawActiveTools: Record<
eraser: false,
custom: true,
frame: true,
embeddable: true,
hand: true,
};
@ -82,6 +84,13 @@ const getFontFamilyByName = (fontFamilyName: string): FontFamilyValues => {
return DEFAULT_FONT_FAMILY;
};
const repairBinding = (binding: PointBinding | null) => {
if (!binding) {
return null;
}
return { ...binding, focus: binding.focus || 0 };
};
const restoreElementWithProperties = <
T extends Required<Omit<ExcalidrawElement, "customData">> & {
customData?: ExcalidrawElement["customData"];
@ -257,8 +266,8 @@ const restoreElement = (
(element.type as ExcalidrawElement["type"] | "draw") === "draw"
? "line"
: element.type,
startBinding: element.startBinding,
endBinding: element.endBinding,
startBinding: repairBinding(element.startBinding),
endBinding: repairBinding(element.endBinding),
lastCommittedPoint: null,
startArrowhead,
endArrowhead,
@ -275,6 +284,10 @@ const restoreElement = (
return restoreElementWithProperties(element, {});
case "diamond":
return restoreElementWithProperties(element, {});
case "embeddable":
return restoreElementWithProperties(element, {
validated: undefined,
});
case "frame":
return restoreElementWithProperties(element, {
name: element.name ?? null,

View file

@ -1,9 +1,35 @@
import { sanitizeUrl } from "@braintree/sanitize-url";
export const normalizeLink = (link: string) => {
link = link.trim();
if (!link) {
return link;
}
return sanitizeUrl(link);
};
export const isLocalLink = (link: string | null) => {
return !!(link?.includes(location.origin) || link?.startsWith("/"));
};
/**
* Returns URL sanitized and safe for usage in places such as
* iframe's src attribute or <a> href attributes.
*/
export const toValidURL = (link: string) => {
link = normalizeLink(link);
// make relative links into fully-qualified urls
if (link.startsWith("/")) {
return `${location.origin}${link}`;
}
try {
new URL(link);
} catch {
// if link does not parse as URL, assume invalid and return blank page
return "about:blank";
}
return link;
};

View file

@ -55,10 +55,6 @@
}
}
.d-none {
display: none;
}
&--remove .ToolIcon__icon svg {
color: $oc-red-6;
}

View file

@ -5,8 +5,12 @@ import {
viewportCoordsToSceneCoords,
wrapEvent,
} from "../utils";
import { getEmbedLink, embeddableURLValidator } from "./embeddable";
import { mutateElement } from "./mutateElement";
import { NonDeletedExcalidrawElement } from "./types";
import {
ExcalidrawEmbeddableElement,
NonDeletedExcalidrawElement,
} from "./types";
import { register } from "../actions/register";
import { ToolButton } from "../components/ToolButton";
@ -21,7 +25,10 @@ import {
} from "react";
import clsx from "clsx";
import { KEYS } from "../keys";
import { DEFAULT_LINK_SIZE } from "../renderer/renderElement";
import {
DEFAULT_LINK_SIZE,
invalidateShapeForElement,
} from "../renderer/renderElement";
import { rotate } from "../math";
import { EVENT, HYPERLINK_TOOLTIP_DELAY, MIME_TYPES } from "../constants";
import { Bounds } from "./bounds";
@ -33,7 +40,8 @@ import { isLocalLink, normalizeLink } from "../data/url";
import "./Hyperlink.scss";
import { trackEvent } from "../analytics";
import { useExcalidrawAppState } from "../components/App";
import { useAppProps, useExcalidrawAppState } from "../components/App";
import { isEmbeddableElement } from "./typeChecks";
const CONTAINER_WIDTH = 320;
const SPACE_BOTTOM = 85;
@ -48,37 +56,112 @@ EXTERNAL_LINK_IMG.src = `data:${MIME_TYPES.svg}, ${encodeURIComponent(
let IS_HYPERLINK_TOOLTIP_VISIBLE = false;
const embeddableLinkCache = new Map<
ExcalidrawEmbeddableElement["id"],
string
>();
export const Hyperlink = ({
element,
setAppState,
onLinkOpen,
setToast,
}: {
element: NonDeletedExcalidrawElement;
setAppState: React.Component<any, AppState>["setState"];
onLinkOpen: ExcalidrawProps["onLinkOpen"];
setToast: (
toast: { message: string; closable?: boolean; duration?: number } | null,
) => void;
}) => {
const appState = useExcalidrawAppState();
const appProps = useAppProps();
const linkVal = element.link || "";
const [inputVal, setInputVal] = useState(linkVal);
const inputRef = useRef<HTMLInputElement>(null);
const isEditing = appState.showHyperlinkPopup === "editor" || !linkVal;
const isEditing = appState.showHyperlinkPopup === "editor";
const handleSubmit = useCallback(() => {
if (!inputRef.current) {
return;
}
const link = normalizeLink(inputRef.current.value);
const link = normalizeLink(inputRef.current.value) || null;
if (!element.link && link) {
trackEvent("hyperlink", "create");
}
mutateElement(element, { link });
setAppState({ showHyperlinkPopup: "info" });
}, [element, setAppState]);
if (isEmbeddableElement(element)) {
if (appState.activeEmbeddable?.element === element) {
setAppState({ activeEmbeddable: null });
}
if (!link) {
mutateElement(element, {
validated: false,
link: null,
});
return;
}
if (!embeddableURLValidator(link, appProps.validateEmbeddable)) {
if (link) {
setToast({ message: t("toast.unableToEmbed"), closable: true });
}
element.link && embeddableLinkCache.set(element.id, element.link);
mutateElement(element, {
validated: false,
link,
});
invalidateShapeForElement(element);
} else {
const { width, height } = element;
const embedLink = getEmbedLink(link);
if (embedLink?.warning) {
setToast({ message: embedLink.warning, closable: true });
}
const ar = embedLink
? embedLink.aspectRatio.w / embedLink.aspectRatio.h
: 1;
const hasLinkChanged =
embeddableLinkCache.get(element.id) !== element.link;
mutateElement(element, {
...(hasLinkChanged
? {
width:
embedLink?.type === "video"
? width > height
? width
: height * ar
: width,
height:
embedLink?.type === "video"
? width > height
? width / ar
: height
: height,
}
: {}),
validated: true,
link,
});
invalidateShapeForElement(element);
if (embeddableLinkCache.has(element.id)) {
embeddableLinkCache.delete(element.id);
}
}
} else {
mutateElement(element, { link });
}
}, [
element,
setToast,
appProps.validateEmbeddable,
appState.activeEmbeddable,
setAppState,
]);
useLayoutEffect(() => {
return () => {
@ -132,10 +215,12 @@ export const Hyperlink = ({
appState.draggingElement ||
appState.resizingElement ||
appState.isRotating ||
appState.openMenu
appState.openMenu ||
appState.viewModeEnabled
) {
return null;
}
return (
<div
className="excalidraw-hyperlinkContainer"
@ -145,6 +230,11 @@ export const Hyperlink = ({
width: CONTAINER_WIDTH,
padding: CONTAINER_PADDING,
}}
onClick={() => {
if (!element.link && !isEditing) {
setAppState({ showHyperlinkPopup: "editor" });
}
}}
>
{isEditing ? (
<input
@ -162,15 +252,14 @@ export const Hyperlink = ({
}
if (event.key === KEYS.ENTER || event.key === KEYS.ESCAPE) {
handleSubmit();
setAppState({ showHyperlinkPopup: "info" });
}
}}
/>
) : (
) : element.link ? (
<a
href={normalizeLink(element.link || "")}
className={clsx("excalidraw-hyperlinkContainer-link", {
"d-none": isEditing,
})}
className="excalidraw-hyperlinkContainer-link"
target={isLocalLink(element.link) ? "_self" : "_blank"}
onClick={(event) => {
if (element.link && onLinkOpen) {
@ -194,6 +283,10 @@ export const Hyperlink = ({
>
{element.link}
</a>
) : (
<div className="excalidraw-hyperlinkContainer-link">
{t("labels.link.empty")}
</div>
)}
<div className="excalidraw-hyperlinkContainer__buttons">
{!isEditing && (
@ -207,8 +300,7 @@ export const Hyperlink = ({
icon={FreedrawIcon}
/>
)}
{linkVal && (
{linkVal && !isEmbeddableElement(element) && (
<ToolButton
type="button"
title={t("buttons.remove")}
@ -271,7 +363,11 @@ export const actionLink = register({
type="button"
icon={LinkIcon}
aria-label={t(getContextMenuLabel(elements, appState))}
title={`${t("labels.link.label")} - ${getShortcutKey("CtrlOrCmd+K")}`}
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}
/>
@ -285,7 +381,11 @@ export const getContextMenuLabel = (
) => {
const selectedElements = getSelectedElements(elements, appState);
const label = selectedElements[0]!.link
? "labels.link.edit"
? isEmbeddableElement(selectedElements[0])
? "labels.link.editEmbed"
: "labels.link.edit"
: isEmbeddableElement(selectedElements[0])
? "labels.link.createEmbed"
: "labels.link.create";
return label;
};
@ -327,6 +427,26 @@ export const isPointHittingLinkIcon = (
element: NonDeletedExcalidrawElement,
appState: AppState,
[x, y]: Point,
) => {
const threshold = 4 / appState.zoom.value;
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
[x1, y1, x2, y2],
element.angle,
appState,
);
const hitLink =
x > linkX - threshold &&
x < linkX + threshold + linkWidth &&
y > linkY - threshold &&
y < linkY + linkHeight + threshold;
return hitLink;
};
export const isPointHittingLink = (
element: NonDeletedExcalidrawElement,
appState: AppState,
[x, y]: Point,
isMobile: boolean,
) => {
if (!element.link || appState.selectedElementIds[element.id]) {
@ -340,19 +460,7 @@ export const isPointHittingLinkIcon = (
) {
return true;
}
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const [linkX, linkY, linkWidth, linkHeight] = getLinkHandleFromCoords(
[x1, y1, x2, y2],
element.angle,
appState,
);
const hitLink =
x > linkX - threshold &&
x < linkX + threshold + linkWidth &&
y > linkY - threshold &&
y < linkY + linkHeight + threshold;
return hitLink;
return isPointHittingLinkIcon(element, appState, [x, y]);
};
let HYPERLINK_TOOLTIP_TIMEOUT_ID: number | null = null;

View file

@ -18,6 +18,7 @@ import {
ExcalidrawBindableElement,
ExcalidrawElement,
ExcalidrawRectangleElement,
ExcalidrawEmbeddableElement,
ExcalidrawDiamondElement,
ExcalidrawTextElement,
ExcalidrawEllipseElement,
@ -39,7 +40,11 @@ import { FrameNameBoundsCache, Point } from "../types";
import { Drawable } from "roughjs/bin/core";
import { AppState } from "../types";
import { getShapeForElement } from "../renderer/renderElement";
import { hasBoundTextElement, isImageElement } from "./typeChecks";
import {
hasBoundTextElement,
isEmbeddableElement,
isImageElement,
} from "./typeChecks";
import { isTextElement } from ".";
import { isTransparent } from "../utils";
import { shouldShowBoundingBox } from "./transformHandles";
@ -57,7 +62,9 @@ const isElementDraggableFromInside = (
return true;
}
const isDraggableFromInside =
!isTransparent(element.backgroundColor) || hasBoundTextElement(element);
!isTransparent(element.backgroundColor) ||
hasBoundTextElement(element) ||
isEmbeddableElement(element);
if (element.type === "line") {
return isDraggableFromInside && isPathALoop(element.points);
}
@ -248,6 +255,7 @@ type HitTestArgs = {
const hitTestPointAgainstElement = (args: HitTestArgs): boolean => {
switch (args.element.type) {
case "rectangle":
case "embeddable":
case "image":
case "text":
case "diamond":
@ -306,6 +314,7 @@ export const distanceToBindableElement = (
case "rectangle":
case "image":
case "text":
case "embeddable":
case "frame":
return distanceToRectangle(element, point);
case "diamond":
@ -337,6 +346,7 @@ const distanceToRectangle = (
| ExcalidrawTextElement
| ExcalidrawFreeDrawElement
| ExcalidrawImageElement
| ExcalidrawEmbeddableElement
| ExcalidrawFrameElement,
point: Point,
): number => {
@ -645,17 +655,23 @@ export const determineFocusDistance = (
const c = line[1];
const mabs = Math.abs(m);
const nabs = Math.abs(n);
let ret;
switch (element.type) {
case "rectangle":
case "image":
case "text":
case "embeddable":
case "frame":
return c / (hwidth * (nabs + q * mabs));
ret = c / (hwidth * (nabs + q * mabs));
break;
case "diamond":
return mabs < nabs ? c / (nabs * hwidth) : c / (mabs * hheight);
ret = mabs < nabs ? c / (nabs * hwidth) : c / (mabs * hheight);
break;
case "ellipse":
return c / (hwidth * Math.sqrt(n ** 2 + q ** 2 * m ** 2));
ret = c / (hwidth * Math.sqrt(n ** 2 + q ** 2 * m ** 2));
break;
}
return ret || 0;
};
export const determineFocusPoint = (
@ -682,6 +698,7 @@ export const determineFocusPoint = (
case "image":
case "text":
case "diamond":
case "embeddable":
case "frame":
point = findFocusPointForRectangulars(element, focus, adjecentPointRel);
break;
@ -733,6 +750,7 @@ const getSortedElementLineIntersections = (
case "image":
case "text":
case "diamond":
case "embeddable":
case "frame":
const corners = getCorners(element);
intersections = corners
@ -768,6 +786,7 @@ const getCorners = (
| ExcalidrawImageElement
| ExcalidrawDiamondElement
| ExcalidrawTextElement
| ExcalidrawEmbeddableElement
| ExcalidrawFrameElement,
scale: number = 1,
): GA.Point[] => {
@ -777,6 +796,7 @@ const getCorners = (
case "rectangle":
case "image":
case "text":
case "embeddable":
case "frame":
return [
GA.point(hx, hy),
@ -926,6 +946,7 @@ export const findFocusPointForRectangulars = (
| ExcalidrawImageElement
| ExcalidrawDiamondElement
| ExcalidrawTextElement
| ExcalidrawEmbeddableElement
| ExcalidrawFrameElement,
// Between -1 and 1 for how far away should the focus point be relative
// to the size of the element. Sign determines orientation.

350
src/element/embeddable.ts Normal file
View file

@ -0,0 +1,350 @@
import { register } from "../actions/register";
import { FONT_FAMILY, VERTICAL_ALIGN } from "../constants";
import { t } from "../i18n";
import { ExcalidrawProps } from "../types";
import { getFontString, setCursorForShape, updateActiveTool } from "../utils";
import { newTextElement } from "./newElement";
import { getContainerElement, wrapText } from "./textElement";
import { isEmbeddableElement } from "./typeChecks";
import {
ExcalidrawElement,
ExcalidrawEmbeddableElement,
NonDeletedExcalidrawElement,
Theme,
} from "./types";
type EmbeddedLink =
| ({
aspectRatio: { w: number; h: number };
warning?: string;
} & (
| { type: "video" | "generic"; link: string }
| { type: "document"; srcdoc: (theme: Theme) => string }
))
| null;
const embeddedLinkCache = new Map<string, EmbeddedLink>();
const RE_YOUTUBE =
/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)(?:\?t=|&t=|\?start=|&start=)?([a-zA-Z0-9_-]+)?[^\s]*$/;
const RE_VIMEO =
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
const RE_FIGMA = /^https:\/\/(?:www\.)?figma\.com/;
const RE_GH_GIST = /^https:\/\/gist\.github\.com/;
const RE_GH_GIST_EMBED =
/^<script[\s\S]*?\ssrc=["'](https:\/\/gist.github.com\/.*?)\.js["']/i;
// not anchored to start to allow <blockquote> twitter embeds
const RE_TWITTER = /(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?twitter.com/;
const RE_TWITTER_EMBED =
/^<blockquote[\s\S]*?\shref=["'](https:\/\/twitter.com\/[^"']*)/i;
const RE_VALTOWN =
/^https:\/\/(?:www\.)?val.town\/(v|embed)\/[a-zA-Z_$][0-9a-zA-Z_$]+\.[a-zA-Z_$][0-9a-zA-Z_$]+/;
const RE_GENERIC_EMBED =
/^<(?:iframe|blockquote)[\s\S]*?\s(?:src|href)=["']([^"']*)["'][\s\S]*?>$/i;
const ALLOWED_DOMAINS = new Set([
"youtube.com",
"youtu.be",
"vimeo.com",
"player.vimeo.com",
"figma.com",
"link.excalidraw.com",
"gist.github.com",
"twitter.com",
"*.simplepdf.eu",
"stackblitz.com",
"val.town",
]);
const createSrcDoc = (body: string) => {
return `<html><body>${body}</body></html>`;
};
export const getEmbedLink = (link: string | null | undefined): EmbeddedLink => {
if (!link) {
return null;
}
if (embeddedLinkCache.has(link)) {
return embeddedLinkCache.get(link)!;
}
const originalLink = link;
let type: "video" | "generic" = "generic";
let aspectRatio = { w: 560, h: 840 };
const ytLink = link.match(RE_YOUTUBE);
if (ytLink?.[2]) {
const time = ytLink[3] ? `&start=${ytLink[3]}` : ``;
const isPortrait = link.includes("shorts");
type = "video";
switch (ytLink[1]) {
case "embed/":
case "watch?v=":
case "shorts/":
link = `https://www.youtube.com/embed/${ytLink[2]}?enablejsapi=1${time}`;
break;
case "playlist?list=":
case "embed/videoseries?list=":
link = `https://www.youtube.com/embed/videoseries?list=${ytLink[2]}&enablejsapi=1${time}`;
break;
default:
link = `https://www.youtube.com/embed/${ytLink[2]}?enablejsapi=1${time}`;
break;
}
aspectRatio = isPortrait ? { w: 315, h: 560 } : { w: 560, h: 315 };
embeddedLinkCache.set(originalLink, { link, aspectRatio, type });
return { link, aspectRatio, type };
}
const vimeoLink = link.match(RE_VIMEO);
if (vimeoLink?.[1]) {
const target = vimeoLink?.[1];
const warning = !/^\d+$/.test(target)
? t("toast.unrecognizedLinkFormat")
: undefined;
type = "video";
link = `https://player.vimeo.com/video/${target}?api=1`;
aspectRatio = { w: 560, h: 315 };
//warning deliberately ommited so it is displayed only once per link
//same link next time will be served from cache
embeddedLinkCache.set(originalLink, { link, aspectRatio, type });
return { link, aspectRatio, type, warning };
}
const figmaLink = link.match(RE_FIGMA);
if (figmaLink) {
type = "generic";
link = `https://www.figma.com/embed?embed_host=share&url=${encodeURIComponent(
link,
)}`;
aspectRatio = { w: 550, h: 550 };
embeddedLinkCache.set(originalLink, { link, aspectRatio, type });
return { link, aspectRatio, type };
}
const valLink = link.match(RE_VALTOWN);
if (valLink) {
link =
valLink[1] === "embed" ? valLink[0] : valLink[0].replace("/v", "/embed");
embeddedLinkCache.set(originalLink, { link, aspectRatio, type });
return { link, aspectRatio, type };
}
if (RE_TWITTER.test(link)) {
let ret: EmbeddedLink;
// assume embed code
if (/<blockquote/.test(link)) {
const srcDoc = createSrcDoc(link);
ret = {
type: "document",
srcdoc: () => srcDoc,
aspectRatio: { w: 480, h: 480 },
};
// assume regular tweet url
} else {
ret = {
type: "document",
srcdoc: (theme: string) =>
createSrcDoc(
`<blockquote class="twitter-tweet" data-dnt="true" data-theme="${theme}"><a href="${link}"></a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>`,
),
aspectRatio: { w: 480, h: 480 },
};
}
embeddedLinkCache.set(originalLink, ret);
return ret;
}
if (RE_GH_GIST.test(link)) {
let ret: EmbeddedLink;
// assume embed code
if (/<script>/.test(link)) {
const srcDoc = createSrcDoc(link);
ret = {
type: "document",
srcdoc: () => srcDoc,
aspectRatio: { w: 550, h: 720 },
};
// assume regular url
} else {
ret = {
type: "document",
srcdoc: () =>
createSrcDoc(`
<script src="${link}.js"></script>
<style type="text/css">
* { margin: 0px; }
table, .gist { height: 100%; }
.gist .gist-file { height: calc(100vh - 2px); padding: 0px; display: grid; grid-template-rows: 1fr auto; }
</style>
`),
aspectRatio: { w: 550, h: 720 },
};
}
embeddedLinkCache.set(link, ret);
return ret;
}
embeddedLinkCache.set(link, { link, aspectRatio, type });
return { link, aspectRatio, type };
};
export const isEmbeddableOrFrameLabel = (
element: NonDeletedExcalidrawElement,
): Boolean => {
if (isEmbeddableElement(element)) {
return true;
}
if (element.type === "text") {
const container = getContainerElement(element);
if (container && isEmbeddableElement(container)) {
return true;
}
}
return false;
};
export const createPlaceholderEmbeddableLabel = (
element: ExcalidrawEmbeddableElement,
): ExcalidrawElement => {
const text =
!element.link || element?.link === "" ? "Empty Web-Embed" : element.link;
const fontSize = Math.max(
Math.min(element.width / 2, element.width / text.length),
element.width / 30,
);
const fontFamily = FONT_FAMILY.Helvetica;
const fontString = getFontString({
fontSize,
fontFamily,
});
return newTextElement({
x: element.x + element.width / 2,
y: element.y + element.height / 2,
strokeColor:
element.strokeColor !== "transparent" ? element.strokeColor : "black",
backgroundColor: "transparent",
fontFamily,
fontSize,
text: wrapText(text, fontString, element.width - 20),
textAlign: "center",
verticalAlign: VERTICAL_ALIGN.MIDDLE,
angle: element.angle ?? 0,
});
};
export const actionSetEmbeddableAsActiveTool = register({
name: "setEmbeddableAsActiveTool",
trackEvent: { category: "toolbar" },
perform: (elements, appState, _, app) => {
const nextActiveTool = updateActiveTool(appState, {
type: "embeddable",
});
setCursorForShape(app.canvas, {
...appState,
activeTool: nextActiveTool,
});
return {
elements,
appState: {
...appState,
activeTool: updateActiveTool(appState, {
type: "embeddable",
}),
},
commitToHistory: false,
};
},
});
const validateHostname = (
url: string,
/** using a Set assumes it already contains normalized bare domains */
allowedHostnames: Set<string> | string,
): boolean => {
try {
const { hostname } = new URL(url);
const bareDomain = hostname.replace(/^www\./, "");
const bareDomainWithFirstSubdomainWildcarded = bareDomain.replace(
/^([^.]+)/,
"*",
);
if (allowedHostnames instanceof Set) {
return (
ALLOWED_DOMAINS.has(bareDomain) ||
ALLOWED_DOMAINS.has(bareDomainWithFirstSubdomainWildcarded)
);
}
if (bareDomain === allowedHostnames.replace(/^www\./, "")) {
return true;
}
} catch (error) {
// ignore
}
return false;
};
export const extractSrc = (htmlString: string): string => {
const twitterMatch = htmlString.match(RE_TWITTER_EMBED);
if (twitterMatch && twitterMatch.length === 2) {
return twitterMatch[1];
}
const gistMatch = htmlString.match(RE_GH_GIST_EMBED);
if (gistMatch && gistMatch.length === 2) {
return gistMatch[1];
}
const match = htmlString.match(RE_GENERIC_EMBED);
if (match && match.length === 2) {
return match[1];
}
return htmlString;
};
export const embeddableURLValidator = (
url: string | null | undefined,
validateEmbeddable: ExcalidrawProps["validateEmbeddable"],
): boolean => {
if (!url) {
return false;
}
if (validateEmbeddable != null) {
if (typeof validateEmbeddable === "function") {
const ret = validateEmbeddable(url);
// if return value is undefined, leave validation to default
if (typeof ret === "boolean") {
return ret;
}
} else if (typeof validateEmbeddable === "boolean") {
return validateEmbeddable;
} else if (validateEmbeddable instanceof RegExp) {
return validateEmbeddable.test(url);
} else if (Array.isArray(validateEmbeddable)) {
for (const domain of validateEmbeddable) {
if (domain instanceof RegExp) {
if (url.match(domain)) {
return true;
}
} else if (validateHostname(url, domain)) {
return true;
}
}
return false;
}
}
return validateHostname(url, ALLOWED_DOMAINS);
};

View file

@ -13,6 +13,7 @@ import {
FontFamilyValues,
ExcalidrawTextContainer,
ExcalidrawFrameElement,
ExcalidrawEmbeddableElement,
} from "../element/types";
import {
arrayToMap,
@ -130,6 +131,18 @@ export const newElement = (
): NonDeleted<ExcalidrawGenericElement> =>
_newElementBase<ExcalidrawGenericElement>(opts.type, opts);
export const newEmbeddableElement = (
opts: {
type: "embeddable";
validated: boolean | undefined;
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawEmbeddableElement> => {
return {
..._newElementBase<ExcalidrawEmbeddableElement>("embeddable", opts),
validated: opts.validated,
};
};
export const newFrameElement = (
opts: ElementConstructorOpts,
): NonDeleted<ExcalidrawFrameElement> => {
@ -177,7 +190,6 @@ export const newTextElement = (
containerId?: ExcalidrawTextContainer["id"];
lineHeight?: ExcalidrawTextElement["lineHeight"];
strokeWidth?: ExcalidrawTextElement["strokeWidth"];
isFrameName?: boolean;
} & ElementConstructorOpts,
): NonDeleted<ExcalidrawTextElement> => {
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
@ -212,7 +224,6 @@ export const newTextElement = (
containerId: opts.containerId || null,
originalText: text,
lineHeight,
isFrameName: opts.isFrameName || false,
},
{},
);
@ -432,7 +443,7 @@ const _deepCopyElement = (val: any, depth: number = 0) => {
// we're not cloning non-array & non-plain-object objects because we
// don't support them on excalidraw elements yet. If we do, we need to make
// sure we start cloning them, so let's warn about it.
if (process.env.NODE_ENV === "development") {
if (import.meta.env.DEV) {
if (
objectType !== "[object Object]" &&
objectType !== "[object Array]" &&

View file

@ -7,11 +7,11 @@ export const showSelectedShapeActions = (
elements: readonly NonDeletedExcalidrawElement[],
) =>
Boolean(
(!appState.viewModeEnabled &&
appState.activeTool.type !== "custom" &&
(appState.editingElement ||
(appState.activeTool.type !== "selection" &&
appState.activeTool.type !== "eraser" &&
appState.activeTool.type !== "hand"))) ||
getSelectedElements(elements, appState).length,
!appState.viewModeEnabled &&
((appState.activeTool.type !== "custom" &&
(appState.editingElement ||
(appState.activeTool.type !== "selection" &&
appState.activeTool.type !== "eraser" &&
appState.activeTool.type !== "hand"))) ||
getSelectedElements(elements, appState).length),
);

View file

@ -1,19 +1,32 @@
import { vi } from "vitest";
import { getPerfectElementSize } from "./sizeHelpers";
import * as constants from "../constants";
const EPSILON_DIGITS = 3;
// Needed so that we can mock the value of constants which is done in
// below tests. In Jest this wasn't needed as global override was possible
// but vite doesn't allow that hence we need to mock
vi.mock(
"../constants.ts",
//@ts-ignore
async (importOriginal) => {
const module: any = await importOriginal();
return { ...module };
},
);
describe("getPerfectElementSize", () => {
it("should return height:0 if `elementType` is line and locked angle is 0", () => {
const { height, width } = getPerfectElementSize("line", 149, 10);
expect(width).toBeCloseTo(149, EPSILON_DIGITS);
expect(height).toBeCloseTo(0, EPSILON_DIGITS);
});
it("should return width:0 if `elementType` is line and locked angle is 90 deg (Math.PI/2)", () => {
const { height, width } = getPerfectElementSize("line", 10, 140);
expect(width).toBeCloseTo(0, EPSILON_DIGITS);
expect(height).toBeCloseTo(140, EPSILON_DIGITS);
});
it("should return height:0 if `elementType` is arrow and locked angle is 0", () => {
const { height, width } = getPerfectElementSize("arrow", 200, 20);
expect(width).toBeCloseTo(200, EPSILON_DIGITS);
@ -24,16 +37,19 @@ describe("getPerfectElementSize", () => {
expect(width).toBeCloseTo(0, EPSILON_DIGITS);
expect(height).toBeCloseTo(100, EPSILON_DIGITS);
});
it("should return adjust height to be width * tan(locked angle)", () => {
const { height, width } = getPerfectElementSize("arrow", 120, 185);
expect(width).toBeCloseTo(120, EPSILON_DIGITS);
expect(height).toBeCloseTo(207.846, EPSILON_DIGITS);
});
it("should return height equals to width if locked angle is 45 deg", () => {
const { height, width } = getPerfectElementSize("arrow", 135, 145);
expect(width).toBeCloseTo(135, EPSILON_DIGITS);
expect(height).toBeCloseTo(135, EPSILON_DIGITS);
});
it("should return height:0 and width:0 when width and height are 0", () => {
const { height, width } = getPerfectElementSize("arrow", 0, 0);
expect(width).toBeCloseTo(0, EPSILON_DIGITS);

View file

@ -955,7 +955,7 @@ describe("textWysiwyg", () => {
// should center align horizontally and vertically by default
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
85,
4.5,
]
@ -979,7 +979,7 @@ describe("textWysiwyg", () => {
// should left align horizontally and bottom vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
15,
65,
]
@ -1001,7 +1001,7 @@ describe("textWysiwyg", () => {
// should right align horizontally and top vertically after resize
resize(rectangle, "ne", [rectangle.x + 100, rectangle.y - 100]);
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
375,
-539,
]
@ -1279,7 +1279,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Left"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
15,
25,
]
@ -1290,7 +1290,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
30,
25,
]
@ -1302,7 +1302,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Align top"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
45,
25,
]
@ -1313,7 +1313,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center vertically"));
fireEvent.click(screen.getByTitle("Left"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
15,
45,
]
@ -1325,7 +1325,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
30,
45,
]
@ -1337,7 +1337,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center vertically"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
45,
45,
]
@ -1349,7 +1349,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
15,
65,
]
@ -1360,7 +1360,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Center"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
30,
65,
]
@ -1371,7 +1371,7 @@ describe("textWysiwyg", () => {
fireEvent.click(screen.getByTitle("Right"));
fireEvent.click(screen.getByTitle("Align bottom"));
expect([h.elements[1].x, h.elements[1].y]).toMatchInlineSnapshot(`
Array [
[
45,
65,
]

View file

@ -4,6 +4,7 @@ import { MarkNonNullable } from "../utility-types";
import {
ExcalidrawElement,
ExcalidrawTextElement,
ExcalidrawEmbeddableElement,
ExcalidrawLinearElement,
ExcalidrawBindableElement,
ExcalidrawGenericElement,
@ -24,7 +25,8 @@ export const isGenericElement = (
(element.type === "selection" ||
element.type === "rectangle" ||
element.type === "diamond" ||
element.type === "ellipse")
element.type === "ellipse" ||
element.type === "embeddable")
);
};
@ -40,6 +42,12 @@ export const isImageElement = (
return !!element && element.type === "image";
};
export const isEmbeddableElement = (
element: ExcalidrawElement | null | undefined,
): element is ExcalidrawEmbeddableElement => {
return !!element && element.type === "embeddable";
};
export const isTextElement = (
element: ExcalidrawElement | null,
): element is ExcalidrawTextElement => {
@ -112,6 +120,7 @@ export const isBindableElement = (
element.type === "diamond" ||
element.type === "ellipse" ||
element.type === "image" ||
element.type === "embeddable" ||
(element.type === "text" && !element.containerId))
);
};
@ -135,6 +144,7 @@ export const isExcalidrawElement = (element: any): boolean => {
element?.type === "text" ||
element?.type === "diamond" ||
element?.type === "rectangle" ||
element?.type === "embeddable" ||
element?.type === "ellipse" ||
element?.type === "arrow" ||
element?.type === "freedraw" ||
@ -162,7 +172,8 @@ export const isBoundToContainer = (
);
};
export const isUsingAdaptiveRadius = (type: string) => type === "rectangle";
export const isUsingAdaptiveRadius = (type: string) =>
type === "rectangle" || type === "embeddable";
export const isUsingProportionalRadius = (type: string) =>
type === "line" || type === "arrow" || type === "diamond";
@ -193,17 +204,13 @@ export const canApplyRoundnessTypeToElement = (
export const getDefaultRoundnessTypeForElement = (
element: ExcalidrawElement,
) => {
if (
element.type === "arrow" ||
element.type === "line" ||
element.type === "diamond"
) {
if (isUsingProportionalRadius(element.type)) {
return {
type: ROUNDNESS.PROPORTIONAL_RADIUS,
};
}
if (element.type === "rectangle") {
if (isUsingAdaptiveRadius(element.type)) {
return {
type: ROUNDNESS.ADAPTIVE_RADIUS,
};

View file

@ -84,6 +84,19 @@ export type ExcalidrawEllipseElement = _ExcalidrawElementBase & {
type: "ellipse";
};
export type ExcalidrawEmbeddableElement = _ExcalidrawElementBase &
Readonly<{
/**
* indicates whether the embeddable src (url) has been validated for rendering.
* nullish value indicates that the validation is pending. We reset the
* value on each restore (or url change) so that we can guarantee
* the validation came from a trusted source (the editor). Also because we
* may not have access to host-app supplied url validator during restore.
*/
validated?: boolean;
type: "embeddable";
}>;
export type ExcalidrawImageElement = _ExcalidrawElementBase &
Readonly<{
type: "image";
@ -110,6 +123,7 @@ export type ExcalidrawFrameElement = _ExcalidrawElementBase & {
export type ExcalidrawGenericElement =
| ExcalidrawSelectionElement
| ExcalidrawRectangleElement
| ExcalidrawEmbeddableElement
| ExcalidrawDiamondElement
| ExcalidrawEllipseElement;
@ -156,6 +170,7 @@ export type ExcalidrawBindableElement =
| ExcalidrawEllipseElement
| ExcalidrawTextElement
| ExcalidrawImageElement
| ExcalidrawEmbeddableElement
| ExcalidrawFrameElement;
export type ExcalidrawTextContainer =

View file

@ -171,10 +171,7 @@ class Collab extends PureComponent<Props, CollabState> {
appJotaiStore.set(collabAPIAtom, collabAPI);
if (
process.env.NODE_ENV === ENV.TEST ||
process.env.NODE_ENV === ENV.DEVELOPMENT
) {
if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
window.collab = window.collab || ({} as Window["collab"]);
Object.defineProperties(window, {
collab: {
@ -333,7 +330,7 @@ class Collab extends PureComponent<Props, CollabState> {
* Indicates whether to fetch files that are errored or pending and older
* than 10 seconds.
*
* Use this as a machanism to fetch files which may be ok but for some
* Use this as a mechanism to fetch files which may be ok but for some
* reason their status was not updated correctly.
*/
forceFetchFiles?: boolean;
@ -860,10 +857,7 @@ declare global {
}
}
if (
process.env.NODE_ENV === ENV.TEST ||
process.env.NODE_ENV === ENV.DEVELOPMENT
) {
if (import.meta.env.MODE === ENV.TEST || import.meta.env.DEV) {
window.collab = window.collab || ({} as Window["collab"]);
}

View file

@ -19,7 +19,9 @@ export const AppWelcomeScreen: React.FC<{
return (
<a
style={{ pointerEvents: "all" }}
href={`${process.env.REACT_APP_PLUS_APP}?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenSignedInUser`}
href={`${
import.meta.env.VITE_APP_PLUS_APP
}?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenSignedInUser`}
key={idx}
>
Excalidraw+

View file

@ -6,7 +6,9 @@ export const ExcalidrawPlusAppLink = () => {
}
return (
<a
href={`${process.env.REACT_APP_PLUS_APP}?utm_source=excalidraw&utm_medium=app&utm_content=signedInUserRedirectButton#excalidraw-redirect`}
href={`${
import.meta.env.VITE_APP_PLUS_APP
}?utm_source=excalidraw&utm_medium=app&utm_content=signedInUserRedirectButton#excalidraw-redirect`}
target="_blank"
rel="noreferrer"
className="plus-button"

View file

@ -21,10 +21,12 @@ import { ResolutionType } from "../../utility-types";
let FIREBASE_CONFIG: Record<string, any>;
try {
FIREBASE_CONFIG = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG);
FIREBASE_CONFIG = JSON.parse(import.meta.env.VITE_APP_FIREBASE_CONFIG);
} catch (error: any) {
console.warn(
`Error JSON parsing firebase config. Supplied value: ${process.env.REACT_APP_FIREBASE_CONFIG}`,
`Error JSON parsing firebase config. Supplied value: ${
import.meta.env.VITE_APP_FIREBASE_CONFIG
}`,
);
FIREBASE_CONFIG = {};
}

View file

@ -47,8 +47,8 @@ export const getSyncableElements = (elements: readonly ExcalidrawElement[]) =>
isSyncableElement(element),
) as SyncableExcalidrawElement[];
const BACKEND_V2_GET = process.env.REACT_APP_BACKEND_V2_GET_URL;
const BACKEND_V2_POST = process.env.REACT_APP_BACKEND_V2_POST_URL;
const BACKEND_V2_GET = import.meta.env.VITE_APP_BACKEND_V2_GET_URL;
const BACKEND_V2_POST = import.meta.env.VITE_APP_BACKEND_V2_POST_URL;
const generateRoomId = async () => {
const buffer = new Uint8Array(ROOM_ID_BYTES);
@ -67,16 +67,16 @@ export const getCollabServer = async (): Promise<{
url: string;
polling: boolean;
}> => {
if (process.env.REACT_APP_WS_SERVER_URL) {
if (import.meta.env.VITE_APP_WS_SERVER_URL) {
return {
url: process.env.REACT_APP_WS_SERVER_URL,
url: import.meta.env.VITE_APP_WS_SERVER_URL,
polling: true,
};
}
try {
const resp = await fetch(
`${process.env.REACT_APP_PORTAL_URL}/collab-server`,
`${import.meta.env.VITE_APP_PORTAL_URL}/collab-server`,
);
return await resp.json();
} catch (error) {

View file

@ -100,6 +100,20 @@ polyfill();
window.EXCALIDRAW_THROTTLE_RENDER = true;
let isSelfEmbedding = false;
if (window.self !== window.top) {
try {
const parentUrl = new URL(document.referrer);
const currentUrl = new URL(window.location.href);
if (parentUrl.origin === currentUrl.origin) {
isSelfEmbedding = true;
}
} catch (error) {
// ignore
}
}
const languageDetector = new LanguageDetector();
languageDetector.init({
languageUtils: {},
@ -518,7 +532,9 @@ const ExcalidrawWrapper = () => {
const [theme, setTheme] = useState<Theme>(
() =>
localStorage.getItem(STORAGE_KEYS.LOCAL_STORAGE_THEME) ||
(localStorage.getItem(
STORAGE_KEYS.LOCAL_STORAGE_THEME,
) as Theme | null) ||
// FIXME migration from old LS scheme. Can be removed later. #5660
importFromLocalStorage().appState?.theme ||
THEME.LIGHT,
@ -641,6 +657,25 @@ const ExcalidrawWrapper = () => {
const isOffline = useAtomValue(isOfflineAtom);
// browsers generally prevent infinite self-embedding, there are
// cases where it still happens, and while we disallow self-embedding
// by not whitelisting our own origin, this serves as an additional guard
if (isSelfEmbedding) {
return (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
textAlign: "center",
height: "100%",
}}
>
<h1>I'm not a pretzel!</h1>
</div>
);
}
return (
<div
style={{ height: "100%" }}

View file

@ -1,31 +0,0 @@
import { register as registerServiceWorker } from "../serviceWorkerRegistration";
import { EVENT } from "../constants";
// On Apple mobile devices add the proprietary app icon and splashscreen markup.
// No one should have to do this manually, and eventually this annoyance will
// go away once https://bugs.webkit.org/show_bug.cgi?id=183937 is fixed.
if (
/\b(iPad|iPhone|iPod|Safari)\b/.test(navigator.userAgent) &&
!matchMedia("(display-mode: standalone)").matches
) {
import(/* webpackChunkName: "pwacompat" */ "pwacompat");
}
registerServiceWorker({
onUpdate: (registration) => {
const waitingServiceWorker = registration.waiting;
if (waitingServiceWorker) {
waitingServiceWorker.addEventListener(
EVENT.STATE_CHANGE,
(event: Event) => {
const target = event.target as ServiceWorker;
const state = target.state as ServiceWorkerState;
if (state === "activated") {
window.location.reload();
}
},
);
waitingServiceWorker.postMessage({ type: "SKIP_WAITING" });
}
},
});

View file

@ -7,7 +7,7 @@ const SentryEnvHostnameMap: { [key: string]: string } = {
};
const REACT_APP_DISABLE_SENTRY =
process.env.REACT_APP_DISABLE_SENTRY === "true";
import.meta.env.VITE_APP_DISABLE_SENTRY === "true";
// Disable Sentry locally or inside the Docker to avoid noise/respect privacy
const onlineEnv =
@ -21,7 +21,7 @@ Sentry.init({
? "https://7bfc596a5bf945eda6b660d3015a5460@sentry.io/5179260"
: undefined,
environment: onlineEnv ? SentryEnvHostnameMap[onlineEnv] : undefined,
release: process.env.REACT_APP_GIT_SHA,
release: import.meta.env.VITE_APP_GIT_SHA,
ignoreErrors: [
"undefined is not an object (evaluating 'window.__pad.performLoop')", // Only happens on Safari, but spams our servers. Doesn't break anything
],

View file

@ -16,7 +16,7 @@ import {
} from "./element/textElement";
import { arrayToMap, findIndex } from "./utils";
import { mutateElement } from "./element/mutateElement";
import { AppState } from "./types";
import { AppClassProperties, AppState } from "./types";
import { getElementsWithinSelection, getSelectedElements } from "./scene";
import { isFrameElement } from "./element";
import { moveOneRight } from "./zindex";
@ -571,8 +571,13 @@ export const replaceAllElementsInFrame = (
export const updateFrameMembershipOfSelectedElements = (
allElements: ExcalidrawElementsIncludingDeleted,
appState: AppState,
app: AppClassProperties,
) => {
const selectedElements = getSelectedElements(allElements, appState);
const selectedElements = app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
// supplying elements explicitly in case we're passed non-state elements
elements: allElements,
});
const elementsToFilter = new Set<ExcalidrawElement>(selectedElements);
if (appState.editingGroupId) {

16
src/global.d.ts vendored
View file

@ -38,16 +38,6 @@ interface CanvasRenderingContext2D {
) => void;
}
// https://github.com/facebook/create-react-app/blob/ddcb7d5/packages/react-scripts/lib/react-app.d.ts
declare namespace NodeJS {
interface ProcessEnv {
readonly REACT_APP_BACKEND_V2_GET_URL: string;
readonly REACT_APP_BACKEND_V2_POST_URL: string;
readonly REACT_APP_PORTAL_URL: string;
readonly REACT_APP_FIREBASE_CONFIG: string;
}
}
interface Clipboard extends EventTarget {
write(data: any[]): Promise<void>;
}
@ -120,3 +110,9 @@ declare module "image-blob-reduce" {
const reduce: ImageBlobReduce.ImageBlobReduceStatic;
export = reduce;
}
declare namespace jest {
interface Expect {
toBeNonNaNNumber(): void;
}
}

View file

@ -1,5 +1,10 @@
import { GroupId, ExcalidrawElement, NonDeleted } from "./element/types";
import { AppState } from "./types";
import {
GroupId,
ExcalidrawElement,
NonDeleted,
NonDeletedExcalidrawElement,
} from "./element/types";
import { AppClassProperties, AppState } from "./types";
import { getSelectedElements } from "./scene";
import { getBoundTextElement } from "./element/textElement";
import { makeNextSelectedElementIds } from "./scene/selection";
@ -67,12 +72,23 @@ export const getSelectedGroupIds = (appState: AppState): GroupId[] =>
*/
export const selectGroupsForSelectedElements = (
appState: AppState,
elements: readonly NonDeleted<ExcalidrawElement>[],
elements: readonly NonDeletedExcalidrawElement[],
prevAppState: AppState,
/**
* supply null in cases where you don't have access to App instance and
* you don't care about optimizing selectElements retrieval
*/
app: AppClassProperties | null,
): AppState => {
let nextAppState: AppState = { ...appState, selectedGroupIds: {} };
const selectedElements = getSelectedElements(elements, appState);
const selectedElements = app
? app.scene.getSelectedElements({
selectedElementIds: appState.selectedElementIds,
// supplying elements explicitly in case we're passed non-state elements
elements,
})
: getSelectedElements(elements, appState);
if (!selectedElements.length) {
return {

View file

@ -17,6 +17,7 @@ const exportLibraryItemToSvg = async (elements: LibraryItem["elements"]) => {
viewBackgroundColor: COLOR_PALETTE.white,
},
files: null,
renderEmbeddables: false,
});
};

View file

@ -1,8 +1,8 @@
import fallbackLangData from "./locales/en.json";
import percentages from "./locales/percentages.json";
import { ENV } from "./constants";
import { jotaiScope, jotaiStore } from "./jotai";
import { atom, useAtomValue } from "jotai";
import { NestedKeyOf } from "./utility-types";
const COMPLETION_THRESHOLD = 85;
@ -12,6 +12,8 @@ export interface Language {
rtl?: boolean;
}
export type TranslationKeys = NestedKeyOf<typeof fallbackLangData>;
export const defaultLang = { code: "en", label: "English" };
export const languages: Language[] = [
@ -71,7 +73,7 @@ export const languages: Language[] = [
];
const TEST_LANG_CODE = "__test__";
if (process.env.NODE_ENV === ENV.DEVELOPMENT) {
if (import.meta.env.DEV) {
languages.unshift(
{ code: TEST_LANG_CODE, label: "test language" },
{
@ -123,7 +125,7 @@ const findPartsForData = (data: any, parts: string[]) => {
};
export const t = (
path: string,
path: NestedKeyOf<typeof fallbackLangData>,
replacement?: { [key: string]: string | number } | null,
fallback?: string,
) => {
@ -142,7 +144,7 @@ export const t = (
if (translation === undefined) {
const errorMessage = `Can't find translation for ${path}`;
// in production, don't blow up the app on a missing translation key
if (process.env.NODE_ENV === "production") {
if (import.meta.env.PROD) {
console.warn(errorMessage);
return "";
}

View file

@ -1,12 +1,14 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import ExcalidrawApp from "./excalidraw-app";
import { registerSW } from "virtual:pwa-register";
import "./excalidraw-app/pwa";
import "./excalidraw-app/sentry";
window.__EXCALIDRAW_SHA__ = process.env.REACT_APP_GIT_SHA;
window.__EXCALIDRAW_SHA__ = import.meta.env.VITE_APP_GIT_SHA;
const rootElement = document.getElementById("root")!;
const root = createRoot(rootElement);
registerSW();
root.render(
<StrictMode>
<ExcalidrawApp />

View file

@ -65,6 +65,7 @@ export const KEYS = {
Y: "y",
Z: "z",
K: "k",
W: "w",
0: "0",
1: "1",

View file

@ -109,8 +109,12 @@
"createContainerFromText": "Wrap text in a container",
"link": {
"edit": "Edit link",
"editEmbed": "Edit link & embed",
"create": "Create link",
"label": "Link"
"createEmbed": "Create link & embed",
"label": "Link",
"labelEmbed": "Link & embed",
"empty": "No link is set"
},
"lineEditor": {
"edit": "Edit line",
@ -164,9 +168,11 @@
"cancel": "Cancel",
"clear": "Clear",
"remove": "Remove",
"embed": "Toggle embedding",
"publishLibrary": "Publish",
"submit": "Submit",
"confirm": "Confirm"
"confirm": "Confirm",
"embeddableInteractionButton": "Click to interact"
},
"alerts": {
"clearReset": "This will clear the whole canvas. Are you sure?",
@ -206,6 +212,10 @@
"line2": "This could result in breaking the <bold>Text Elements</bold> in your drawings.",
"line3": "We strongly recommend disabling this setting. You can follow <link>these steps</link> on how to do so.",
"line4": "If disabling this setting doesn't fix the display of text elements, please open an <issueLink>issue</issueLink> on our GitHub, or write us on <discordLink>Discord</discordLink>"
},
"libraryElementTypeError": {
"embeddable": "Embeddable elements cannot be added to the library.",
"image": "Support for adding images to the library coming soon!"
}
},
"toolBar": {
@ -224,6 +234,7 @@
"link": "Add/ Update link for a selected shape",
"eraser": "Eraser",
"frame": "Frame tool",
"embeddable": "Web Embed",
"hand": "Hand (panning tool)",
"extraTools": "More tools"
},
@ -237,6 +248,7 @@
"linearElement": "Click to start multiple points, drag for single line",
"freeDraw": "Click and drag, release when you're finished",
"text": "Tip: you can also add text by double-clicking anywhere with the selection tool",
"embeddable": "Click-drag to create a website embed",
"text_selected": "Double-click or press ENTER to edit text",
"text_editing": "Press Escape or CtrlOrCmd+ENTER to finish editing",
"linearElementMulti": "Click on last point or press Escape or Enter to finish",
@ -411,7 +423,9 @@
"fileSavedToFilename": "Saved to {filename}",
"canvas": "canvas",
"selection": "selection",
"pasteAsSingleElement": "Use {{shortcut}} to paste as a single element,\nor paste into an existing text editor"
"pasteAsSingleElement": "Use {{shortcut}} to paste as a single element,\nor paste into an existing text editor",
"unableToEmbed": "Embedding this url is currently not allowed. Raise an issue on GitHub to request the url whitelisted",
"unrecognizedLinkFormat": "The link you embedded does not match the expected format. Please try to paste the 'embed' string provided by the source site"
},
"colors": {
"transparent": "Transparent",

View file

@ -0,0 +1,16 @@
[
{
"path": "dist/excalidraw.production.min.js",
"limit": "290 kB"
},
{
"path": "dist/excalidraw-assets/locales",
"name": "dist/excalidraw-assets/locales",
"limit": "270 kB"
},
{
"path": "dist/excalidraw-assets/vendor-*.js",
"name": "dist/excalidraw-assets/vendor*.js",
"limit": "30 kB"
}
]

View file

@ -13,8 +13,27 @@ Please add the latest change on the top under the correct section.
## Unreleased
### renderEmbeddable
```tsx
(element: NonDeletedExcalidrawElement, radius: number, appState: UIAppState) => JSX.Element | null;`
```
The renderEmbeddable function allows you to customize the rendering of a JSX component instead of using the default `<iframe>`. By setting props.renderEmbeddable, you can provide a custom implementation for rendering the element.
#### Parameters:
- element (NonDeletedExcalidrawElement): The element to be rendered.
- radius (number): The calculated border radius in pixels.
- appState (UIAppState): The current state of the UI.
#### Return value:
JSX.Element | null: The JSX component representing the custom rendering, or null if the default `<iframe>` should be rendered.
### Features
- Added [`props.validateEmbeddable`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props#validateEmbeddable) to customize embeddable src url validation. [#6691](https://github.com/excalidraw/excalidraw/pull/6691)
- Add support for `opts.fitToViewport` and `opts.viewportZoomFactor` in the [`ExcalidrawAPI.scrollToContent`](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props/ref#scrolltocontent) API. [#6581](https://github.com/excalidraw/excalidraw/pull/6581).
- Properly sanitize element `link` urls. [#6728](https://github.com/excalidraw/excalidraw/pull/6728).
- Sidebar component now supports tabs — for more detailed description of new behavior and breaking changes, see the linked PR. [#6213](https://github.com/excalidraw/excalidraw/pull/6213)

View file

@ -9,9 +9,9 @@ const parseEnvVariables = (filepath) => {
},
{},
);
envVars.PKG_NAME = JSON.stringify(pkg.name);
envVars.PKG_VERSION = JSON.stringify(pkg.version);
envVars.IS_EXCALIDRAW_NPM_PACKAGE = JSON.stringify(true);
envVars.VITE_PKG_NAME = JSON.stringify(pkg.name);
envVars.VITE_PKG_VERSION = JSON.stringify(pkg.version);
envVars.VITE_IS_EXCALIDRAW_NPM_PACKAGE = JSON.stringify(true);
return envVars;
};

View file

@ -26,7 +26,7 @@ import {
LibraryItems,
PointerDownState as ExcalidrawPointerDownState,
} from "../../../types";
import { NonDeletedExcalidrawElement } from "../../../element/types";
import { NonDeletedExcalidrawElement, Theme } from "../../../element/types";
import { ImportedLibraryData } from "../../../data/types";
import CustomFooter from "./CustomFooter";
import MobileFooter from "./MobileFooter";
@ -96,7 +96,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
const [canvasUrl, setCanvasUrl] = useState<string>("");
const [exportWithDarkMode, setExportWithDarkMode] = useState(false);
const [exportEmbedScene, setExportEmbedScene] = useState(false);
const [theme, setTheme] = useState("light");
const [theme, setTheme] = useState<Theme>("light");
const [isCollaborating, setIsCollaborating] = useState(false);
const [commentIcons, setCommentIcons] = useState<{ [id: string]: Comment }>(
{},
@ -595,11 +595,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
type="checkbox"
checked={theme === "dark"}
onChange={() => {
let newTheme = "light";
if (theme === "light") {
newTheme = "dark";
}
setTheme(newTheme);
setTheme(theme === "light" ? "dark" : "light");
}}
/>
Switch to Dark Theme
@ -678,11 +674,17 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
gridModeEnabled={gridModeEnabled}
theme={theme}
name="Custom name of drawing"
UIOptions={{ canvasActions: { loadScene: false } }}
UIOptions={{
canvasActions: {
loadScene: false,
},
}}
renderTopRightUI={renderTopRightUI}
onLinkOpen={onLinkOpen}
onPointerDown={onPointerDown}
onScrollChange={rerenderCommentIcons}
// allow all urls
validateEmbeddable={true}
>
{excalidrawAPI && (
<Footer>

View file

@ -43,6 +43,8 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
onScrollChange,
children,
scrollConstraints,
validateEmbeddable,
renderEmbeddable,
} = props;
const canvasActions = props.UIOptions?.canvasActions;
@ -117,6 +119,8 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
onPointerDown={onPointerDown}
onScrollChange={onScrollChange}
scrollConstraints={scrollConstraints}
validateEmbeddable={validateEmbeddable}
renderEmbeddable={renderEmbeddable}
>
{children}
</App>

View file

@ -52,15 +52,19 @@
"@babel/preset-env": "7.18.6",
"@babel/preset-react": "7.18.6",
"@babel/preset-typescript": "7.18.6",
"@size-limit/preset-big-lib": "8.2.6",
"autoprefixer": "10.4.7",
"babel-loader": "8.2.5",
"babel-plugin-transform-class-properties": "6.24.1",
"cross-env": "7.0.3",
"css-loader": "6.7.1",
"dotenv": "16.0.1",
"import-meta-loader": "1.1.0",
"mini-css-extract-plugin": "2.6.1",
"postcss-loader": "7.0.1",
"sass-loader": "13.0.2",
"size-limit": "8.2.4",
"style-loader": "3.3.3",
"terser-webpack-plugin": "5.3.3",
"ts-loader": "9.3.1",
"typescript": "4.9.4",
@ -79,6 +83,7 @@
"pack": "yarn build:umd && yarn pack",
"start": "webpack serve --config webpack.dev-server.config.js",
"install:deps": "yarn install --frozen-lockfile && yarn --cwd ../../../",
"build:example": "EXAMPLE=true webpack --config webpack.dev-server.config.js && yarn gen:types"
"build:example": "EXAMPLE=true webpack --config webpack.dev-server.config.js && yarn gen:types",
"size": "yarn build:umd && size-limit"
}
}

View file

@ -4,5 +4,5 @@ if (process.env.NODE_ENV !== ENV.TEST) {
/* global __webpack_public_path__:writable */
__webpack_public_path__ =
window.EXCALIDRAW_ASSET_PATH ||
`https://unpkg.com/${process.env.PKG_NAME}@${process.env.PKG_VERSION}/dist/`;
`https://unpkg.com/${process.env.VITE_PKG_NAME}@${process.env.VITE_PKG_VERSION}/dist/`;
}

View file

@ -47,6 +47,9 @@ module.exports = {
exclude:
/node_modules\/(?!(browser-fs-access|canvas-roundrect-polyfill))/,
use: [
{
loader: "import-meta-loader",
},
{
loader: "ts-loader",
options: {

View file

@ -50,6 +50,9 @@ module.exports = {
/node_modules\/(?!(browser-fs-access|canvas-roundrect-polyfill))/,
use: [
{
loader: "import-meta-loader",
},
{
loader: "ts-loader",
options: {

File diff suppressed because it is too large Load diff

View file

@ -185,8 +185,10 @@ export const exportToSvg = async ({
appState = getDefaultAppState(),
files = {},
exportPadding,
renderEmbeddables,
}: Omit<ExportOpts, "getDimensions"> & {
exportPadding?: number;
renderEmbeddables?: boolean;
}): Promise<SVGSVGElement> => {
const { elements: restoredElements, appState: restoredAppState } = restore(
{ elements, appState },
@ -204,6 +206,7 @@ export const exportToSvg = async ({
exportAppState,
files,
{
renderEmbeddables,
// NOTE as long as we're using the Scene hack, we need to ensure
// we pass the original, uncloned elements when serializing
// so that we keep ids stable. Hence adding the serializeAsJSON helper

View file

@ -27,7 +27,13 @@ import { RoughSVG } from "roughjs/bin/svg";
import { RoughGenerator } from "roughjs/bin/generator";
import { RenderConfig } from "../scene/types";
import { distance, getFontString, getFontFamilyString, isRTL } from "../utils";
import {
distance,
getFontString,
getFontFamilyString,
isRTL,
isTransparent,
} from "../utils";
import { getCornerRadius, isPathALoop, isRightAngle } from "../math";
import rough from "roughjs/bin/rough";
import { AppState, BinaryFiles, Zoom } from "../types";
@ -49,8 +55,12 @@ import {
getBoundTextMaxWidth,
} from "../element/textElement";
import { LinearElementEditor } from "../element/linearElementEditor";
import {
createPlaceholderEmbeddableLabel,
getEmbedLink,
} from "../element/embeddable";
import { getContainingFrame } from "../frame";
import { normalizeLink } from "../data/url";
import { normalizeLink, toValidURL } from "../data/url";
// using a stronger invert (100% vs our regular 93%) and saturate
// as a temp hack to make images in dark theme look closer to original
@ -262,6 +272,7 @@ const drawElementOnCanvas = (
((getContainingFrame(element)?.opacity ?? 100) * element.opacity) / 10000;
switch (element.type) {
case "rectangle":
case "embeddable":
case "diamond":
case "ellipse": {
context.lineJoin = "round";
@ -427,13 +438,13 @@ export const generateRoughOptions = (
switch (element.type) {
case "rectangle":
case "embeddable":
case "diamond":
case "ellipse": {
options.fillStyle = element.fillStyle;
options.fill =
element.backgroundColor === "transparent"
? undefined
: element.backgroundColor;
options.fill = isTransparent(element.backgroundColor)
? undefined
: element.backgroundColor;
if (element.type === "ellipse") {
options.curveFitting = 1;
}
@ -458,6 +469,26 @@ export const generateRoughOptions = (
}
};
const modifyEmbeddableForRoughOptions = (
element: NonDeletedExcalidrawElement,
isExporting: boolean,
) => {
if (
element.type === "embeddable" &&
(isExporting || !element.validated) &&
isTransparent(element.backgroundColor) &&
isTransparent(element.strokeColor)
) {
return {
...element,
roughness: 0,
backgroundColor: "#d3d3d3",
fillStyle: "solid",
} as const;
}
return element;
};
/**
* Generates the element's shape and puts it into the cache.
* @param element
@ -466,8 +497,9 @@ export const generateRoughOptions = (
const generateElementShape = (
element: NonDeletedExcalidrawElement,
generator: RoughGenerator,
isExporting: boolean = false,
) => {
let shape = shapeCache.get(element);
let shape = isExporting ? undefined : shapeCache.get(element);
// `null` indicates no rc shape applicable for this element type
// (= do not generate anything)
@ -475,7 +507,11 @@ const generateElementShape = (
elementWithCanvasCache.delete(element);
switch (element.type) {
case "rectangle": {
case "rectangle":
case "embeddable": {
// this is for rendering the stroke/bg of the embeddable, especially
// when the src url is not set
if (element.roundness) {
const w = element.width;
const h = element.height;
@ -486,7 +522,10 @@ const generateElementShape = (
} Q ${w} ${h}, ${w - r} ${h} L ${r} ${h} Q 0 ${h}, 0 ${
h - r
} L 0 ${r} Q 0 0, ${r} 0`,
generateRoughOptions(element, true),
generateRoughOptions(
modifyEmbeddableForRoughOptions(element, isExporting),
true,
),
);
} else {
shape = generator.rectangle(
@ -494,7 +533,10 @@ const generateElementShape = (
0,
element.width,
element.height,
generateRoughOptions(element),
generateRoughOptions(
modifyEmbeddableForRoughOptions(element, isExporting),
false,
),
);
}
setShapeForElement(element, shape);
@ -873,7 +915,7 @@ const drawElementFromCanvas = (
);
if (
process.env.REACT_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX ===
import.meta.env.VITE_APP_DEBUG_ENABLE_TEXT_CONTAINER_BOUNDING_BOX ===
"true" &&
hasBoundTextElement(element)
) {
@ -996,8 +1038,9 @@ export const renderElement = (
case "line":
case "arrow":
case "image":
case "text": {
generateElementShape(element, generator);
case "text":
case "embeddable": {
generateElementShape(element, generator, renderConfig.isExporting);
if (renderConfig.isExporting) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
const cx = (x1 + x2) / 2 + renderConfig.scrollX;
@ -1180,7 +1223,9 @@ export const renderElementToSvg = (
offsetY: number,
exportWithDarkMode?: boolean,
exportingFrameId?: string | null,
renderEmbeddables?: boolean,
) => {
const offset = { x: offsetX, y: offsetY };
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
let cx = (x2 - x1) / 2 - (element.x - x1);
let cy = (y2 - y1) / 2 - (element.y - y1);
@ -1253,6 +1298,106 @@ export const renderElementToSvg = (
g ? root.appendChild(g) : root.appendChild(node);
break;
}
case "embeddable": {
// render placeholder rectangle
generateElementShape(element, generator, true);
const node = roughSVGDrawWithPrecision(
rsvg,
getShapeForElement(element)!,
MAX_DECIMALS_FOR_SVG_EXPORT,
);
const opacity = element.opacity / 100;
if (opacity !== 1) {
node.setAttribute("stroke-opacity", `${opacity}`);
node.setAttribute("fill-opacity", `${opacity}`);
}
node.setAttribute("stroke-linecap", "round");
node.setAttribute(
"transform",
`translate(${offsetX || 0} ${
offsetY || 0
}) rotate(${degree} ${cx} ${cy})`,
);
root.appendChild(node);
const label: ExcalidrawElement =
createPlaceholderEmbeddableLabel(element);
renderElementToSvg(
label,
rsvg,
root,
files,
label.x + offset.x - element.x,
label.y + offset.y - element.y,
exportWithDarkMode,
exportingFrameId,
renderEmbeddables,
);
// render embeddable element + iframe
const embeddableNode = roughSVGDrawWithPrecision(
rsvg,
getShapeForElement(element)!,
MAX_DECIMALS_FOR_SVG_EXPORT,
);
embeddableNode.setAttribute("stroke-linecap", "round");
embeddableNode.setAttribute(
"transform",
`translate(${offsetX || 0} ${
offsetY || 0
}) rotate(${degree} ${cx} ${cy})`,
);
while (embeddableNode.firstChild) {
embeddableNode.removeChild(embeddableNode.firstChild);
}
const radius = getCornerRadius(
Math.min(element.width, element.height),
element,
);
const embedLink = getEmbedLink(toValidURL(element.link || ""));
// if rendering embeddables explicitly disabled or
// embedding documents via srcdoc (which doesn't seem to work for SVGs)
// replace with a link instead
if (renderEmbeddables === false || embedLink?.type === "document") {
const anchorTag = svgRoot.ownerDocument!.createElementNS(SVG_NS, "a");
anchorTag.setAttribute("href", normalizeLink(element.link || ""));
anchorTag.setAttribute("target", "_blank");
anchorTag.setAttribute("rel", "noopener noreferrer");
anchorTag.style.borderRadius = `${radius}px`;
embeddableNode.appendChild(anchorTag);
} else {
const foreignObject = svgRoot.ownerDocument!.createElementNS(
SVG_NS,
"foreignObject",
);
foreignObject.style.width = `${element.width}px`;
foreignObject.style.height = `${element.height}px`;
foreignObject.style.border = "none";
const div = foreignObject.ownerDocument!.createElementNS(SVG_NS, "div");
div.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
div.style.width = "100%";
div.style.height = "100%";
const iframe = div.ownerDocument!.createElement("iframe");
iframe.src = embedLink?.link ?? "";
iframe.style.width = "100%";
iframe.style.height = "100%";
iframe.style.border = "none";
iframe.style.borderRadius = `${radius}px`;
iframe.style.top = "0";
iframe.style.left = "0";
iframe.allowFullscreen = true;
div.appendChild(iframe);
foreignObject.appendChild(div);
embeddableNode.appendChild(foreignObject);
}
root.appendChild(embeddableNode);
break;
}
case "line":
case "arrow": {
const boundText = getBoundTextElement(element);

View file

@ -62,7 +62,15 @@ import {
EXTERNAL_LINK_IMG,
getLinkHandleFromCoords,
} from "../element/Hyperlink";
import { isFrameElement, isLinearElement } from "../element/typeChecks";
import {
isEmbeddableElement,
isFrameElement,
isLinearElement,
} from "../element/typeChecks";
import {
isEmbeddableOrFrameLabel,
createPlaceholderEmbeddableLabel,
} from "../element/embeddable";
import {
elementOverlapsWithFrame,
getTargetFrame,
@ -154,23 +162,52 @@ const fillCircle = (
const strokeGrid = (
context: CanvasRenderingContext2D,
gridSize: number,
offsetX: number,
offsetY: number,
scrollX: number,
scrollY: number,
zoom: Zoom,
width: number,
height: number,
) => {
const BOLD_LINE_FREQUENCY = 5;
enum GridLineColor {
Bold = "#cccccc",
Regular = "#e5e5e5",
}
const offsetX =
-Math.round(zoom.value / gridSize) * gridSize + (scrollX % gridSize);
const offsetY =
-Math.round(zoom.value / gridSize) * gridSize + (scrollY % gridSize);
const lineWidth = Math.min(1 / zoom.value, 1);
const spaceWidth = 1 / zoom.value;
const lineDash = [lineWidth * 3, spaceWidth + (lineWidth + spaceWidth)];
context.save();
context.strokeStyle = "rgba(0,0,0,0.1)";
context.beginPath();
context.lineWidth = lineWidth;
for (let x = offsetX; x < offsetX + width + gridSize * 2; x += gridSize) {
const isBold =
Math.round(x - scrollX) % (BOLD_LINE_FREQUENCY * gridSize) === 0;
context.beginPath();
context.setLineDash(isBold ? [] : lineDash);
context.strokeStyle = isBold ? GridLineColor.Bold : GridLineColor.Regular;
context.moveTo(x, offsetY - gridSize);
context.lineTo(x, offsetY + height + gridSize * 2);
context.stroke();
}
for (let y = offsetY; y < offsetY + height + gridSize * 2; y += gridSize) {
const isBold =
Math.round(y - scrollY) % (BOLD_LINE_FREQUENCY * gridSize) === 0;
context.beginPath();
context.setLineDash(isBold ? [] : lineDash);
context.strokeStyle = isBold ? GridLineColor.Bold : GridLineColor.Regular;
context.moveTo(offsetX - gridSize, y);
context.lineTo(offsetX + width + gridSize * 2, y);
context.stroke();
}
context.stroke();
context.restore();
};
@ -417,12 +454,9 @@ export const _renderScene = ({
strokeGrid(
context,
appState.gridSize,
-Math.ceil(renderConfig.zoom.value / appState.gridSize) *
appState.gridSize +
(renderConfig.scrollX % appState.gridSize),
-Math.ceil(renderConfig.zoom.value / appState.gridSize) *
appState.gridSize +
(renderConfig.scrollY % appState.gridSize),
renderConfig.scrollX,
renderConfig.scrollY,
renderConfig.zoom,
normalizedCanvasWidth / renderConfig.zoom.value,
normalizedCanvasHeight / renderConfig.zoom.value,
);
@ -460,48 +494,102 @@ export const _renderScene = ({
let editingLinearElement: NonDeleted<ExcalidrawLinearElement> | undefined =
undefined;
visibleElements.forEach((element) => {
try {
// - when exporting the whole canvas, we DO NOT apply clipping
// - when we are exporting a particular frame, apply clipping
// if the containing frame is not selected, apply clipping
const frameId = element.frameId || appState.frameToHighlight?.id;
visibleElements
.filter((el) => !isEmbeddableOrFrameLabel(el))
.forEach((element) => {
try {
// - when exporting the whole canvas, we DO NOT apply clipping
// - when we are exporting a particular frame, apply clipping
// if the containing frame is not selected, apply clipping
const frameId = element.frameId || appState.frameToHighlight?.id;
if (
frameId &&
((renderConfig.isExporting && isOnlyExportingSingleFrame(elements)) ||
(!renderConfig.isExporting &&
appState.frameRendering.enabled &&
appState.frameRendering.clip))
) {
context.save();
if (
frameId &&
((renderConfig.isExporting &&
isOnlyExportingSingleFrame(elements)) ||
(!renderConfig.isExporting &&
appState.frameRendering.enabled &&
appState.frameRendering.clip))
) {
context.save();
const frame = getTargetFrame(element, appState);
const frame = getTargetFrame(element, appState);
if (frame && isElementInFrame(element, elements, appState)) {
frameClip(frame, context, renderConfig);
if (frame && isElementInFrame(element, elements, appState)) {
frameClip(frame, context, renderConfig);
}
renderElement(element, rc, context, renderConfig, appState);
context.restore();
} else {
renderElement(element, rc, context, renderConfig, appState);
}
renderElement(element, rc, context, renderConfig, appState);
context.restore();
} else {
renderElement(element, rc, context, renderConfig, appState);
}
// Getting the element using LinearElementEditor during collab mismatches version - being one head of visible elements due to
// ShapeCache returns empty hence making sure that we get the
// correct element from visible elements
if (appState.editingLinearElement?.elementId === element.id) {
if (element) {
editingLinearElement =
element as NonDeleted<ExcalidrawLinearElement>;
// Getting the element using LinearElementEditor during collab mismatches version - being one head of visible elements due to
// ShapeCache returns empty hence making sure that we get the
// correct element from visible elements
if (appState.editingLinearElement?.elementId === element.id) {
if (element) {
editingLinearElement =
element as NonDeleted<ExcalidrawLinearElement>;
}
}
if (!isExporting) {
renderLinkIcon(element, context, appState);
}
} catch (error: any) {
console.error(error);
}
if (!isExporting) {
renderLinkIcon(element, context, appState);
});
// render embeddables on top
visibleElements
.filter((el) => isEmbeddableOrFrameLabel(el))
.forEach((element) => {
try {
const render = () => {
renderElement(element, rc, context, renderConfig, appState);
if (
isEmbeddableElement(element) &&
(isExporting || !element.validated) &&
element.width &&
element.height
) {
const label = createPlaceholderEmbeddableLabel(element);
renderElement(label, rc, context, renderConfig, appState);
}
if (!isExporting) {
renderLinkIcon(element, context, appState);
}
};
// - when exporting the whole canvas, we DO NOT apply clipping
// - when we are exporting a particular frame, apply clipping
// if the containing frame is not selected, apply clipping
const frameId = element.frameId || appState.frameToHighlight?.id;
if (
frameId &&
((renderConfig.isExporting &&
isOnlyExportingSingleFrame(elements)) ||
(!renderConfig.isExporting &&
appState.frameRendering.enabled &&
appState.frameRendering.clip))
) {
context.save();
const frame = getTargetFrame(element, appState);
if (frame && isElementInFrame(element, elements, appState)) {
frameClip(frame, context, renderConfig);
}
render();
context.restore();
} else {
render();
}
} catch (error: any) {
console.error(error);
}
} catch (error: any) {
console.error(error);
}
});
});
if (editingLinearElement) {
renderLinearPointHandles(
@ -640,10 +728,13 @@ export const _renderScene = ({
dashed: !!renderConfig.remoteSelectedElementIds[element.id],
cx,
cy,
activeEmbeddable:
appState.activeEmbeddable?.element === element &&
appState.activeEmbeddable.state === "active",
});
}
return acc;
}, [] as { angle: number; elementX1: number; elementY1: number; elementX2: number; elementY2: number; selectionColors: string[]; dashed?: boolean; cx: number; cy: number }[]);
}, [] as { angle: number; elementX1: number; elementY1: number; elementX2: number; elementY2: number; selectionColors: string[]; dashed?: boolean; cx: number; cy: number; activeEmbeddable: boolean }[]);
const addSelectionForGroupId = (groupId: GroupId) => {
const groupElements = getElementsInGroup(elements, groupId);
@ -659,6 +750,7 @@ export const _renderScene = ({
dashed: true,
cx: elementX1 + (elementX2 - elementX1) / 2,
cy: elementY1 + (elementY2 - elementY1) / 2,
activeEmbeddable: false,
});
};
@ -1000,6 +1092,7 @@ const renderSelectionBorder = (
dashed?: boolean;
cx: number;
cy: number;
activeEmbeddable: boolean;
},
padding = DEFAULT_SPACING * 2,
) => {
@ -1013,6 +1106,7 @@ const renderSelectionBorder = (
cx,
cy,
dashed,
activeEmbeddable,
} = elementProperties;
const elementWidth = elementX2 - elementX1;
const elementHeight = elementY2 - elementY1;
@ -1023,7 +1117,7 @@ const renderSelectionBorder = (
context.save();
context.translate(renderConfig.scrollX, renderConfig.scrollY);
context.lineWidth = 1 / renderConfig.zoom.value;
context.lineWidth = (activeEmbeddable ? 4 : 1) / renderConfig.zoom.value;
const count = selectionColors.length;
for (let index = 0; index < count; ++index) {
@ -1084,6 +1178,7 @@ const renderBindingHighlightForBindableElement = (
case "rectangle":
case "text":
case "image":
case "embeddable":
case "frame":
strokeRectWithRotation(
context,
@ -1178,6 +1273,7 @@ const renderElementsBoxHighlight = (
dashed: false,
cx: elementX1 + (elementX2 - elementX1) / 2,
cy: elementY1 + (elementY2 - elementY1) / 2,
activeEmbeddable: false,
};
};
@ -1326,11 +1422,13 @@ export const renderSceneToSvg = (
offsetY = 0,
exportWithDarkMode = false,
exportingFrameId = null,
renderEmbeddables,
}: {
offsetX?: number;
offsetY?: number;
exportWithDarkMode?: boolean;
exportingFrameId?: string | null;
renderEmbeddables?: boolean;
} = {},
) => {
if (!svgRoot) {
@ -1338,22 +1436,48 @@ export const renderSceneToSvg = (
}
// render elements
elements.forEach((element) => {
if (!element.isDeleted) {
try {
renderElementToSvg(
element,
rsvg,
svgRoot,
files,
element.x + offsetX,
element.y + offsetY,
exportWithDarkMode,
exportingFrameId,
);
} catch (error: any) {
console.error(error);
elements
.filter((el) => !isEmbeddableOrFrameLabel(el))
.forEach((element) => {
if (!element.isDeleted) {
try {
renderElementToSvg(
element,
rsvg,
svgRoot,
files,
element.x + offsetX,
element.y + offsetY,
exportWithDarkMode,
exportingFrameId,
renderEmbeddables,
);
} catch (error: any) {
console.error(error);
}
}
}
});
});
// render embeddables on top
elements
.filter((el) => isEmbeddableElement(el))
.forEach((element) => {
if (!element.isDeleted) {
try {
renderElementToSvg(
element,
rsvg,
svgRoot,
files,
element.x + offsetX,
element.y + offsetY,
exportWithDarkMode,
exportingFrameId,
renderEmbeddables,
);
} catch (error: any) {
console.error(error);
}
}
});
};

View file

@ -11,6 +11,9 @@ import {
} from "../element";
import { LinearElementEditor } from "../element/linearElementEditor";
import { isFrameElement } from "../element/typeChecks";
import { getSelectedElements } from "./selection";
import { AppState } from "../types";
import { Assert, SameType } from "../utility-types";
type ElementIdKey = InstanceType<typeof LinearElementEditor>["elementId"];
type ElementKey = ExcalidrawElement | ElementIdKey;
@ -18,6 +21,31 @@ type ElementKey = ExcalidrawElement | ElementIdKey;
type SceneStateCallback = () => void;
type SceneStateCallbackRemover = () => void;
type SelectionHash = string & { __brand: "selectionHash" };
const hashSelectionOpts = (
opts: Parameters<InstanceType<typeof Scene>["getSelectedElements"]>[0],
) => {
const keys = ["includeBoundTextElement", "includeElementsInFrames"] as const;
type HashableKeys = Omit<typeof opts, "selectedElementIds" | "elements">;
// just to ensure we're hashing all expected keys
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type _ = Assert<
SameType<
Required<HashableKeys>,
Pick<Required<HashableKeys>, typeof keys[number]>
>
>;
let hash = "";
for (const key of keys) {
hash += `${key}:${opts[key] ? "1" : "0"}`;
}
return hash as SelectionHash;
};
// ideally this would be a branded type but it'd be insanely hard to work with
// in our codebase
export type ExcalidrawElementsIncludingDeleted = readonly ExcalidrawElement[];
@ -68,6 +96,15 @@ class Scene {
private nonDeletedFrames: readonly NonDeleted<ExcalidrawFrameElement>[] = [];
private frames: readonly ExcalidrawFrameElement[] = [];
private elementsMap = new Map<ExcalidrawElement["id"], ExcalidrawElement>();
private selectedElementsCache: {
selectedElementIds: AppState["selectedElementIds"] | null;
elements: readonly NonDeletedExcalidrawElement[] | null;
cache: Map<SelectionHash, NonDeletedExcalidrawElement[]>;
} = {
selectedElementIds: null,
elements: null,
cache: new Map(),
};
getElementsIncludingDeleted() {
return this.elements;
@ -81,6 +118,52 @@ class Scene {
return this.frames;
}
getSelectedElements(opts: {
// NOTE can be ommitted by making Scene constructor require App instance
selectedElementIds: AppState["selectedElementIds"];
/**
* for specific cases where you need to use elements not from current
* scene state. This in effect will likely result in cache-miss, and
* the cache won't be updated in this case.
*/
elements?: readonly ExcalidrawElement[];
// selection-related options
includeBoundTextElement?: boolean;
includeElementsInFrames?: boolean;
}): NonDeleted<ExcalidrawElement>[] {
const hash = hashSelectionOpts(opts);
const elements = opts?.elements || this.nonDeletedElements;
if (
this.selectedElementsCache.elements === elements &&
this.selectedElementsCache.selectedElementIds === opts.selectedElementIds
) {
const cached = this.selectedElementsCache.cache.get(hash);
if (cached) {
return cached;
}
} else if (opts?.elements == null) {
// if we're operating on latest scene elements and the cache is not
// storing the latest elements, clear the cache
this.selectedElementsCache.cache.clear();
}
const selectedElements = getSelectedElements(
elements,
{ selectedElementIds: opts.selectedElementIds },
opts,
);
// cache only if we're not using custom elements
if (opts?.elements == null) {
this.selectedElementsCache.selectedElementIds = opts.selectedElementIds;
this.selectedElementsCache.elements = this.nonDeletedElements;
this.selectedElementsCache.cache.set(hash, selectedElements);
}
return selectedElements;
}
getNonDeletedFrames(): readonly NonDeleted<ExcalidrawFrameElement>[] {
return this.nonDeletedFrames;
}
@ -168,11 +251,21 @@ class Scene {
}
destroy() {
this.nonDeletedElements = [];
this.elements = [];
this.nonDeletedFrames = [];
this.frames = [];
this.elementsMap.clear();
this.selectedElementsCache.selectedElementIds = null;
this.selectedElementsCache.elements = null;
this.selectedElementsCache.cache.clear();
Scene.sceneMapById.forEach((scene, elementKey) => {
if (scene === this) {
Scene.sceneMapById.delete(elementKey);
}
});
// done not for memory leaks, but to guard against possible late fires
// (I guess?)
this.callbacks.clear();

View file

@ -1,7 +1,12 @@
import { NonDeletedExcalidrawElement } from "../element/types";
import { isEmbeddableElement } from "../element/typeChecks";
import {
ExcalidrawEmbeddableElement,
NonDeletedExcalidrawElement,
} from "../element/types";
export const hasBackground = (type: string) =>
type === "rectangle" ||
type === "embeddable" ||
type === "ellipse" ||
type === "diamond" ||
type === "line" ||
@ -12,6 +17,7 @@ export const hasStrokeColor = (type: string) =>
export const hasStrokeWidth = (type: string) =>
type === "rectangle" ||
type === "embeddable" ||
type === "ellipse" ||
type === "diamond" ||
type === "freedraw" ||
@ -20,6 +26,7 @@ export const hasStrokeWidth = (type: string) =>
export const hasStrokeStyle = (type: string) =>
type === "rectangle" ||
type === "embeddable" ||
type === "ellipse" ||
type === "diamond" ||
type === "arrow" ||
@ -27,6 +34,7 @@ export const hasStrokeStyle = (type: string) =>
export const canChangeRoundness = (type: string) =>
type === "rectangle" ||
type === "embeddable" ||
type === "arrow" ||
type === "line" ||
type === "diamond";
@ -61,9 +69,21 @@ export const getElementsAtPosition = (
elements: readonly NonDeletedExcalidrawElement[],
isAtPositionFn: (element: NonDeletedExcalidrawElement) => boolean,
) => {
const embeddables: ExcalidrawEmbeddableElement[] = [];
// The parameter elements comes ordered from lower z-index to higher.
// We want to preserve that order on the returned array.
return elements.filter(
(element) => !element.isDeleted && isAtPositionFn(element),
);
// Exception being embeddables which should be on top of everything else in
// terms of hit testing.
const elsAtPos = elements.filter((element) => {
const hit = !element.isDeleted && isAtPositionFn(element);
if (hit) {
if (isEmbeddableElement(element)) {
embeddables.push(element);
return false;
}
return true;
}
return false;
});
return elsAtPos.concat(embeddables);
};

View file

@ -96,6 +96,7 @@ export const exportToSvg = async (
files: BinaryFiles | null,
opts?: {
serializeAsJSON?: () => string;
renderEmbeddables?: boolean;
},
): Promise<SVGSVGElement> => {
const {
@ -132,12 +133,13 @@ export const exportToSvg = async (
}
let assetPath = "https://excalidraw.com/";
// Asset path needs to be determined only when using package
if (process.env.IS_EXCALIDRAW_NPM_PACKAGE) {
if (import.meta.env.VITE_IS_EXCALIDRAW_NPM_PACKAGE) {
assetPath =
window.EXCALIDRAW_ASSET_PATH ||
`https://unpkg.com/${process.env.PKG_NAME}@${process.env.PKG_VERSION}`;
`https://unpkg.com/${import.meta.env.VITE_PKG_NAME}@${
import.meta.env.PKG_VERSION
}`;
if (assetPath?.startsWith("/")) {
assetPath = assetPath.replace("/", `${window.location.origin}/`);
@ -212,6 +214,7 @@ export const exportToSvg = async (
offsetY,
exportWithDarkMode: appState.exportWithDarkMode,
exportingFrameId: exportingFrame?.id || null,
renderEmbeddables: opts?.renderEmbeddables,
});
return svgRoot;

View file

@ -1,147 +0,0 @@
/// <reference lib="webworker" />
/* eslint-disable no-restricted-globals */
// This service worker can be customized!
// See https://developers.google.com/web/tools/workbox/modules
// for the list of available Workbox modules, or add any other
// code you'd like.
// You can also remove this file if you'd prefer not to use a
// service worker, and the Workbox build step will be skipped.
import { clientsClaim } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute, createHandlerBoundToURL } from "workbox-precaching";
import { registerRoute } from "workbox-routing";
import { CacheFirst, StaleWhileRevalidate } from "workbox-strategies";
declare const self: ServiceWorkerGlobalScope;
clientsClaim();
// Precache assets generated by your build process.
//
// Their URLs are injected into the __WB_MANIFEST during build (by workbox).
//
// This variable must be present somewhere in your service worker file,
// even if you decide not to use precaching. See https://cra.link/PWA.
//
// We don't want to precache i18n files so we filter them out
// (normally this should be configured in a webpack workbox plugin, but we don't
// have access to it in CRA) — this is because all users will use at most
// one or two languages, so there's no point fetching all of them. (They'll
// be cached as you load them.)
const manifest = self.__WB_MANIFEST.filter((entry) => {
return !/locales\/[\w-]+json/.test(
typeof entry === "string" ? entry : entry.url,
);
});
precacheAndRoute(manifest);
// Set up App Shell-style routing, so that all navigation requests
// are fulfilled with your index.html shell. Learn more at
// https://developer.chrome.com/docs/workbox/app-shell-model/
//
// below is copied verbatim from CRA@5
const fileExtensionRegexp = new RegExp("/[^/?]+\\.[^/]+$");
registerRoute(
// Return false to exempt requests from being fulfilled by index.html.
({ request, url }: { request: Request; url: URL }) => {
// If this isn't a navigation, skip.
if (request.mode !== "navigate") {
return false;
}
// If this is a URL that starts with /_, skip.
if (url.pathname.startsWith("/_")) {
return false;
}
// If this looks like a URL for a resource, because it contains
// a file extension, skip.
if (url.pathname.match(fileExtensionRegexp)) {
return false;
}
// Return true to signal that we want to use the handler.
return true;
},
createHandlerBoundToURL(`${process.env.PUBLIC_URL}/index.html`),
);
// Cache resources that aren't being precached
// -----------------------------------------------------------------------------
registerRoute(
new RegExp("/fonts.css"),
new StaleWhileRevalidate({
cacheName: "fonts",
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
}),
);
// since we serve fonts from, don't forget to append new ?v= param when
// updating fonts (glyphs) without changing the filename
registerRoute(
new RegExp("/.+.(ttf|woff2|otf)"),
new CacheFirst({
cacheName: "fonts",
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({
maxEntries: 50,
// 90 days
maxAgeSeconds: 7776000000,
}),
],
}),
);
registerRoute(
new RegExp("/locales\\/[\\w-]+json"),
// Customize this strategy as needed, e.g., by changing to CacheFirst.
new CacheFirst({
cacheName: "locales",
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({
maxEntries: 50,
// 30 days
maxAgeSeconds: 2592000000,
}),
],
}),
);
// -----------------------------------------------------------------------------
self.addEventListener("fetch", (event) => {
if (
event.request.method === "POST" &&
event.request.url.endsWith("/web-share-target")
) {
return event.respondWith(
(async () => {
const formData = await event.request.formData();
const file = formData.get("file");
const webShareTargetCache = await caches.open("web-share-target");
await webShareTargetCache.put("shared-file", new Response(file));
return Response.redirect("/?web-share-target", 303);
})(),
);
}
});
// This allows the web app to trigger skipWaiting via
// registration.waiting.postMessage({type: 'SKIP_WAITING'})
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});

View file

@ -1,162 +0,0 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
),
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export const register = (config?: Config) => {
if (
(process.env.NODE_ENV === "production" ||
process.env.REACT_APP_DEV_ENABLE_SW?.toLowerCase() === "true") &&
"serviceWorker" in navigator
) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener("load", () => {
const isWebexLP = window.location.pathname.startsWith("/webex");
if (isWebexLP) {
unregister(() => {
window.location.reload();
});
return false;
}
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.info(
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://bit.ly/CRA-PWA",
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
};
const registerValidSW = (swUrl: string, config?: Config) => {
navigator.serviceWorker
.register(swUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.info(
"New content is available and will be used when all tabs for this page are closed.",
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.info("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch((error) => {
console.error("Error during service worker registration:", error);
});
};
const checkValidServiceWorker = (swUrl: string, config?: Config) => {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { "Service-Worker": "script" },
})
.then((response) => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get("content-type");
if (
response.status === 404 ||
(contentType != null && contentType.indexOf("javascript") === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch((error) => {
console.info(
"No internet connection found. App is running in offline mode.",
error.message,
);
});
};
export const unregister = (callback?: () => void) => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
return registration.unregister();
})
.then(() => {
callback?.();
})
.catch((error) => {
console.error(error.message);
});
}
};

View file

@ -1,19 +1,16 @@
// vitest.setup.ts
import "vitest-canvas-mock";
import "@testing-library/jest-dom";
import "jest-canvas-mock";
import dotenv from "dotenv";
import { vi } from "vitest";
import polyfill from "./polyfill";
require("fake-indexeddb/auto");
polyfill();
// jest doesn't know of .env.development so we need to init it ourselves
dotenv.config({
path: require("path").resolve(__dirname, "../.env.development"),
});
jest.mock("nanoid", () => {
vi.mock("nanoid", () => {
return {
nanoid: jest.fn(() => "test-id"),
nanoid: vi.fn(() => "test-id"),
};
});
// ReactDOM is located inside index.tsx file

View file

@ -11,23 +11,23 @@ describe("Test MobileMenu", () => {
const { h } = window;
const dimensions = { height: 400, width: 800 };
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
beforeEach(async () => {
await render(<ExcalidrawApp />);
//@ts-ignore
h.app.refreshDeviceState(h.app.excalidrawContainerRef.current!);
});
beforeAll(() => {
mockBoundingClientRect(dimensions);
});
afterAll(() => {
restoreOriginalGetBoundingClientRect();
});
it("should set device correctly", () => {
expect(h.app.device).toMatchInlineSnapshot(`
Object {
{
"canDeviceFitSidebar": false,
"isLandscape": true,
"isMobile": true,
@ -39,7 +39,6 @@ describe("Test MobileMenu", () => {
it("should initialize with welcome screen and hide once user interacts", async () => {
expect(document.querySelector(".welcome-screen-center")).toMatchSnapshot();
UI.clickTool("rectangle");
expect(document.querySelector(".welcome-screen-center")).toBeNull();
});

View file

@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Test MobileMenu should initialize with welcome screen and hide once user interacts 1`] = `
exports[`Test MobileMenu > should initialize with welcome screen and hide once user interacts 1`] = `
<div
class="welcome-screen-center"
>

View file

@ -1,15 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`tryParseSpreadsheet works for numbers with comma in them 1`] = `
Object {
"spreadsheet": Object {
"labels": Array [
exports[`tryParseSpreadsheet > works for numbers with comma in them 1`] = `
{
"spreadsheet": {
"labels": [
"Week 1",
"Week 2",
"Week 3",
],
"title": "Users",
"values": Array [
"values": [
814,
10301,
4264,

File diff suppressed because it is too large Load diff

View file

@ -1,9 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Test dragCreate add element to the scene when pointer dragging long enough arrow 1`] = `1`;
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > arrow 1`] = `1`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough arrow 2`] = `
Object {
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > arrow 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
@ -11,7 +11,7 @@ Object {
"endBinding": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -19,18 +19,18 @@ Object {
"link": null,
"locked": false,
"opacity": 100,
"points": Array [
Array [
"points": [
[
0,
0,
],
Array [
[
30,
50,
],
],
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 2,
},
"seed": 337897,
@ -49,16 +49,16 @@ Object {
}
`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough diamond 1`] = `1`;
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > diamond 1`] = `1`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough diamond 2`] = `
Object {
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > diamond 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -66,7 +66,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 2,
},
"seed": 337897,
@ -83,16 +83,16 @@ Object {
}
`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough ellipse 1`] = `1`;
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > ellipse 1`] = `1`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough ellipse 2`] = `
Object {
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > ellipse 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -100,7 +100,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 2,
},
"seed": 337897,
@ -117,8 +117,8 @@ Object {
}
`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough line 1`] = `
Object {
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > line 1`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
@ -126,7 +126,7 @@ Object {
"endBinding": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -134,18 +134,18 @@ Object {
"link": null,
"locked": false,
"opacity": 100,
"points": Array [
Array [
"points": [
[
0,
0,
],
Array [
[
30,
50,
],
],
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 2,
},
"seed": 337897,
@ -164,16 +164,16 @@ Object {
}
`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough rectangle 1`] = `1`;
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > rectangle 1`] = `1`;
exports[`Test dragCreate add element to the scene when pointer dragging long enough rectangle 2`] = `
Object {
exports[`Test dragCreate > add element to the scene when pointer dragging long enough > rectangle 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -181,7 +181,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 337897,

File diff suppressed because one or more lines are too long

View file

@ -1,11 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Test Linear Elements Test bound text element should match styles for text editor 1`] = `
exports[`Test Linear Elements > Test bound text element > should match styles for text editor 1`] = `
<textarea
class="excalidraw-wysiwyg"
data-type="wysiwyg"
dir="auto"
style="position: absolute; display: inline-block; min-height: 1em; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; filter: var(--theme-filter); max-height: -7.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Virgil, Segoe UI Emoji;"
style="position: absolute; display: inline-block; min-height: 1em; backface-visibility: hidden; margin: 0px; padding: 0px; border: 0px; outline: 0; resize: none; background: transparent; overflow: hidden; z-index: var(--zIndex-wysiwyg); word-break: break-word; white-space: pre-wrap; overflow-wrap: break-word; box-sizing: content-box; width: 10.5px; height: 25px; left: 35px; top: 7.5px; transform: translate(0px, 0px) scale(1) rotate(0deg); text-align: center; vertical-align: middle; color: rgb(30, 30, 30); opacity: 1; filter: var(--theme-filter); max-height: -7.5px; font: Emoji 20px 20px; line-height: 1.25; font-family: Virgil, Segoe UI Emoji;"
tabindex="0"
wrap="off"
/>

View file

@ -1,13 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`duplicate element on move when ALT is clicked rectangle 1`] = `
Object {
exports[`duplicate element on move when ALT is clicked > rectangle 1`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0_copy",
"isDeleted": false,
@ -15,7 +15,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 401146281,
@ -32,14 +32,14 @@ Object {
}
`;
exports[`duplicate element on move when ALT is clicked rectangle 2`] = `
Object {
exports[`duplicate element on move when ALT is clicked > rectangle 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -47,7 +47,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 337897,
@ -64,14 +64,14 @@ Object {
}
`;
exports[`move element rectangle 1`] = `
Object {
exports[`move element > rectangle 1`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 50,
"id": "id0",
"isDeleted": false,
@ -79,7 +79,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 337897,
@ -96,19 +96,19 @@ Object {
}
`;
exports[`move element rectangles with binding arrow 1`] = `
Object {
exports[`move element > rectangles with binding arrow 1`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": Array [
Object {
"boundElements": [
{
"id": "id2",
"type": "arrow",
},
],
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 100,
"id": "id0",
"isDeleted": false,
@ -116,7 +116,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 337897,
@ -133,19 +133,19 @@ Object {
}
`;
exports[`move element rectangles with binding arrow 2`] = `
Object {
exports[`move element > rectangles with binding arrow 2`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": Array [
Object {
"boundElements": [
{
"id": "id2",
"type": "arrow",
},
],
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 300,
"id": "id1",
"isDeleted": false,
@ -153,7 +153,7 @@ Object {
"locked": false,
"opacity": 100,
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 3,
},
"seed": 449462985,
@ -170,20 +170,20 @@ Object {
}
`;
exports[`move element rectangles with binding arrow 3`] = `
Object {
exports[`move element > rectangles with binding arrow 3`] = `
{
"angle": 0,
"backgroundColor": "transparent",
"boundElements": null,
"endArrowhead": null,
"endBinding": Object {
"endBinding": {
"elementId": "id1",
"focus": -0.46666666666666673,
"gap": 10,
},
"fillStyle": "hachure",
"frameId": null,
"groupIds": Array [],
"groupIds": [],
"height": 81.48231043525051,
"id": "id2",
"isDeleted": false,
@ -191,23 +191,23 @@ Object {
"link": null,
"locked": false,
"opacity": 100,
"points": Array [
Array [
"points": [
[
0,
0,
],
Array [
[
81,
81.48231043525051,
],
],
"roughness": 1,
"roundness": Object {
"roundness": {
"type": 2,
},
"seed": 401146281,
"startArrowhead": null,
"startBinding": Object {
"startBinding": {
"elementId": "id0",
"focus": -0.6000000000000001,
"gap": 10,

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