Compare commits

..

4 Commits

Author SHA1 Message Date
barnabasmolnar 4330f3ec9d Enhanced animations API. 2026-06-04 19:13:24 +02:00
barnabasmolnar d5aad6202d tweak fade api a little bit 2026-06-03 19:15:52 +02:00
barnabasmolnar db73e30eae tweak demo 2026-06-03 16:04:37 +02:00
barnabasmolnar f472af04a9 [WIP] Initial implem of fade animating elements. 2026-06-02 19:06:32 +02:00
18 changed files with 774 additions and 72 deletions
@@ -1,4 +1,5 @@
"use client";
import * as excalidrawLib from "@excalidraw/excalidraw";
import { Excalidraw } from "@excalidraw/excalidraw";
@@ -13,6 +14,7 @@ const ExcalidrawWrapper: React.FC = () => {
appTitle={"Excalidraw with Nextjs Example"}
useCustom={(api: any, args?: any[]) => {}}
excalidrawLib={excalidrawLib}
showFadeDemo={true}
>
<Excalidraw />
</App>
@@ -70,6 +70,7 @@ export interface AppProps {
customArgs?: any[];
children: React.ReactNode;
excalidrawLib: typeof TExcalidraw;
showFadeDemo?: boolean;
}
export default function ExampleApp({
@@ -78,6 +79,7 @@ export default function ExampleApp({
customArgs,
children,
excalidrawLib,
showFadeDemo = false,
}: AppProps) {
const {
exportToCanvas,
@@ -116,6 +118,19 @@ export default function ExampleApp({
{},
);
const [comment, setComment] = useState<Comment | null>(null);
const [hideAllForFadeDemo, setHideAllForFadeDemo] = useState(false);
const [fadeDemoNextIndex, setFadeDemoNextIndex] = useState(0);
const [fadeDemoElementIds, setFadeDemoElementIds] = useState<string[]>([]);
const [demoAnimationType, setDemoAnimationType] = useState<"fade" | "fly">(
"fade",
);
const [demoAnimationDuration, setDemoAnimationDuration] = useState(500);
const [demoFlyFrom, setDemoFlyFrom] = useState<
"left" | "right" | "top" | "bottom"
>("left");
const [demoAnimationEasing, setDemoAnimationEasing] = useState<
"linear" | "easeOut" | "easeInOut"
>("easeOut");
const initialStatePromiseRef = useRef<{
promise: ResolvablePromise<ExcalidrawInitialDataState | null>;
@@ -178,7 +193,8 @@ export default function ExampleApp({
const newElement = cloneElement(
Excalidraw,
{
excalidrawAPI: (api: ExcalidrawImperativeAPI) => setExcalidrawAPI(api),
onExcalidrawAPI: (api: ExcalidrawImperativeAPI | null) =>
setExcalidrawAPI(api),
initialData: initialStatePromiseRef.current.promise,
onChange: (
elements: NonDeletedExcalidrawElement[],
@@ -208,6 +224,10 @@ export default function ExampleApp({
onPointerDown,
onScrollChange: rerenderCommentIcons,
validateEmbeddable: true,
resolveRenderOpacity: hideAllForFadeDemo
? (element: NonDeletedExcalidrawElement) =>
fadeDemoElementIds.includes(element.id) ? 0 : undefined
: undefined,
},
<>
{excalidrawAPI && (
@@ -664,6 +684,229 @@ export default function ExampleApp({
>
Reset Scene
</button>
{showFadeDemo && (
<>
<label>
Animation type
<select
value={demoAnimationType}
onChange={(event) =>
setDemoAnimationType(
event.target.value as "fade" | "fly",
)
}
>
<option value="fade">fade</option>
<option value="fly">fly</option>
</select>
</label>
<label>
Duration
<input
type="number"
value={demoAnimationDuration}
onChange={(event) =>
setDemoAnimationDuration(Number(event.target.value) || 0)
}
/>
</label>
<label>
Easing
<select
value={demoAnimationEasing}
onChange={(event) =>
setDemoAnimationEasing(
event.target.value as "linear" | "easeOut" | "easeInOut",
)
}
>
<option value="linear">linear</option>
<option value="easeOut">easeOut</option>
<option value="easeInOut">easeInOut</option>
</select>
</label>
{demoAnimationType === "fly" && (
<label>
Fly from
<select
value={demoFlyFrom}
onChange={(event) =>
setDemoFlyFrom(
event.target.value as
| "left"
| "right"
| "top"
| "bottom",
)
}
>
<option value="left">left</option>
<option value="right">right</option>
<option value="top">top</option>
<option value="bottom">bottom</option>
</select>
</label>
)}
<button
onClick={() => {
if (!excalidrawAPI) {
return;
}
setFadeDemoElementIds(
excalidrawAPI
.getSceneElements()
.map((element) => element.id),
);
excalidrawAPI.clearElementAnimationOverrides();
setHideAllForFadeDemo(true);
setFadeDemoNextIndex(0);
}}
>
Hide every element
</button>
<button
onClick={() => {
if (!excalidrawAPI || !hideAllForFadeDemo) {
return;
}
const elements = excalidrawAPI
.getSceneElements()
.filter((element) =>
fadeDemoElementIds.includes(element.id),
);
if (!elements.length) {
return;
}
const nextIndex =
fadeDemoNextIndex >= elements.length
? 0
: fadeDemoNextIndex;
if (nextIndex === 0) {
excalidrawAPI.clearElementAnimationOverrides();
}
if (demoAnimationType === "fly") {
excalidrawAPI.animateElements({
elements: [elements[nextIndex].id],
type: "fly",
from: demoFlyFrom,
duration: demoAnimationDuration,
phase: "in",
easing: demoAnimationEasing,
});
} else {
excalidrawAPI.animateElements({
elements: [elements[nextIndex].id],
type: "fade",
duration: demoAnimationDuration,
phase: "in",
easing: demoAnimationEasing,
});
}
setFadeDemoNextIndex(nextIndex + 1);
}}
>
Animate in next element
</button>
<button
onClick={() => {
if (!excalidrawAPI || !hideAllForFadeDemo) {
return;
}
const elements = excalidrawAPI
.getSceneElements()
.filter((element) =>
fadeDemoElementIds.includes(element.id),
);
if (!elements.length) {
return;
}
if (demoAnimationType === "fly") {
excalidrawAPI.animateElements({
elements,
type: "fly",
from: demoFlyFrom,
duration: demoAnimationDuration,
stagger: 120,
phase: "in",
easing: demoAnimationEasing,
});
} else {
excalidrawAPI.animateElements({
elements,
type: "fade",
duration: demoAnimationDuration,
stagger: 120,
phase: "in",
easing: demoAnimationEasing,
});
}
setFadeDemoNextIndex(elements.length);
}}
>
Animate in all
</button>
<button
onClick={() => {
if (!excalidrawAPI || !hideAllForFadeDemo) {
return;
}
const elements = excalidrawAPI
.getSceneElements()
.filter((element) =>
fadeDemoElementIds.includes(element.id),
);
if (!elements.length) {
return;
}
const prevIndex = Math.min(
fadeDemoNextIndex - 1,
elements.length - 1,
);
if (prevIndex < 0) {
return;
}
if (demoAnimationType === "fly") {
excalidrawAPI.animateElements({
elements: [elements[prevIndex].id],
type: "fly",
from: demoFlyFrom,
duration: demoAnimationDuration,
phase: "out",
easing: demoAnimationEasing,
});
} else {
excalidrawAPI.animateElements({
elements: [elements[prevIndex].id],
type: "fade",
duration: demoAnimationDuration,
phase: "out",
easing: demoAnimationEasing,
});
}
setFadeDemoNextIndex(prevIndex);
}}
>
Animate out prev element
</button>
</>
)}
<button
onClick={() => {
const libraryItems: LibraryItems = [
+35 -13
View File
@@ -2,6 +2,28 @@ import type { ExcalidrawElementSkeleton } from "@excalidraw/excalidraw/element/t
import type { FileId } from "@excalidraw/excalidraw/element/types";
const elements: ExcalidrawElementSkeleton[] = [
// {
// type: "arrow",
// x: 100,
// y: 500,
// },
// {
// type: "arrow",
// x: 250,
// y: 250,
// label: {
// text: "HELLO WORLD!!",
// },
// start: {
// type: "rectangle",
// // x: -100,
// },
// end: {
// type: "ellipse",
// // x: 300,
// },
// },
{
type: "rectangle",
x: 10,
@@ -22,14 +44,14 @@ const elements: ExcalidrawElementSkeleton[] = [
},
id: "2",
},
{
type: "arrow",
x: 100,
y: 200,
label: { text: "HELLO WORLD!!" },
start: { type: "rectangle" },
end: { type: "ellipse" },
},
// {
// type: "arrow",
// x: 100,
// y: 200,
// label: { text: "HELLO WORLD!!" },
// start: { type: "rectangle" },
// end: { type: "ellipse" },
// },
{
type: "image",
x: 606.1042326312408,
@@ -38,11 +60,11 @@ const elements: ExcalidrawElementSkeleton[] = [
height: 230,
fileId: "rocket" as FileId,
},
{
type: "frame",
children: ["1", "2"],
name: "My frame",
},
// {
// type: "frame",
// children: ["1", "2"],
// name: "My frame",
// },
];
export default {
elements,
+4 -4
View File
@@ -125,7 +125,7 @@ const focusPointUpdate = (
if (switchToInsideBinding || boundToSameElement) {
currentBinding = {
...currentBinding,
mode: "fixed",
mode: "inside",
};
} else {
currentBinding = {
@@ -166,7 +166,7 @@ const focusPointUpdate = (
if (switchToInsideBinding || boundToSameElementAfterUpdate) {
adjacentBinding = {
...adjacentBinding,
mode: "fixed",
mode: "inside",
};
} else {
adjacentBinding = {
@@ -256,8 +256,8 @@ export const handleFocusPointDrag = (
// Handle binding mode switch
const newMode =
switchToInsideBinding && arrow[bindingField]?.mode === "orbit"
? "fixed"
: !switchToInsideBinding && arrow[bindingField]?.mode === "fixed"
? "inside"
: !switchToInsideBinding && arrow[bindingField]?.mode === "inside"
? "orbit"
: null;
+25 -22
View File
@@ -328,7 +328,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
if (hit) {
start = {
element: hit,
mode: "fixed",
mode: "inside",
focusPoint: point,
};
} else {
@@ -353,13 +353,13 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
start: isMultiPoint
? { mode: undefined }
: {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: origin ?? center,
},
end: isMultiPoint
? { mode: "orbit", element: hit, focusPoint: point }
: { mode: "fixed", element: hit, focusPoint: point },
: { mode: "inside", element: hit, focusPoint: point },
};
}
@@ -379,7 +379,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
start: isMultiPoint
? { mode: undefined }
: {
mode: otherElement.id !== hit.id ? "orbit" : "fixed",
mode: otherElement.id !== hit.id ? "orbit" : "inside",
element: otherElement,
focusPoint: origin ?? pointFrom<GlobalPoint>(arrow.x, arrow.y),
},
@@ -402,7 +402,7 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
const otherIsInsideBinding =
!!appState.selectedLinearElement?.initialState.arrowStartIsInside;
const other: BindingStrategy = {
mode: otherIsInsideBinding ? "fixed" : "orbit",
mode: otherIsInsideBinding ? "inside" : "orbit",
element: otherElement,
focusPoint: shiftKey
? elementCenterPoint(otherElement, elementsMap)
@@ -416,9 +416,9 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
let current: BindingStrategy;
if (hit) {
const isInsideBinding =
globalBindMode === "fixed" || globalBindMode === "skip";
globalBindMode === "inside" || globalBindMode === "skip";
current = {
mode: isInsideBinding && !isNested ? "fixed" : "orbit",
mode: isInsideBinding && !isNested ? "inside" : "orbit",
element: hit,
focusPoint: isInsideBinding || isNested ? point : point,
};
@@ -436,10 +436,10 @@ const bindingStrategyForNewSimpleArrowEndpointDragging = (
if (!arrow.startBinding) {
if (hit) {
const isInsideBinding =
globalBindMode === "fixed" || globalBindMode === "skip";
globalBindMode === "inside" || globalBindMode === "skip";
end = {
mode: isInsideBinding ? "fixed" : "orbit",
mode: isInsideBinding ? "inside" : "orbit",
element: hit,
focusPoint: point,
};
@@ -488,7 +488,7 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
// If the global bind mode is in free binding mode, just bind
// where the pointer is and keep the other end intact
if (globalBindMode === "fixed" || globalBindMode === "skip") {
if (globalBindMode === "inside" || globalBindMode === "skip") {
current = hit
? {
element:
@@ -496,7 +496,7 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
? hit
: oppositeElement,
focusPoint: point,
mode: "fixed",
mode: "inside",
}
: { mode: null };
other =
@@ -514,9 +514,12 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
}
// Already inside binding over the same hit element should remain inside bound
if (hit.id === currentBinding?.elementId && currentBinding.mode === "fixed") {
if (
hit.id === currentBinding?.elementId &&
currentBinding.mode === "inside"
) {
return {
current: { mode: "fixed", focusPoint: point, element: hit },
current: { mode: "inside", focusPoint: point, element: hit },
other,
};
}
@@ -535,7 +538,7 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
// The opposite binding is inside the same element
// eslint-disable-next-line no-else-return
else {
current = { element: hit, mode: "fixed", focusPoint: point };
current = { element: hit, mode: "inside", focusPoint: point };
return { current, other: isMultiPoint ? { mode: undefined } : other };
}
@@ -547,7 +550,7 @@ const bindingStrategyForSimpleArrowEndpointDragging_complex = (
if (isOverlapping && oppositeElement && !otherIsTransparent) {
current = {
element: oppositeElement,
mode: "fixed",
mode: "inside",
focusPoint: point,
};
} else {
@@ -738,7 +741,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
) {
return {
start: {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: startDragged
? globalPoint
@@ -752,7 +755,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
), // startFixedPoint,
},
end: {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: endDragged
? globalPoint
@@ -771,7 +774,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
start: startDragged
? hit
? {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: globalPoint,
}
@@ -780,7 +783,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
end: endDragged
? hit
? {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: globalPoint,
}
@@ -793,7 +796,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
const current: BindingStrategy = hit
? pointInElement
? {
mode: "fixed",
mode: "inside",
element: hit,
focusPoint: globalPoint,
}
@@ -830,7 +833,7 @@ const getBindingStrategyForDraggingBindingElementEndpoints_simple = (
});
const otherNeverOverride = opts?.newArrow
? appState.selectedLinearElement?.initialState.arrowStartIsInside
: otherBinding?.mode === "fixed";
: otherBinding?.mode === "inside";
const other: BindingStrategy = !otherNeverOverride
? otherBindableElement &&
!otherFocusPointIsInElement &&
@@ -1769,7 +1772,7 @@ export const updateBoundPoint = (
// 0. Short-circuit for inside binding as it doesn't require any
// calculations and is not affected by other bindings
if (binding.mode === "fixed") {
if (binding.mode === "inside") {
return LinearElementEditor.createPointAt(
arrow,
elementsMap,
+1 -1
View File
@@ -762,7 +762,7 @@ export const isPointInElement = (
(isLinearElement(element) || isFreeDrawElement(element)) &&
!isPathALoop(element.points)
) {
// There isn't any "fixed" for a non-looping path
// There isn't any "inside" for a non-looping path
return false;
}
+5 -5
View File
@@ -1083,7 +1083,7 @@ export class LinearElementEditor {
},
arrowStartIsInside:
!!app.state.newElement &&
(app.state.bindMode === "fixed" || app.state.bindMode === "skip"),
(app.state.bindMode === "inside" || app.state.bindMode === "skip"),
altFocusPoint: null,
},
selectedPointsIndices: [element.points.length - 1],
@@ -1145,7 +1145,7 @@ export class LinearElementEditor {
},
arrowStartIsInside:
!!app.state.newElement &&
(app.state.bindMode === "fixed" || app.state.bindMode === "skip"),
(app.state.bindMode === "inside" || app.state.bindMode === "skip"),
altFocusPoint: null,
},
selectedPointsIndices: nextSelectedPointsIndices,
@@ -2412,7 +2412,7 @@ const pointDraggingUpdates = (
const endLocalPoint = startIsDraggingOverEndElement
? nextArrow.points[nextArrow.points.length - 1]
: endIsDraggingOverStartElement &&
app.state.bindMode !== "fixed" &&
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[0]
: endBindable
@@ -2443,7 +2443,7 @@ const pointDraggingUpdates = (
endIsDraggingOverStartElement && getFeatureFlag("COMPLEX_BINDINGS")
? nextArrow.points[0]
: startIsDraggingOverEndElement &&
app.state.bindMode !== "fixed" &&
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
? endLocalPoint
: startBindable
@@ -2461,7 +2461,7 @@ const pointDraggingUpdates = (
!startIsDraggingOverEndElement &&
!(
endIsDraggingOverStartElement &&
app.state.bindMode !== "fixed" &&
app.state.bindMode !== "inside" &&
getFeatureFlag("COMPLEX_BINDINGS")
) &&
!!endBindable;
+60 -1
View File
@@ -1,6 +1,7 @@
import rough from "roughjs/bin/rough";
import {
clamp,
type GlobalPoint,
isRightAngleRads,
lineSegment,
@@ -105,8 +106,62 @@ const getCanvasPadding = (element: ExcalidrawElement) => {
}
};
export const resolveRenderOpacity = (
element: ExcalidrawElement,
renderConfig: Pick<
StaticCanvasRenderConfig,
"elementOpacityOverrides" | "resolveRenderOpacity"
>,
) => {
const override = renderConfig.elementOpacityOverrides?.get(element.id);
if (override !== undefined) {
return clamp(override, 0, 100);
}
const resolvedOpacity = renderConfig.resolveRenderOpacity?.(
element as NonDeletedExcalidrawElement,
);
if (resolvedOpacity !== undefined) {
return clamp(resolvedOpacity, 0, 100);
}
return element.opacity;
};
export const resolveRenderPositionOffset = (
element: ExcalidrawElement,
renderConfig: Pick<StaticCanvasRenderConfig, "elementPositionOverrides">,
) => {
return renderConfig.elementPositionOverrides?.get(element.id) ?? { x: 0, y: 0 };
};
export const getRenderElementWithPositionOverride = <
TElement extends NonDeletedExcalidrawElement,
>(
element: TElement,
renderConfig: Pick<StaticCanvasRenderConfig, "elementPositionOverrides">,
): TElement => {
const positionOffset = resolveRenderPositionOffset(element, renderConfig);
if (positionOffset.x === 0 && positionOffset.y === 0) {
return element;
}
return {
...element,
x: element.x + positionOffset.x,
y: element.y + positionOffset.y,
} as TElement;
};
export const getRenderOpacity = (
element: ExcalidrawElement,
renderConfig: Pick<
StaticCanvasRenderConfig,
"elementOpacityOverrides" | "resolveRenderOpacity"
>,
containingFrame: ExcalidrawFrameLikeElement | null,
elementsPendingErasure: ElementsPendingErasure,
pendingNodes: Readonly<PendingExcalidrawElements> | null,
@@ -115,7 +170,8 @@ export const getRenderOpacity = (
// multiplying frame opacity with element opacity to combine them
// (e.g. frame 50% and element 50% opacity should result in 25% opacity)
let opacity =
(((containingFrame?.opacity ?? 100) * element.opacity) / 10000) *
(((containingFrame?.opacity ?? 100) * resolveRenderOpacity(element, renderConfig)) /
10000) *
globalAlpha;
// if pending erasure, multiply again to combine further
@@ -791,8 +847,11 @@ export const renderElement = (
!appState.selectedElementIds[element.id] &&
!appState.hoveredElementIds[element.id];
element = getRenderElementWithPositionOverride(element, renderConfig);
context.globalAlpha = getRenderOpacity(
element,
renderConfig,
getContainingFrame(element, elementsMap),
renderConfig.elementsPendingErasure,
renderConfig.pendingFlowchartNodes,
+1 -1
View File
@@ -279,7 +279,7 @@ export type ExcalidrawTextElementWithContainer = {
export type FixedPoint = [number, number];
export type BindMode = "fixed" | "orbit" | "skip";
export type BindMode = "inside" | "orbit" | "skip";
export type FixedPointBinding = {
elementId: ExcalidrawBindableElement["id"];
+2 -2
View File
@@ -72,14 +72,14 @@ describe("binding for simple arrows", () => {
expect(startBinding.fixedPoint[0]).toBeLessThanOrEqual(1);
expect(startBinding.fixedPoint[1]).toBeGreaterThanOrEqual(0);
expect(startBinding.fixedPoint[1]).toBeLessThanOrEqual(1);
expect(startBinding.mode).toBe("fixed");
expect(startBinding.mode).toBe("inside");
const endBinding = arrow.endBinding as FixedPointBinding;
expect(endBinding.fixedPoint[0]).toBeGreaterThanOrEqual(0);
expect(endBinding.fixedPoint[0]).toBeLessThanOrEqual(1);
expect(endBinding.fixedPoint[1]).toBeGreaterThanOrEqual(0);
expect(endBinding.fixedPoint[1]).toBeLessThanOrEqual(1);
expect(endBinding.mode).toBe("fixed");
expect(endBinding.mode).toBe("inside");
// Move the bindable
mouse.downAt(100, 150);
@@ -1940,7 +1940,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
bindBindingElement(
newElement,
startElement,
appState.bindMode === "fixed" ? "fixed" : "orbit",
appState.bindMode === "inside" ? "inside" : "orbit",
"start",
app.scene,
);
@@ -1954,7 +1954,7 @@ export const actionChangeArrowType = register<keyof typeof ARROW_TYPE>({
bindBindingElement(
newElement,
endElement,
appState.bindMode === "fixed" ? "fixed" : "orbit",
appState.bindMode === "inside" ? "inside" : "orbit",
"end",
app.scene,
);
+350 -11
View File
@@ -207,10 +207,12 @@ import {
getLineHeightInPx,
getApproxMinLineWidth,
getApproxMinLineHeight,
getMinTextElementWidth,
ShapeCache,
getRenderOpacity,
editGroupForSelectedElement,
getMinTextElementWidth,
ShapeCache,
getRenderOpacity,
resolveRenderPositionOffset,
resolveRenderOpacity,
editGroupForSelectedElement,
getElementsInGroup,
getSelectedGroupIdForElement,
getSelectedGroupIds,
@@ -450,6 +452,7 @@ import { searchItemInFocusAtom } from "./SearchMenu";
import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
import { StaticCanvas, InteractiveCanvas } from "./canvases";
import NewElementCanvas from "./canvases/NewElementCanvas";
import { AnimationController } from "../renderer/animation";
import { isPointHittingLink } from "./hyperlink/helpers";
import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
import { AppStateObserver, type OnStateChange } from "./AppStateObserver";
@@ -740,6 +743,235 @@ class App extends React.Component<AppProps, AppState> {
onRemoveEventListenersEmitter = new Emitter<[]>();
api: ExcalidrawImperativeAPI;
private renderAnimationVersion = 0;
private elementOpacityOverrides = new Map<string, number>();
private elementPositionOverrides = new Map<string, { x: number; y: number }>();
private elementAnimationStates = new Map<
string,
{
opacityFrom: number;
opacityTo: number;
positionFrom: { x: number; y: number };
positionTo: { x: number; y: number };
easing: "linear" | "easeOut" | "easeInOut";
duration: number;
delay: number;
elapsed: number;
}
>();
private getElementAnimationKey = () => `${this.id}:animate-element`;
private bumpRenderAnimationVersion = () => {
this.renderAnimationVersion++;
this.setState({});
};
private getRenderOpacityConfig = () => ({
elementOpacityOverrides: this.elementOpacityOverrides,
elementPositionOverrides: this.elementPositionOverrides,
resolveRenderOpacity: this.props.resolveRenderOpacity,
});
private getResolvedElementOpacity = (element: NonDeletedExcalidrawElement) => {
return resolveRenderOpacity(element, this.getRenderOpacityConfig());
};
private getElementVisibleOpacity = (element: NonDeletedExcalidrawElement) => {
return clamp(element.opacity, 0, 100);
};
private applyAnimationEasing = (
progress: number,
easing: "linear" | "easeOut" | "easeInOut",
) => {
switch (easing) {
case "linear":
return progress;
case "easeOut":
return easeOut(progress);
case "easeInOut":
return progress < 0.5
? 4 * progress * progress * progress
: 1 - Math.pow(-2 * progress + 2, 3) / 2;
}
};
private getFlyPositionOffset = (
element: NonDeletedExcalidrawElement,
from: "left" | "right" | "top" | "bottom",
) => {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(
element,
this.scene.getNonDeletedElementsMap(),
);
const viewportWidth = this.state.width / this.state.zoom.value;
const viewportHeight = this.state.height / this.state.zoom.value;
const elementWidth = x2 - x1;
const elementHeight = y2 - y1;
switch (from) {
case "left":
return { x: -(Math.max(viewportWidth, elementWidth) + 64), y: 0 };
case "right":
return { x: Math.max(viewportWidth, elementWidth) + 64, y: 0 };
case "top":
return { x: 0, y: -(Math.max(viewportHeight, elementHeight) + 64) };
case "bottom":
return { x: 0, y: Math.max(viewportHeight, elementHeight) + 64 };
}
};
private animateElement = ({
id,
opacityFrom,
opacityTo,
positionFrom = { x: 0, y: 0 },
positionTo = { x: 0, y: 0 },
easing,
duration,
delay,
}: {
id: string;
opacityFrom: number;
opacityTo: number;
positionFrom?: { x: number; y: number };
positionTo?: { x: number; y: number };
easing: "linear" | "easeOut" | "easeInOut";
duration: number;
delay: number;
}) => {
const normalizedOpacityFrom = clamp(opacityFrom, 0, 100);
const normalizedOpacityTo = clamp(opacityTo, 0, 100);
const normalizedDuration = Math.max(duration, 0);
const normalizedDelay = Math.max(delay, 0);
this.elementOpacityOverrides.set(id, normalizedOpacityFrom);
if (positionFrom.x !== 0 || positionFrom.y !== 0) {
this.elementPositionOverrides.set(id, positionFrom);
} else {
this.elementPositionOverrides.delete(id);
}
if (normalizedDuration === 0 && normalizedDelay === 0) {
this.elementAnimationStates.delete(id);
this.elementOpacityOverrides.set(id, normalizedOpacityTo);
if (positionTo.x !== 0 || positionTo.y !== 0) {
this.elementPositionOverrides.set(id, positionTo);
} else {
this.elementPositionOverrides.delete(id);
}
this.bumpRenderAnimationVersion();
return;
}
this.elementAnimationStates.set(id, {
opacityFrom: normalizedOpacityFrom,
opacityTo: normalizedOpacityTo,
positionFrom,
positionTo,
easing,
duration: normalizedDuration,
delay: normalizedDelay,
elapsed: 0,
});
this.bumpRenderAnimationVersion();
this.syncElementAnimations();
};
private syncElementAnimations = () => {
const animationKey = this.getElementAnimationKey();
if (this.elementAnimationStates.size === 0) {
AnimationController.cancel(animationKey);
return;
}
if (AnimationController.running(animationKey)) {
return;
}
AnimationController.start(animationKey, ({ deltaTime }) => {
let shouldRerender = false;
for (const [id, animation] of this.elementAnimationStates) {
const element = this.scene.getNonDeletedElement(id);
if (!element) {
this.elementAnimationStates.delete(id);
shouldRerender =
this.elementOpacityOverrides.delete(id) || shouldRerender;
shouldRerender =
this.elementPositionOverrides.delete(id) || shouldRerender;
continue;
}
animation.elapsed += deltaTime;
const progress =
animation.elapsed <= animation.delay
? 0
: animation.duration === 0
? 1
: Math.min(
(animation.elapsed - animation.delay) / animation.duration,
1,
);
const easedProgress = this.applyAnimationEasing(
progress,
animation.easing,
);
const nextOpacity =
animation.opacityFrom +
(animation.opacityTo - animation.opacityFrom) * easedProgress;
const nextPosition = {
x:
animation.positionFrom.x +
(animation.positionTo.x - animation.positionFrom.x) * easedProgress,
y:
animation.positionFrom.y +
(animation.positionTo.y - animation.positionFrom.y) * easedProgress,
};
const clampedOpacity = clamp(nextOpacity, 0, 100);
if (this.elementOpacityOverrides.get(id) !== clampedOpacity) {
this.elementOpacityOverrides.set(id, clampedOpacity);
shouldRerender = true;
}
const currentPositionOverride =
this.elementPositionOverrides.get(id) ?? ({ x: 0, y: 0 } as const);
if (
currentPositionOverride.x !== nextPosition.x ||
currentPositionOverride.y !== nextPosition.y
) {
if (nextPosition.x === 0 && nextPosition.y === 0) {
this.elementPositionOverrides.delete(id);
} else {
this.elementPositionOverrides.set(id, nextPosition);
}
shouldRerender = true;
}
if (animation.elapsed >= animation.delay + animation.duration) {
this.elementAnimationStates.delete(id);
}
}
if (shouldRerender) {
this.bumpRenderAnimationVersion();
}
return this.elementAnimationStates.size > 0 ? {} : undefined;
});
};
private createExcalidrawAPI(): ExcalidrawImperativeAPI {
const api: ExcalidrawImperativeAPI = {
@@ -757,6 +989,9 @@ class App extends React.Component<AppProps, AppState> {
clear: this.resetHistory,
},
scrollToContent: this.scrollToContent,
animateElements: this.animateElements,
cancelElementAnimation: this.cancelElementAnimation,
clearElementAnimationOverrides: this.clearElementAnimationOverrides,
getSceneElements: this.getSceneElements,
getAppState: () => this.state,
getFiles: () => this.files,
@@ -1095,7 +1330,7 @@ class App extends React.Component<AppProps, AppState> {
);
this.setState({
bindMode: "fixed",
bindMode: "inside",
selectedLinearElement: {
...this.state.selectedLinearElement,
initialState: {
@@ -1176,16 +1411,16 @@ class App extends React.Component<AppProps, AppState> {
: null;
const isAlreadyInsideBindingToSameElement =
(otherBinding &&
arrow[otherBinding]?.mode === "fixed" &&
arrow[otherBinding]?.mode === "inside" &&
arrow[otherBinding]?.elementId === hoveredElement?.id) ||
(currentBinding &&
arrow[currentBinding]?.mode === "fixed" &&
arrow[currentBinding]?.mode === "inside" &&
hoveredElement?.id === arrow[currentBinding]?.elementId);
if (
currentBinding &&
otherBinding &&
arrow[currentBinding]?.mode === "fixed" &&
arrow[currentBinding]?.mode === "inside" &&
hoveredElement?.id !== arrow[currentBinding]?.elementId &&
arrow[otherBinding]?.elementId !== arrow[currentBinding]?.elementId
) {
@@ -1217,7 +1452,7 @@ class App extends React.Component<AppProps, AppState> {
}
// Clear the inside binding mode too
if (this.state.bindMode === "fixed") {
if (this.state.bindMode === "inside") {
flushSync(() => {
this.setState({
bindMode: "orbit",
@@ -1734,6 +1969,10 @@ class App extends React.Component<AppProps, AppState> {
const isHovered =
this.state.activeEmbeddable?.element === el &&
this.state.activeEmbeddable?.state === "hover";
const renderPositionOffset = resolveRenderPositionOffset(
el,
this.getRenderOpacityConfig(),
);
// scale video embeds based on zoom (capped) so that smaller embeds
// on canvas when zoomed are still of legible quality
@@ -1755,13 +1994,14 @@ class App extends React.Component<AppProps, AppState> {
})}
style={{
transform: isVisible
? `translate(${x - this.state.offsetLeft}px, ${
y - this.state.offsetTop
? `translate(${x + renderPositionOffset.x * this.state.zoom.value - this.state.offsetLeft}px, ${
y + renderPositionOffset.y * this.state.zoom.value - this.state.offsetTop
}px) scale(${scale})`
: "none",
display: isVisible ? "block" : "none",
opacity: getRenderOpacity(
el,
this.getRenderOpacityConfig(),
getContainingFrame(el, this.scene.getNonDeletedElementsMap()),
this.elementsPendingErasure,
null,
@@ -2351,6 +2591,9 @@ class App extends React.Component<AppProps, AppState> {
pendingFlowchartNodes:
this.flowChartCreator.pendingNodes,
theme: this.state.theme,
...this.getRenderOpacityConfig(),
renderAnimationVersion:
this.renderAnimationVersion,
}}
/>
{newElementCanvasElement && (
@@ -2373,6 +2616,9 @@ class App extends React.Component<AppProps, AppState> {
this.elementsPendingErasure,
pendingFlowchartNodes: null,
theme: this.state.theme,
...this.getRenderOpacityConfig(),
renderAnimationVersion:
this.renderAnimationVersion,
}}
/>
)}
@@ -3206,6 +3452,7 @@ class App extends React.Component<AppProps, AppState> {
this.editorLifecycleEvents.emit("editor:unmount");
this.props.onUnmount?.();
this.props.onExcalidrawAPI?.(null);
AnimationController.cancel(this.getElementAnimationKey());
(window as any).launchQueue?.setConsumer(() => {});
@@ -4618,6 +4865,98 @@ class App extends React.Component<AppProps, AppState> {
},
);
public animateElements = ({
elements,
duration = 250,
delay = 0,
stagger = 0,
phase = "in",
easing,
...animation
}:
| {
elements: readonly (ExcalidrawElement | ExcalidrawElement["id"])[];
type: "fade";
duration?: number;
delay?: number;
stagger?: number;
phase?: "in" | "out";
easing?: "linear" | "easeOut" | "easeInOut";
}
| {
elements: readonly (ExcalidrawElement | ExcalidrawElement["id"])[];
type: "fly";
from: "left" | "right" | "top" | "bottom";
duration?: number;
delay?: number;
stagger?: number;
phase?: "in" | "out";
easing?: "linear" | "easeOut" | "easeInOut";
}) => {
const normalizedDelay = Math.max(delay, 0);
const normalizedStagger = Math.max(stagger, 0);
elements.forEach((elementOrId, index) => {
const id = typeof elementOrId === "string" ? elementOrId : elementOrId.id;
const element = this.scene.getNonDeletedElement(id);
if (!element) {
return;
}
if (animation.type === "fade") {
this.animateElement({
id,
opacityFrom:
phase === "in" ? 0 : this.getElementVisibleOpacity(element),
opacityTo:
phase === "in" ? this.getElementVisibleOpacity(element) : 0,
easing: easing ?? "easeInOut",
duration,
delay: normalizedDelay + index * normalizedStagger,
});
return;
}
const flyOffset = this.getFlyPositionOffset(element, animation.from);
this.animateElement({
id,
opacityFrom: phase === "in" ? 0 : this.getElementVisibleOpacity(element),
opacityTo: phase === "in" ? this.getElementVisibleOpacity(element) : 0,
positionFrom: phase === "in" ? flyOffset : { x: 0, y: 0 },
positionTo: phase === "in" ? { x: 0, y: 0 } : flyOffset,
easing: easing ?? "easeOut",
duration,
delay: normalizedDelay + index * normalizedStagger,
});
});
};
public cancelElementAnimation = (id: string) => {
if (!this.elementAnimationStates.delete(id)) {
return;
}
this.syncElementAnimations();
};
public clearElementAnimationOverrides = () => {
if (
this.elementOpacityOverrides.size === 0 &&
this.elementPositionOverrides.size === 0 &&
this.elementAnimationStates.size === 0
) {
return;
}
this.elementAnimationStates.clear();
this.elementOpacityOverrides.clear();
this.elementPositionOverrides.clear();
this.syncElementAnimations();
this.bumpRenderAnimationVersion();
};
public applyDeltas = (
deltas: StoreDelta[],
options?: ApplyToOptions,
+4 -4
View File
@@ -239,8 +239,8 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
if (binding.elementId) {
return {
elementId: binding.elementId,
mode: (binding.mode as string) === "inside" ? "fixed" : binding.mode,
fixedPoint: normalizeFixedPoint(binding.fixedPoint || [0.5, 0.5]),
mode: binding.mode,
fixedPoint: normalizeFixedPoint(binding.fixedPoint),
} as FixedPointBinding | null;
}
return null;
@@ -269,7 +269,7 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
elementsMap,
);
const mode = isPointInElement(p, boundElement, elementsMap)
? "fixed"
? "inside"
: "orbit";
const safeElement = {
...element,
@@ -289,7 +289,7 @@ const repairBinding = <T extends ExcalidrawArrowElement>(
: null,
};
const focusPoint =
mode === "fixed"
mode === "inside"
? p
: projectFixedPointOntoDiagonal(
safeElement,
+2
View File
@@ -99,6 +99,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
children,
validateEmbeddable,
renderEmbeddable,
resolveRenderOpacity,
aiEnabled,
showDeprecatedFonts,
renderScrollbars,
@@ -217,6 +218,7 @@ const ExcalidrawBase = (props: ExcalidrawProps) => {
onDuplicate={onDuplicate}
validateEmbeddable={validateEmbeddable}
renderEmbeddable={renderEmbeddable}
resolveRenderOpacity={resolveRenderOpacity}
aiEnabled={aiEnabled !== false}
showDeprecatedFonts={showDeprecatedFonts}
renderScrollbars={renderScrollbars}
+18 -4
View File
@@ -14,11 +14,16 @@ import {
} from "@excalidraw/element";
import {
elementOverlapsWithFrame,
getContainingFrame,
getTargetFrame,
shouldApplyFrameClip,
} from "@excalidraw/element";
import { renderElement } from "@excalidraw/element";
import {
getRenderElementWithPositionOverride,
getRenderOpacity,
renderElement,
} from "@excalidraw/element";
import { getElementAbsoluteCoords } from "@excalidraw/element";
@@ -170,7 +175,10 @@ const renderLinkIcon = (
context: CanvasRenderingContext2D,
appState: StaticCanvasAppState,
elementsMap: ElementsMap,
renderConfig: StaticCanvasRenderConfig,
) => {
element = getRenderElementWithPositionOverride(element, renderConfig);
if (element.link && !appState.selectedElementIds[element.id]) {
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
const [x, y, width, height] = getLinkHandleFromCoords(
@@ -221,7 +229,13 @@ const renderLinkIcon = (
linkCanvasCacheContext.restore();
}
context.globalAlpha = element.opacity / 100;
context.globalAlpha = getRenderOpacity(
element,
renderConfig,
getContainingFrame(element, elementsMap),
renderConfig.elementsPendingErasure,
renderConfig.pendingFlowchartNodes,
);
context.drawImage(linkCanvas, x - centerX, y - centerY, width, height);
context.restore();
}
@@ -370,7 +384,7 @@ const _renderStaticScene = ({
context.restore();
if (!isExporting) {
renderLinkIcon(element, context, appState, elementsMap);
renderLinkIcon(element, context, appState, elementsMap, renderConfig);
}
} catch (error: any) {
console.error(
@@ -421,7 +435,7 @@ const _renderStaticScene = ({
);
}
if (!isExporting) {
renderLinkIcon(element, context, appState, elementsMap);
renderLinkIcon(element, context, appState, elementsMap, renderConfig);
}
};
// - when exporting the whole canvas, we DO NOT apply clipping
+8
View File
@@ -12,6 +12,7 @@ import type {
AppClassProperties,
AppState,
EmbedsValidationStatus,
RenderOpacityResolver,
ElementsPendingErasure,
InteractiveCanvasAppState,
StaticCanvasAppState,
@@ -37,6 +38,13 @@ export type StaticCanvasRenderConfig = {
elementsPendingErasure: ElementsPendingErasure;
pendingFlowchartNodes: PendingExcalidrawElements | null;
theme: AppState["theme"];
resolveRenderOpacity?: RenderOpacityResolver;
elementOpacityOverrides?: ReadonlyMap<ExcalidrawElement["id"], number>;
elementPositionOverrides?: ReadonlyMap<
ExcalidrawElement["id"],
{ x: number; y: number }
>;
renderAnimationVersion?: number;
};
export type SVGRenderConfig = {
@@ -857,7 +857,7 @@ describe("repairing bindings", () => {
endBinding: {
elementId: container.id,
fixedPoint: [0.5, 0.5],
mode: "fixed",
mode: "inside",
},
});
+10
View File
@@ -567,6 +567,10 @@ export type OnExportProgress = {
progress?: number;
};
export type RenderOpacityResolver = (
element: NonDeletedExcalidrawElement,
) => ExcalidrawElement["opacity"] | undefined;
export interface ExcalidrawProps {
onChange?: (
elements: readonly OrderedExcalidrawElement[],
@@ -682,6 +686,7 @@ export interface ExcalidrawProps {
element: NonDeleted<ExcalidrawEmbeddableElement>,
appState: AppState,
) => JSX.Element | null;
resolveRenderOpacity?: RenderOpacityResolver;
aiEnabled?: boolean;
showDeprecatedFonts?: boolean;
renderScrollbars?: boolean;
@@ -962,6 +967,11 @@ export interface ExcalidrawImperativeAPI {
getFiles: () => InstanceType<typeof App>["files"];
getName: InstanceType<typeof App>["getName"];
scrollToContent: InstanceType<typeof App>["scrollToContent"];
animateElements: InstanceType<typeof App>["animateElements"];
cancelElementAnimation: InstanceType<typeof App>["cancelElementAnimation"];
clearElementAnimationOverrides: InstanceType<
typeof App
>["clearElementAnimationOverrides"];
registerAction: (action: Action) => void;
refresh: InstanceType<typeof App>["refresh"];
setToast: InstanceType<typeof App>["setToast"];