Compare commits

..

14 Commits

Author SHA1 Message Date
Ryan Di 638c544bd1 lint 2026-04-24 17:13:37 +10:00
Ryan Di 79b5bab273 tests 2026-04-24 17:02:24 +10:00
Ryan Di b2920f0baf update docs 2026-04-24 16:32:46 +10:00
Ryan Di 4be8dd9879 refactor store to isolate synthetic tx commits and use markers instead 2026-04-24 16:15:32 +10:00
Ryan Di 801c936fd4 refactor(transaction): split module and tighten tx lifecycle 2026-04-24 14:35:25 +10:00
Ryan Di d4836f9e25 improve typing for partial updates 2026-04-24 11:10:02 +10:00
Ryan Di 75192db663 tx markers/effective-delta + perf tune 2026-04-23 14:34:30 +10:00
Ryan Di ef9afb0d37 chore(transaction): keep live-wins-per-prop + API clean up 2026-04-21 20:32:58 +10:00
Ryan Di a5769f96cd merge winner & scope 2026-04-20 17:23:14 +10:00
dwelle 2c6f513aed push more tests & failing test case 2026-04-19 23:08:21 +02:00
Ryan Di bfd4af2367 refactor(transaction): consolidate ledger into single file, fix store API, and optimize snapshots
- Move TransactionLedger + types from @excalidraw/element into
  packages/excalidraw/transaction.ts (no external consumers)
- Move commitSyntheticIncrement from App passthrough to Store directly,
  fix didAppStateChange to use Delta.isRightDifferent instead of
  presence-check, and replace isolated increments queue with direct
  scheduleMicroAction + flushMicroActions
- Remove commitSyntheticHistoryEntry from App, expose store and
  createTransaction on AppClassProperties instead
- Replace O(N) deep-copy snapshot in updateScene with shallow map copy
  (element refs are safe — ledger ignores index, the only in-place
  mutated prop, and deep-copies only recorded elements)
- Merge ledger + manager tests into single transaction.test.tsx
- Update dev-docs to reflect new file structure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 21:59:11 +10:00
Ryan Di 2177e1cfa0 test(transaction): add deferred flush and conflict-scope coverage 2026-04-15 14:20:00 +10:00
Ryan Di 5cd609cea7 test(transaction): add interleaved history isolation coverage 2026-04-14 16:43:00 +10:00
Ryan Di 226a6eef0a feat(editor): add ledger-backed transaction manager with isolated history lane 2026-04-13 23:17:58 +10:00
30 changed files with 4347 additions and 1047 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
FROM node:24-bullseye
FROM node:18-bullseye
# Vite wants to open the browser using `open`, so we
# need to install those utils.
+2 -2
View File
@@ -1,4 +1,4 @@
FROM --platform=${BUILDPLATFORM} node:24 AS build
FROM --platform=${BUILDPLATFORM} node:18 AS build
WORKDIR /opt/node_app
@@ -13,7 +13,7 @@ ARG NODE_ENV=production
RUN npm_config_target_arch=${TARGETARCH} yarn build:app:docker
FROM nginx:1.27-alpine
FROM --platform=${TARGETPLATFORM} nginx:1.27-alpine
COPY --from=build /opt/node_app/excalidraw-app/build /usr/share/nginx/html
+125
View File
@@ -0,0 +1,125 @@
# Transactions
Transactions let many live scene updates render immediately while still committing a single durable history entry.
Typical use case:
- AI streaming emits many `NEVER` updates for real-time feedback.
- Those updates advance the live scene and store snapshot, but do not create undo history.
- A transaction records the intended logical delta separately, then commits one synthetic durable increment at the end.
## Key Files
### `packages/excalidraw/transaction/`
- `transaction.ts`
- `Transaction` is the per-tx instance.
- `updateScene()` applies live updates with `captureUpdate: NEVER`.
- `updateElements()` is a typed partial-patch helper over `updateScene()`.
- `commit()` builds synthetic snapshots and commits one durable entry.
- `cancel()` ends the tx without committing history.
- `ledger.ts`
- `TransactionLedger` keeps per-element baseline, target, and touched props across tx steps.
- `buildSyntheticSnapshots()` reconciles tx intent with the live scene using `live-wins-per-prop`.
- `undoOverridePlanner.ts`
- Tracks tx intermediate values.
- Produces undo override candidates for regular user history entries that were recorded while a tx was active.
- `manager.ts`
- Owns tx lifecycle state and active-tx priority.
- Injects tx undo markers into durable deltas at record time.
- Resolves effective history deltas at undo/redo time.
- `diff.ts` / `types.ts`
- Shared diff helpers and transaction-specific types.
### `packages/element/src/store.ts`
- `store.commitSyntheticIncrement()`
- Builds `StoreSnapshot -> StoreChange -> StoreDelta` from logical before/after snapshots.
- Commits the synthetic durable increment immediately through an isolated path.
- Does not flush unrelated pending micro actions.
- `StoreDelta.markers`
- Carries extra history markers such as `txUndoOverrides`.
### `packages/excalidraw/history.ts`
- `onBeforeRecord()`
- Lets the transaction manager attach markers before a durable delta becomes a history entry.
- `setEffectiveDeltaResolver()`
- Lets the transaction manager rewrite a history delta at undo/redo time before it is applied.
## Flow
1. Caller creates a transaction.
2. `tx.updateScene()` applies live updates with `NEVER`.
3. The ledger records net element changes; appState intent is accumulated separately.
4. Regular user durable edits that happen while the tx is active may receive tx undo markers.
5. `tx.commit()` asks the ledger for logical before/after snapshots and calls `store.commitSyntheticIncrement()`.
6. Undo/redo later uses the manager's effective-delta resolver to decide whether ended tx markers should patch the baseline of a regular history entry.
Result:
- live rendering stays immediate;
- one tx still produces one durable history entry;
- interleaved regular edits can undo back to the correct pre-tx baseline.
## Undo Examples
### Interleaved Regular Edit
1. Baseline: `rect = (x: 0, stroke: black)`
2. Tx updates it live to `(x: 200, stroke: red)` with `NEVER`
3. User makes a regular durable edit: `(x: 200, stroke: purple)`
4. Tx commits; live stays purple
The user history entry was recorded while the tx was active, so its local baseline is `red`.
If undo later runs after the tx has ended, restoring `red` is wrong: the correct pre-tx baseline is `black`.
To fix this:
- record-time attaches a tx undo marker to the user history entry
- perform-time checks whether the tx has already ended
- if ended, the effective delta is patched so undo restores `black` instead of `red`
### Active Tx vs Ended Tx
Using the same example:
- if the user undoes while the tx is still active, the marker stays inactive and undo restores the tx intermediate value (`red`)
- if the user undoes after the tx has ended, the marker becomes active and undo restores the pre-tx baseline (`black`)
So markers are recorded early, but applied conditionally.
## AppState
Elements use ledger snapshots. AppState does not.
The transaction instead keeps:
- `initialAppState`: observed appState at tx start
- `accumulatedAppState`: merged caller intent from `tx.updateScene({ appState })`
At commit, the transaction computes the final appState patch and passes it into `store.commitSyntheticIncrement()`.
## Example
```ts
const tx = app.transactionManager.create();
tx.updateScene({ elements: updatedElementsA });
tx.updateScene({ elements: updatedElementsB });
tx.updateElements({
elements: [
{ id: "rect-1", type: "rectangle", updates: { strokeColor: "#f00" } },
{ id: "rect-2", type: "rectangle", updates: { x: 120 } },
],
});
tx.commit();
```
## Notes
- `commit()` and `cancel()` are idempotent.
- `updateScene()` and `updateElements()` throw after the tx has ended.
- Conflict handling inside synthetic snapshots is fixed to `live-wins-per-prop`.
- Multi-tx interleaving is supported through manager-owned lifecycle tracking and active-tx priority.
+4 -6
View File
@@ -1943,9 +1943,9 @@ export const calculateFixedPointForElbowArrowBinding = (
return {
fixedPoint: normalizeFixedPoint([
(nonRotatedSnappedGlobalPoint[0] - hoveredElement.x) /
Math.max(hoveredElement.width, PRECISION),
hoveredElement.width,
(nonRotatedSnappedGlobalPoint[1] - hoveredElement.y) /
Math.max(hoveredElement.height, PRECISION),
hoveredElement.height,
]),
};
};
@@ -1976,11 +1976,9 @@ export const calculateFixedPointForNonElbowArrowBinding = (
// Calculate the ratio relative to the element's bounds
const fixedPointX =
(nonRotatedPoint[0] - hoveredElement.x) /
Math.max(hoveredElement.width, PRECISION);
(nonRotatedPoint[0] - hoveredElement.x) / hoveredElement.width;
const fixedPointY =
(nonRotatedPoint[1] - hoveredElement.y) /
Math.max(hoveredElement.height, PRECISION);
(nonRotatedPoint[1] - hoveredElement.y) / hoveredElement.height;
return {
fixedPoint: normalizeFixedPoint([fixedPointX, fixedPointY]),
+2 -2
View File
@@ -2124,8 +2124,8 @@ const normalizeArrowElementUpdate = (
offsetY < -MAX_POS ||
offsetY > MAX_POS ||
offsetX + points[points.length - 1][0] < -MAX_POS ||
offsetX + points[points.length - 1][0] > MAX_POS ||
offsetY + points[points.length - 1][1] < -MAX_POS ||
offsetY + points[points.length - 1][0] > MAX_POS ||
offsetX + points[points.length - 1][1] < -MAX_POS ||
offsetY + points[points.length - 1][1] > MAX_POS
) {
console.error(
-1
View File
@@ -88,7 +88,6 @@ export * from "./selection";
export * from "./shape";
export * from "./showSelectedShapeActions";
export * from "./sizeHelpers";
export * from "./snapping";
export * from "./sortElements";
export * from "./store";
export * from "./textElement";
+93 -352
View File
@@ -7,7 +7,6 @@ import {
type LocalPoint,
pointDistance,
vectorFromPoint,
line,
curveLength,
curvePointAtLength,
} from "@excalidraw/math";
@@ -30,9 +29,6 @@ import {
isPathALoop,
moveArrowAboveBindable,
projectFixedPointOntoDiagonal,
snapLinearElementPoint,
snapToDiscreteAngle,
type SnapLine,
type Store,
} from "@excalidraw/element";
@@ -52,7 +48,6 @@ import {
calculateFixedPointForNonElbowArrowBinding,
getBindingStrategyForDraggingBindingElementEndpoints,
isBindingEnabled,
maxBindingDistance_simple,
snapToMid,
updateBoundPoint,
} from "./binding";
@@ -61,7 +56,6 @@ import {
getElementPointsCoords,
getMinMaxXYFromCurvePathOps,
} from "./bounds";
import { getHoveredElementForBinding } from "./collision";
import { headingIsHorizontal, vectorToHeading } from "./heading";
import { mutateElement } from "./mutateElement";
@@ -300,10 +294,7 @@ export class LinearElementEditor {
scenePointerX: number,
scenePointerY: number,
linearElementEditor: LinearElementEditor,
): Pick<
AppState,
"suggestedBinding" | "selectedLinearElement" | "snapLines"
> | null {
): Pick<AppState, "suggestedBinding" | "selectedLinearElement"> | null {
const elementsMap = app.scene.getNonDeletedElementsMap();
const elements = app.scene.getNonDeletedElements();
const { elementId } = linearElementEditor;
@@ -320,26 +311,36 @@ export class LinearElementEditor {
linearElementEditor.customLineAngle ??
determineCustomLinearAngle(pivotPoint, element.points[idx]);
const { point: newDraggingPointPosition, snapLines } =
LinearElementEditor._getSnappedPointForLinearElement({
app,
event,
elements,
elementsMap,
// Determine if point movement should happen and how much
let deltaX = 0;
let deltaY = 0;
if (shouldRotateWithDiscreteAngle(event)) {
const [width, height] = LinearElementEditor._getShiftLockedDelta(
element,
pointIndex: idx,
scenePointerX,
scenePointerY,
pointerOffset: linearElementEditor.pointerOffset,
referencePoint: shouldRotateWithDiscreteAngle(event)
? pivotPoint
: null,
selectedPointsIndices: [idx],
elementsMap,
pivotPoint,
pointFrom(scenePointerX, scenePointerY),
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
customLineAngle,
});
);
const target = pointFrom<LocalPoint>(
width + pivotPoint[0],
height + pivotPoint[1],
);
const deltaX = newDraggingPointPosition[0] - point[0];
const deltaY = newDraggingPointPosition[1] - point[1];
deltaX = target[0] - point[0];
deltaY = target[1] - point[1];
} else {
const newDraggingPointPosition = LinearElementEditor.createPointAt(
element,
elementsMap,
scenePointerX - linearElementEditor.pointerOffset.x,
scenePointerY - linearElementEditor.pointerOffset.y,
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
);
deltaX = newDraggingPointPosition[0] - point[0];
deltaY = newDraggingPointPosition[1] - point[1];
}
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
@@ -397,8 +398,6 @@ export class LinearElementEditor {
// PERF: Avoid state updates if not absolutely necessary
if (
app.state.selectedLinearElement?.customLineAngle === customLineAngle &&
app.state.snapLines.length === 0 &&
snapLines.length === 0 &&
linearElementEditor.initialState.altFocusPoint &&
(!suggestedBinding ||
isShallowEqual(app.state.suggestedBinding ?? [], suggestedBinding))
@@ -437,7 +436,6 @@ export class LinearElementEditor {
return {
selectedLinearElement: newLinearElementEditor,
suggestedBinding,
snapLines,
};
}
@@ -447,10 +445,7 @@ export class LinearElementEditor {
scenePointerX: number,
scenePointerY: number,
linearElementEditor: LinearElementEditor,
): Pick<
AppState,
"suggestedBinding" | "selectedLinearElement" | "snapLines"
> | null {
): Pick<AppState, "suggestedBinding" | "selectedLinearElement"> | null {
const elementsMap = app.scene.getNonDeletedElementsMap();
const elements = app.scene.getNonDeletedElements();
const { elbowed, elementId, initialState } = linearElementEditor;
@@ -498,6 +493,7 @@ export class LinearElementEditor {
lastClickedPoint = element.points.length - 1;
}
// point that's being dragged (out of all selected points)
const draggingPoint = element.points[lastClickedPoint];
// The adjacent point to the one dragged point
const pivotPoint =
@@ -511,27 +507,35 @@ export class LinearElementEditor {
element.points.length - 1,
);
const { point: newDraggingPointPosition, snapLines } =
LinearElementEditor._getSnappedPointForLinearElement({
app,
event,
elements,
elementsMap,
// Determine if point movement should happen and how much
let deltaX = 0;
let deltaY = 0;
if (shouldRotateWithDiscreteAngle(event) && singlePointDragged) {
const [width, height] = LinearElementEditor._getShiftLockedDelta(
element,
pointIndex: lastClickedPoint,
scenePointerX,
scenePointerY,
pointerOffset: linearElementEditor.pointerOffset,
referencePoint:
shouldRotateWithDiscreteAngle(event) && singlePointDragged
? pivotPoint
: null,
selectedPointsIndices,
elementsMap,
pivotPoint,
pointFrom(scenePointerX, scenePointerY),
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
customLineAngle,
});
const deltaX = newDraggingPointPosition[0] - draggingPoint[0];
const deltaY = newDraggingPointPosition[1] - draggingPoint[1];
);
const target = pointFrom<LocalPoint>(
width + pivotPoint[0],
height + pivotPoint[1],
);
deltaX = target[0] - draggingPoint[0];
deltaY = target[1] - draggingPoint[1];
} else {
const newDraggingPointPosition = LinearElementEditor.createPointAt(
element,
elementsMap,
scenePointerX - linearElementEditor.pointerOffset.x,
scenePointerY - linearElementEditor.pointerOffset.y,
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
);
deltaX = newDraggingPointPosition[0] - draggingPoint[0];
deltaY = newDraggingPointPosition[1] - draggingPoint[1];
}
// Apply the point movement if needed
let suggestedBinding: AppState["suggestedBinding"] = null;
@@ -670,7 +674,6 @@ export class LinearElementEditor {
return {
selectedLinearElement: newLinearElementEditor,
suggestedBinding,
snapLines,
};
}
@@ -1175,10 +1178,7 @@ export class LinearElementEditor {
scenePointerX: number,
scenePointerY: number,
app: AppClassProperties,
): {
editingLinearElement: LinearElementEditor;
snapLines: readonly SnapLine[];
} | null {
): LinearElementEditor | null {
const appState = app.state;
if (!appState.selectedLinearElement?.isEditing) {
return null;
@@ -1187,10 +1187,7 @@ export class LinearElementEditor {
const elementsMap = app.scene.getNonDeletedElementsMap();
const element = LinearElementEditor.getElement(elementId, elementsMap);
if (!element) {
return {
editingLinearElement: appState.selectedLinearElement,
snapLines: appState.snapLines,
};
return appState.selectedLinearElement;
}
const { points } = element;
@@ -1202,37 +1199,36 @@ export class LinearElementEditor {
}
return appState.selectedLinearElement?.lastUncommittedPoint
? {
editingLinearElement: {
...appState.selectedLinearElement,
lastUncommittedPoint: null,
},
snapLines: [],
...appState.selectedLinearElement,
lastUncommittedPoint: null,
}
: {
editingLinearElement: appState.selectedLinearElement,
snapLines: [],
};
: appState.selectedLinearElement;
}
const anchor = points[points.length - 2];
const elements = app.scene.getNonDeletedElements();
const { point: newPoint, snapLines } =
LinearElementEditor._getSnappedPointForLinearElement({
app,
event,
elements,
elementsMap,
let newPoint: LocalPoint;
if (shouldRotateWithDiscreteAngle(event) && points.length >= 2) {
const anchor = points[points.length - 2];
const [width, height] = LinearElementEditor._getShiftLockedDelta(
element,
pointIndex: points.length - 1,
scenePointerX,
scenePointerY,
pointerOffset: appState.selectedLinearElement.pointerOffset,
referencePoint:
shouldRotateWithDiscreteAngle(event) && points.length >= 2
? anchor
: null,
selectedPointsIndices: [points.length - 1],
});
elementsMap,
anchor,
pointFrom(scenePointerX, scenePointerY),
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
);
newPoint = pointFrom(width + anchor[0], height + anchor[1]);
} else {
newPoint = LinearElementEditor.createPointAt(
element,
elementsMap,
scenePointerX - appState.selectedLinearElement.pointerOffset.x,
scenePointerY - appState.selectedLinearElement.pointerOffset.y,
event[KEYS.CTRL_OR_CMD] || isElbowArrow(element)
? null
: app.getEffectiveGridSize(),
);
}
if (lastPoint === lastUncommittedPoint) {
LinearElementEditor.movePoints(
@@ -1240,7 +1236,7 @@ export class LinearElementEditor {
app.scene,
new Map([
[
points.length - 1,
element.points.length - 1,
{
point: newPoint,
},
@@ -1250,13 +1246,9 @@ export class LinearElementEditor {
} else {
LinearElementEditor.addPoints(element, app.scene, [newPoint]);
}
return {
editingLinearElement: {
...appState.selectedLinearElement,
lastUncommittedPoint: element.points[element.points.length - 1],
},
snapLines,
...appState.selectedLinearElement,
lastUncommittedPoint: element.points[element.points.length - 1],
};
}
@@ -1282,53 +1274,18 @@ export class LinearElementEditor {
static getPointsGlobalCoordinates(
element: NonDeleted<ExcalidrawLinearElement>,
elementsMap: ElementsMap,
options: {
dragOffset?: { x: number; y: number };
excludePointsIndices?: readonly number[];
} = {},
): GlobalPoint[] {
const { dragOffset, excludePointsIndices } = options;
if (!element.points || element.points.length === 0) {
return [];
}
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
const cx = (x1 + x2) / 2;
const cy = (y1 + y2) / 2;
let elementX = element.x;
let elementY = element.y;
if (dragOffset) {
elementX += dragOffset.x;
elementY += dragOffset.y;
}
const globalPoints: GlobalPoint[] = [];
for (let i = 0; i < element.points.length; i++) {
// Skip the point being edited if specified
if (
excludePointsIndices?.length &&
excludePointsIndices.find((index) => index === i) !== undefined
) {
continue;
}
const p = element.points[i];
const globalX = elementX + p[0];
const globalY = elementY + p[1];
const rotated = pointRotateRads<GlobalPoint>(
pointFrom(globalX, globalY),
return element.points.map((p) => {
const { x, y } = element;
return pointRotateRads(
pointFrom(x + p[0], y + p[1]),
pointFrom(cx, cy),
element.angle,
);
globalPoints.push(rotated);
}
return globalPoints;
});
}
static getPointAtIndexGlobalCoordinates(
@@ -1882,222 +1839,6 @@ export class LinearElementEditor {
);
}
private static _getPointPlacementGridSize(
element: NonDeleted<ExcalidrawLinearElement>,
app: AppClassProperties,
event: Pick<KeyboardEvent | PointerEvent, typeof KEYS.CTRL_OR_CMD>,
): NullableGridSize {
return event[KEYS.CTRL_OR_CMD] || isElbowArrow(element)
? null
: app.getEffectiveGridSize();
}
private static _shouldSkipExternalSnapForBindableTarget({
appState,
elements,
elementsMap,
element,
pointIndex,
scenePoint,
selectedPointsIndices,
}: {
appState: AppState;
elements: readonly Ordered<NonDeletedExcalidrawElement>[];
elementsMap: NonDeletedSceneElementsMap;
element: NonDeleted<ExcalidrawLinearElement>;
pointIndex: number;
scenePoint: GlobalPoint;
selectedPointsIndices?: readonly number[];
}) {
if (
isElbowArrow(element) ||
!isBindingElement(element) ||
!isBindingEnabled(appState) ||
selectedPointsIndices?.length !== 1
) {
return false;
}
if (pointIndex !== 0 && pointIndex !== element.points.length - 1) {
return false;
}
return !!getHoveredElementForBinding(
scenePoint,
elements,
elementsMap,
maxBindingDistance_simple(appState.zoom),
);
}
private static _getSnappedPointForLinearElement({
app,
event,
elements,
elementsMap,
element,
pointIndex,
scenePointerX,
scenePointerY,
pointerOffset,
referencePoint,
selectedPointsIndices,
customLineAngle,
}: {
app: AppClassProperties;
event: PointerEvent | React.PointerEvent<HTMLCanvasElement>;
elements: readonly Ordered<NonDeletedExcalidrawElement>[];
elementsMap: NonDeletedSceneElementsMap;
element: NonDeleted<ExcalidrawLinearElement>;
pointIndex: number;
scenePointerX: number;
scenePointerY: number;
pointerOffset: Readonly<{ x: number; y: number }>;
referencePoint?: LocalPoint | null;
selectedPointsIndices?: readonly number[];
customLineAngle?: number | null;
}): {
point: LocalPoint;
snapLines: SnapLine[];
} {
const gridSize = LinearElementEditor._getPointPlacementGridSize(
element,
app,
event,
);
if (referencePoint) {
const referencePointCoords =
LinearElementEditor.getPointGlobalCoordinates(
element,
referencePoint,
elementsMap,
);
const [gridX, gridY] = getGridPoint(
scenePointerX,
scenePointerY,
gridSize,
);
let { width: dxFromReference, height: dyFromReference } =
getLockedLinearCursorAlignSize(
referencePointCoords[0],
referencePointCoords[1],
gridX,
gridY,
customLineAngle ?? undefined,
);
const effectiveGridX = referencePointCoords[0] + dxFromReference;
const effectiveGridY = referencePointCoords[1] + dyFromReference;
let snapLines: SnapLine[] = [];
const shouldSkipExternalSnap =
LinearElementEditor._shouldSkipExternalSnapForBindableTarget({
appState: app.state,
elements,
elementsMap,
element,
pointIndex,
scenePoint: pointFrom<GlobalPoint>(effectiveGridX, effectiveGridY),
selectedPointsIndices,
});
if (!isElbowArrow(element)) {
const { snapOffset, snapLines: nextSnapLines } = snapLinearElementPoint(
elements,
element,
pointFrom<GlobalPoint>(effectiveGridX, effectiveGridY),
app,
event,
elementsMap,
{
includeExternalPoints: !shouldSkipExternalSnap,
includeSelfPoints: true,
selectedPointsIndices,
},
);
snapLines = nextSnapLines;
if (nextSnapLines.length > 0) {
const result = snapToDiscreteAngle(
nextSnapLines,
line(
pointFrom(effectiveGridX, effectiveGridY),
pointFrom(referencePointCoords[0], referencePointCoords[1]),
),
pointFrom(gridX, gridY),
referencePointCoords,
);
if (result.snapLines.length > 0) {
dxFromReference = result.dxFromReference;
dyFromReference = result.dyFromReference;
snapLines = result.snapLines;
} else {
dxFromReference =
effectiveGridX + snapOffset.x - referencePointCoords[0];
dyFromReference =
effectiveGridY + snapOffset.y - referencePointCoords[1];
}
}
}
const [rotatedX, rotatedY] = pointRotateRads(
pointFrom(dxFromReference, dyFromReference),
pointFrom(0, 0),
-element.angle as Radians,
);
return {
point: pointFrom(
referencePoint[0] + rotatedX,
referencePoint[1] + rotatedY,
),
snapLines,
};
}
const originalPointerX = scenePointerX - pointerOffset.x;
const originalPointerY = scenePointerY - pointerOffset.y;
const shouldSkipExternalSnap =
LinearElementEditor._shouldSkipExternalSnapForBindableTarget({
appState: app.state,
elements,
elementsMap,
element,
pointIndex,
scenePoint: pointFrom<GlobalPoint>(originalPointerX, originalPointerY),
selectedPointsIndices,
});
const { snapOffset, snapLines } = snapLinearElementPoint(
elements,
element,
pointFrom(originalPointerX, originalPointerY),
app,
event,
elementsMap,
{
includeExternalPoints: !shouldSkipExternalSnap,
includeSelfPoints: true,
selectedPointsIndices,
},
);
return {
point: LinearElementEditor.createPointAt(
element,
elementsMap,
originalPointerX + snapOffset.x,
originalPointerY + snapOffset.y,
gridSize,
),
snapLines,
};
}
static getBoundTextElementPosition = (
element: ExcalidrawLinearElement,
boundTextElement: ExcalidrawTextElementWithContainer,
+189 -9
View File
@@ -111,6 +111,67 @@ export class Store {
this.scheduleAction(CaptureUpdateAction.IMMEDIATELY);
}
/**
* Commits a synthetic durable history entry without changing the live scene.
*
* Builds StoreSnapshot StoreChange StoreDelta from the provided
* logical before/after element maps and optional appState patches, then
* emits the resulting durable increment immediately through an isolated
* path that does not flush pending micro actions.
*
* appState patches are merged on top of the current observed appState
* baseline so only the provided keys participate in the synthetic diff.
*/
public commitSyntheticIncrement(params: {
logicalBefore: {
elements: SceneElementsMap;
appState?: Partial<ObservedAppState>;
};
logicalAfter: {
elements: SceneElementsMap;
appState?: Partial<ObservedAppState>;
};
}): boolean {
const { logicalBefore, logicalAfter } = params;
const observedAppStateBaseline = this.snapshot.appState;
const syntheticAppStateBefore = logicalBefore.appState
? { ...observedAppStateBaseline, ...logicalBefore.appState }
: observedAppStateBaseline;
const syntheticAppStateAfter = logicalAfter.appState
? { ...observedAppStateBaseline, ...logicalAfter.appState }
: observedAppStateBaseline;
const didAppStateChange = Delta.isRightDifferent(
syntheticAppStateBefore,
syntheticAppStateAfter,
);
const prevSnapshot = StoreSnapshot.create(
logicalBefore.elements,
syntheticAppStateBefore,
{
didElementsChange: true,
didAppStateChange,
},
);
const nextSnapshot = StoreSnapshot.create(
logicalAfter.elements,
syntheticAppStateAfter,
{
didElementsChange: true,
didAppStateChange,
},
);
const change = StoreChange.create(prevSnapshot, nextSnapshot);
const delta = StoreDelta.calculate(prevSnapshot, nextSnapshot);
if (delta.isEmpty()) {
return false;
}
this.emitIsolatedDurableIncrement(change, delta);
return true;
}
/**
* Schedule special "micro" actions, to-be executed before the next commit, before it executes a scheduled "macro" action.
*/
@@ -206,6 +267,7 @@ export class Store {
public clear(): void {
this.snapshot = StoreSnapshot.empty();
this.scheduledMacroActions = new Set();
this.scheduledMicroActions = [];
}
/**
@@ -245,6 +307,24 @@ export class Store {
}
}
/**
* Emits a synthetic durable increment immediately without draining the
* regular micro-action queue.
*/
private emitIsolatedDurableIncrement(change: StoreChange, delta: StoreDelta) {
const nextSnapshot = this.applyChangeToSnapshot(change);
if (!nextSnapshot) {
return;
}
try {
this.emitDurableIncrement(nextSnapshot, change, delta);
} finally {
this.snapshot = nextSnapshot;
}
}
/**
* Performs change calculation and emits an ephemeral increment.
*
@@ -491,6 +571,89 @@ export class EphemeralIncrement extends StoreIncrement {
}
}
/**
* Serializable delta marker used to recover pre-tx undo baselines
* without rewriting history stack entries.
*/
export type TxUndoOverride = {
txId: string;
elementId: string;
prop: string;
expectedInsertedValue: unknown;
preTxBaselineValue: unknown;
consumedKey: string;
};
export type StoreDeltaMarkers = {
txUndoOverrides?: TxUndoOverride[];
};
const cloneTxUndoOverride = (override: TxUndoOverride): TxUndoOverride => ({
...override,
});
const cloneStoreDeltaMarkers = (
markers: StoreDeltaMarkers | undefined,
): StoreDeltaMarkers | undefined =>
markers
? {
...markers,
txUndoOverrides: markers.txUndoOverrides?.map(cloneTxUndoOverride),
}
: undefined;
const pruneStoreDeltaMarkers = (delta: StoreDelta) => {
const txUndoOverrides = delta.markers?.txUndoOverrides;
if (!txUndoOverrides || txUndoOverrides.length === 0) {
return;
}
const updatedEntries = delta.elements.updated as Record<
string,
Delta<Record<string, unknown>>
>;
const nextTxUndoOverrides = txUndoOverrides.filter((override) => {
const updatedEntry = updatedEntries[override.elementId];
return (
!!updatedEntry &&
Object.prototype.hasOwnProperty.call(updatedEntry.inserted, override.prop)
);
});
if (nextTxUndoOverrides.length === txUndoOverrides.length) {
return;
}
if (nextTxUndoOverrides.length === 0) {
delta.markers = undefined;
return;
}
delta.markers = {
...delta.markers,
txUndoOverrides: nextTxUndoOverrides.map(cloneTxUndoOverride),
};
};
export const mergeStoreDeltaMarkers = (
delta: StoreDelta,
markers: StoreDeltaMarkers,
) => {
const txUndoOverrides = markers.txUndoOverrides ?? [];
if (txUndoOverrides.length === 0) {
return;
}
const existing = delta.markers?.txUndoOverrides ?? [];
delta.markers = {
...delta.markers,
txUndoOverrides: [
...existing.map(cloneTxUndoOverride),
...txUndoOverrides.map(cloneTxUndoOverride),
],
};
};
/**
* Represents a captured delta by the Store.
*/
@@ -499,6 +662,7 @@ export class StoreDelta {
public readonly id: string,
public readonly elements: ElementsDelta,
public readonly appState: AppStateDelta,
public markers?: StoreDeltaMarkers,
) {}
/**
@@ -508,12 +672,16 @@ export class StoreDelta {
elements: ElementsDelta,
appState: AppStateDelta,
opts: {
id: string;
} = {
id: randomId(),
},
id?: string;
markers?: StoreDeltaMarkers;
} = {},
) {
return new this(opts.id, elements, appState);
return new this(
opts.id ?? randomId(),
elements,
appState,
cloneStoreDeltaMarkers(opts.markers),
);
}
/**
@@ -538,11 +706,12 @@ export class StoreDelta {
* Restore a store delta instance from a DTO.
*/
public static restore(storeDeltaDTO: DTO<StoreDelta>) {
const { id, elements, appState } = storeDeltaDTO;
const { id, elements, appState, markers } = storeDeltaDTO;
return new this(
id,
ElementsDelta.restore(elements),
AppStateDelta.restore(appState),
cloneStoreDeltaMarkers(markers),
);
}
@@ -553,11 +722,12 @@ export class StoreDelta {
id,
elements: { added, removed, updated },
appState: { delta: appStateDelta },
markers,
}: DTO<StoreDelta>) {
const elements = ElementsDelta.create(added, removed, updated);
const appState = AppStateDelta.create(appStateDelta);
return new this(id, elements, appState);
return new this(id, elements, appState, cloneStoreDeltaMarkers(markers));
}
/**
@@ -569,8 +739,10 @@ export class StoreDelta {
for (const delta of deltas) {
aggregatedDelta.elements.squash(delta.elements);
aggregatedDelta.appState.squash(delta.appState);
mergeStoreDeltaMarkers(aggregatedDelta, delta.markers ?? {});
}
pruneStoreDeltaMarkers(aggregatedDelta);
return aggregatedDelta;
}
@@ -578,7 +750,12 @@ export class StoreDelta {
* Inverse store delta, creates new instance of `StoreDelta`.
*/
public static inverse(delta: StoreDelta) {
return this.create(delta.elements.inverse(), delta.appState.inverse());
const inversed = this.create(
delta.elements.inverse(),
delta.appState.inverse(),
{ markers: delta.markers },
);
return inversed;
}
/**
@@ -614,7 +791,7 @@ export class StoreDelta {
nextElements: SceneElementsMap,
modifierOptions?: "deleted" | "inserted",
): StoreDelta {
return this.create(
const nextDelta = this.create(
delta.elements.applyLatestChanges(
prevElements,
nextElements,
@@ -623,8 +800,11 @@ export class StoreDelta {
delta.appState,
{
id: delta.id,
markers: delta.markers,
},
);
pruneStoreDeltaMarkers(nextDelta);
return nextDelta;
}
public static empty() {
@@ -155,24 +155,6 @@ describe("Test Linear Elements", () => {
});
};
const dragMove = (startPoint: GlobalPoint, endPoint: GlobalPoint) => {
fireEvent.pointerDown(interactiveCanvas, {
clientX: startPoint[0],
clientY: startPoint[1],
});
fireEvent.pointerMove(interactiveCanvas, {
clientX: endPoint[0],
clientY: endPoint[1],
});
};
const dragEnd = (endPoint: GlobalPoint) => {
fireEvent.pointerUp(interactiveCanvas, {
clientX: endPoint[0],
clientY: endPoint[1],
});
};
const deletePoint = (point: GlobalPoint) => {
fireEvent.pointerDown(interactiveCanvas, {
clientX: point[0],
@@ -276,73 +258,6 @@ describe("Test Linear Elements", () => {
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
});
it("shows snap lines and snaps the endpoint when creating a line", () => {
const rect = API.createElement({
type: "rectangle",
x: 100,
y: 100,
width: 40,
height: 40,
});
API.setElements([rect]);
API.setAppState({ objectsSnapModeEnabled: true });
UI.clickTool("line");
const startPoint = pointFrom<GlobalPoint>(20, 20);
const pointerNearCorner = pointFrom<GlobalPoint>(95, 95);
dragMove(startPoint, pointerNearCorner);
expect(h.state.snapLines.length).toBeGreaterThan(0);
dragEnd(pointerNearCorner);
const line = h.elements.find(
(element): element is ExcalidrawLinearElement => element.type === "line",
);
expect(line).toBeDefined();
const endpoint = LinearElementEditor.getPointGlobalCoordinates(
line!,
line!.points[line!.points.length - 1],
h.app.scene.getNonDeletedElementsMap(),
);
expect(endpoint).toEqual(pointFrom<GlobalPoint>(100, 100));
});
it("prefers binding over external snaps when creating an arrow endpoint", () => {
const rect = API.createElement({
type: "rectangle",
x: 100,
y: 100,
width: 40,
height: 40,
});
API.setElements([rect]);
API.setAppState({ objectsSnapModeEnabled: true });
UI.clickTool("arrow");
const startPoint = pointFrom<GlobalPoint>(20, 20);
const pointerNearBindable = pointFrom<GlobalPoint>(96, 118);
dragMove(startPoint, pointerNearBindable);
expect(h.state.suggestedBinding?.element.id).toBe(rect.id);
expect(h.state.snapLines).toEqual([]);
dragEnd(pointerNearBindable);
const arrow = h.elements.find(
(element): element is ExcalidrawLinearElement => element.type === "arrow",
);
expect(arrow?.endBinding?.elementId).toBe(rect.id);
});
it("should enter line editor via enter (line)", () => {
createTwoPointerLinearElement("line");
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
@@ -486,77 +401,6 @@ describe("Test Linear Elements", () => {
`);
});
it("shows snap lines when dragging a point to another line point axis", () => {
const line = API.createElement({
type: "line",
x: 20,
y: 20,
width: 100,
height: 50,
roughness: 0,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(50, 50),
pointFrom<LocalPoint>(100, 0),
],
});
API.setElements([line]);
API.setAppState({ objectsSnapModeEnabled: true });
enterLineEditingMode(line);
const middlePoint = pointFrom<GlobalPoint>(70, 70);
const pointerNearEndPointX = pointFrom<GlobalPoint>(117, 65);
dragMove(middlePoint, pointerNearEndPointX);
expect(h.state.snapLines.length).toBeGreaterThan(0);
dragEnd(pointerNearEndPointX);
expect(API.getElement(line).points[1]).toEqual(
pointFrom<LocalPoint>(100, 45),
);
});
it("prefers binding over external snaps when dragging an existing arrow endpoint", () => {
const rect = API.createElement({
type: "rectangle",
x: 100,
y: 100,
width: 40,
height: 40,
});
const arrow = API.createElement({
type: "arrow",
x: 20,
y: 20,
width: 40,
height: 0,
points: [pointFrom<LocalPoint>(0, 0), pointFrom<LocalPoint>(40, 0)],
});
API.setElements([rect, arrow]);
API.setAppState({ objectsSnapModeEnabled: true });
enterLineEditingMode(arrow);
const endPoint = LinearElementEditor.getPointGlobalCoordinates(
arrow,
arrow.points[arrow.points.length - 1],
h.app.scene.getNonDeletedElementsMap(),
);
const pointerNearBindable = pointFrom<GlobalPoint>(96, 118);
dragMove(endPoint, pointerNearBindable);
expect(h.state.suggestedBinding?.element.id).toBe(rect.id);
expect(h.state.snapLines).toEqual([]);
dragEnd(pointerNearBindable);
expect(API.getElement(arrow).endBinding?.elementId).toBe(rect.id);
});
it("should update the midpoints when element roundness changed", async () => {
createThreePointerLinearElement("line");
+140
View File
@@ -0,0 +1,140 @@
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
import { arrayToMap } from "@excalidraw/common";
import type App from "@excalidraw/excalidraw/components/App";
import type { ObservedAppState } from "@excalidraw/excalidraw/types";
import type {
ExcalidrawElement,
SceneElementsMap,
} from "@excalidraw/element/types";
import {
CaptureUpdateAction,
Store,
StoreSnapshot,
newElementWith,
} from "../src";
const getScheduledMicroActionCount = (store: Store) =>
(
store as unknown as {
scheduledMicroActions: Array<() => void>;
}
).scheduledMicroActions.length;
const flushMicroActions = (store: Store) => {
(
store as unknown as {
flushMicroActions: () => void;
}
).flushMicroActions();
};
const toSceneElementsMap = (
elements: readonly ExcalidrawElement[],
): SceneElementsMap => arrayToMap(elements) as SceneElementsMap;
const createStoreHarness = (elements: SceneElementsMap) => {
const appState: ObservedAppState = StoreSnapshot.empty().appState;
const app = {
scene: {
getElementsMapIncludingDeleted: () => elements,
},
state: appState,
} as unknown as App;
const store = new Store(app);
store.snapshot = StoreSnapshot.create(elements, appState);
return { store, appState };
};
describe("Store synthetic increment isolation", () => {
it("keeps pending immediate micro actions queued across synthetic commit", () => {
const element = API.createElement({
type: "rectangle",
id: "store-isolated-immediate",
x: 0,
y: 0,
});
const baselineElements = toSceneElementsMap([element]);
const { store } = createStoreHarness(baselineElements);
const incrementTypes: Array<"durable" | "ephemeral"> = [];
const detach = store.onStoreIncrementEmitter.on((increment) => {
incrementTypes.push(increment.type);
});
store.scheduleMicroAction({
action: CaptureUpdateAction.IMMEDIATELY,
elements: [newElementWith(element, { y: 240 })],
appState: undefined,
});
expect(getScheduledMicroActionCount(store)).toBe(1);
const committed = store.commitSyntheticIncrement({
logicalBefore: {
elements: baselineElements,
},
logicalAfter: {
elements: toSceneElementsMap([newElementWith(element, { x: 120 })]),
},
});
expect(committed).toBe(true);
expect(incrementTypes).toEqual(["durable"]);
expect(getScheduledMicroActionCount(store)).toBe(1);
flushMicroActions(store);
expect(incrementTypes).toEqual(["durable", "durable"]);
expect(getScheduledMicroActionCount(store)).toBe(0);
detach();
});
it("keeps pending eventually micro actions queued across synthetic commit", () => {
const element = API.createElement({
type: "rectangle",
id: "store-isolated-eventually",
x: 0,
y: 0,
});
const baselineElements = toSceneElementsMap([element]);
const { store } = createStoreHarness(baselineElements);
const incrementTypes: Array<"durable" | "ephemeral"> = [];
const detach = store.onStoreIncrementEmitter.on((increment) => {
incrementTypes.push(increment.type);
});
store.scheduleMicroAction({
action: CaptureUpdateAction.EVENTUALLY,
elements: [newElementWith(element, { y: 240 })],
appState: undefined,
});
expect(getScheduledMicroActionCount(store)).toBe(1);
const committed = store.commitSyntheticIncrement({
logicalBefore: {
elements: baselineElements,
},
logicalAfter: {
elements: toSceneElementsMap([newElementWith(element, { x: 120 })]),
},
});
expect(committed).toBe(true);
expect(incrementTypes).toEqual(["durable"]);
expect(getScheduledMicroActionCount(store)).toBe(1);
flushMicroActions(store);
expect(incrementTypes).toEqual(["durable", "ephemeral"]);
expect(getScheduledMicroActionCount(store)).toBe(0);
detach();
});
});
+44 -76
View File
@@ -239,16 +239,6 @@ import {
hitElementBoundingBox,
isLineElement,
isSimpleArrow,
isGridModeEnabled,
SnapCache,
isActiveToolNonLinearSnappable,
getSnapLinesAtPointer,
isSnappingEnabled,
getReferenceSnapPoints,
getVisibleGaps,
snapDraggedElements,
snapNewElement,
snapResizingElements,
StoreDelta,
type ApplyToOptions,
positionElementsOnGrid,
@@ -371,6 +361,7 @@ import { restoreAppState, restoreElements } from "../data/restore";
import { getCenter, getDistance } from "../gesture";
import { History } from "../history";
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
import { TransactionManager } from "../transaction";
import {
calculateScrollCenter,
@@ -406,6 +397,18 @@ import {
import { Fonts } from "../fonts";
import { editorJotaiStore, type WritableAtom } from "../editor-jotai";
import { ImageSceneDataError } from "../errors";
import {
getSnapLinesAtPointer,
snapDraggedElements,
isActiveToolNonLinearSnappable,
snapNewElement,
snapResizingElements,
isSnappingEnabled,
getVisibleGaps,
getReferenceSnapPoints,
SnapCache,
isGridModeEnabled,
} from "../snapping";
import { Renderer } from "../scene/Renderer";
import {
setEraserCursor,
@@ -635,7 +638,8 @@ class App extends React.Component<AppProps, AppState> {
public library: AppClassProperties["library"];
public libraryItemsFromStorage: LibraryItems | undefined;
public id: string;
private store: Store;
public transactionManager: TransactionManager;
public store: Store;
private history: History;
public excalidrawContainerValue: {
container: HTMLDivElement | null;
@@ -783,29 +787,6 @@ class App extends React.Component<AppProps, AppState> {
return api;
}
private withStableSnapLines<T extends { snapLines: AppState["snapLines"] }>(
state: T,
): T {
const snapLines = updateStable(this.state.snapLines, state.snapLines);
return snapLines === state.snapLines
? state
: {
...state,
snapLines,
};
}
private shouldUpdateSelectedLinearElementState(
selectedLinearElement: AppState["selectedLinearElement"],
snapLines: AppState["snapLines"],
) {
return (
selectedLinearElement !== this.state.selectedLinearElement ||
snapLines !== this.state.snapLines
);
}
constructor(props: AppProps) {
super(props);
const defaultAppState = getDefaultAppState();
@@ -853,6 +834,8 @@ class App extends React.Component<AppProps, AppState> {
this.store = new Store(this);
this.history = new History(this.store);
this.transactionManager = new TransactionManager(this);
this.transactionManager.attachHistory(this.history);
this.excalidrawContainerValue = {
container: this.excalidrawContainerRef.current,
@@ -860,7 +843,6 @@ class App extends React.Component<AppProps, AppState> {
};
this.fonts = new Fonts(this.scene);
this.history = new History(this.store);
this.actionManager.registerAll(actions);
this.actionManager.registerAction(createUndoAction(this.history));
@@ -4623,6 +4605,11 @@ class App extends React.Component<AppProps, AppState> {
);
};
/** Creates a new transaction for batching mutations into a single undo entry. */
public createTransaction: TransactionManager["create"] = () => {
return this.transactionManager.create();
};
public mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
element: TElement,
updates: ElementUpdate<TElement>,
@@ -6807,10 +6794,7 @@ class App extends React.Component<AppProps, AppState> {
if (
!this.state.newElement &&
(isActiveToolNonLinearSnappable(this.state.activeTool.type) ||
((this.state.activeTool.type === "line" ||
this.state.activeTool.type === "arrow") &&
this.state.currentItemArrowType !== ARROW_TYPE.elbow))
isActiveToolNonLinearSnappable(this.state.activeTool.type)
) {
const { originOffset, snapLines } = getSnapLinesAtPointer(
this.scene.getNonDeletedElements(),
@@ -6859,7 +6843,7 @@ class App extends React.Component<AppProps, AppState> {
this.state.selectedLinearElement?.isEditing &&
!this.state.selectedLinearElement.isDragging
) {
const result = this.state.newElement
const editingLinearElement = this.state.newElement
? null
: LinearElementEditor.handlePointerMoveInEditMode(
event,
@@ -6868,33 +6852,18 @@ class App extends React.Component<AppProps, AppState> {
this,
);
if (result) {
const { editingLinearElement, snapLines } = result;
const nextState = this.withStableSnapLines({
selectedLinearElement: editingLinearElement,
snapLines,
});
if (
editingLinearElement &&
this.shouldUpdateSelectedLinearElementState(
nextState.selectedLinearElement,
nextState.snapLines,
)
) {
// Since we are reading from previous state which is not possible with
// automatic batching in React 18 hence using flush sync to synchronously
// update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
flushSync(() => {
this.setState(nextState);
if (
editingLinearElement &&
editingLinearElement !== this.state.selectedLinearElement
) {
// Since we are reading from previous state which is not possible with
// automatic batching in React 18 hence using flush sync to synchronously
// update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
flushSync(() => {
this.setState({
selectedLinearElement: editingLinearElement,
});
}
if (
editingLinearElement.lastUncommittedPoint == null &&
this.state.suggestedBinding
) {
this.setState({ suggestedBinding: null });
}
});
}
}
@@ -9752,27 +9721,25 @@ class App extends React.Component<AppProps, AppState> {
pointerDownState.lastCoords.x = pointerCoords.x;
pointerDownState.lastCoords.y = pointerCoords.y;
pointerDownState.drag.hasOccurred = true;
const nextState = this.withStableSnapLines(newState);
// NOTE: Optimize setState calls because it
// affects history and performance
if (
nextState.suggestedBinding !== this.state.suggestedBinding ||
newState.suggestedBinding !== this.state.suggestedBinding ||
!isShallowEqual(
nextState.selectedLinearElement?.selectedPointsIndices ?? [],
newState.selectedLinearElement?.selectedPointsIndices ?? [],
this.state.selectedLinearElement?.selectedPointsIndices ?? [],
) ||
nextState.selectedLinearElement?.hoverPointIndex !==
newState.selectedLinearElement?.hoverPointIndex !==
this.state.selectedLinearElement?.hoverPointIndex ||
nextState.selectedLinearElement?.customLineAngle !==
newState.selectedLinearElement?.customLineAngle !==
this.state.selectedLinearElement?.customLineAngle ||
this.state.selectedLinearElement.isDragging !==
nextState.selectedLinearElement?.isDragging ||
newState.selectedLinearElement?.isDragging ||
this.state.selectedLinearElement?.initialState?.altFocusPoint !==
nextState.selectedLinearElement?.initialState?.altFocusPoint ||
nextState.snapLines !== this.state.snapLines
newState.selectedLinearElement?.initialState?.altFocusPoint
) {
this.setState(nextState);
this.setState(newState);
}
return;
@@ -10461,7 +10428,8 @@ class App extends React.Component<AppProps, AppState> {
this.lassoTrail.endPath();
this.previousPointerMoveCoords = null;
SnapCache.destroy();
SnapCache.setReferenceSnapPoints(null);
SnapCache.setVisibleGaps(null);
this.savePointer(childEvent.clientX, childEvent.clientY, "up");
@@ -3,7 +3,6 @@ import { CANVAS_SEARCH_TAB, DEFAULT_SIDEBAR } from "@excalidraw/common";
import {
isFlowchartNodeElement,
isImageElement,
isGridModeEnabled,
isLinearElement,
isLineElement,
isTextBindableContainer,
@@ -17,6 +16,7 @@ import type { EditorInterface } from "@excalidraw/common";
import { t } from "../i18n";
import { getShortcutKey } from "../shortcut";
import { isEraserActive } from "../appState";
import { isGridModeEnabled } from "../snapping";
import "./HintViewer.scss";
@@ -12,11 +12,10 @@ import { frameAndChildrenSelectedTogether } from "@excalidraw/element";
import { elementsAreInSameGroup } from "@excalidraw/element";
import { isGridModeEnabled } from "@excalidraw/element";
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
import { t } from "../../i18n";
import { isGridModeEnabled } from "../../snapping";
import { useExcalidrawAppState, useExcalidrawSetAppState } from "../App";
import { Island } from "../Island";
import { CloseIcon } from "../icons";
+6 -41
View File
@@ -96,8 +96,6 @@ type RestoredAppState = Omit<
"offsetTop" | "offsetLeft" | "width" | "height"
>;
const MAX_ARROW_PX = 75_000;
export const AllowedExcalidrawActiveTools: Record<
AppState["activeTool"]["type"],
boolean
@@ -469,8 +467,8 @@ export const restoreElement = (
element.endArrowhead === undefined
? "arrow"
: normalizeArrowhead(element.endArrowhead);
const x = element.x as number | undefined;
const y = element.y as number | undefined;
const x: number | undefined = element.x;
const y: number | undefined = element.y;
const points: readonly LocalPoint[] | undefined = // migrate old arrow model to new one
!Array.isArray(element.points) || element.points.length < 2
? [pointFrom(0, 0), pointFrom(element.width, element.height)]
@@ -495,8 +493,8 @@ export const restoreElement = (
startArrowhead,
endArrowhead,
points,
x: x ?? 0,
y: y ?? 0,
x,
y,
elbowed: (element as ExcalidrawArrowElement).elbowed,
...getSizeFromPoints(points),
};
@@ -515,44 +513,12 @@ export const restoreElement = (
})
: restoreElementWithProperties(element as ExcalidrawArrowElement, base);
const normalizedRestoredElement = {
return {
...restoredElement,
...LinearElementEditor.getNormalizeElementPointsAndCoords(
restoredElement,
),
};
// Last resort fix for extremely large arrows
if (
normalizedRestoredElement.width > MAX_ARROW_PX ||
normalizedRestoredElement.height > MAX_ARROW_PX
) {
console.error(
`Removing extremely large arrow ${
normalizedRestoredElement.id
} (type: ${
isElbowArrow(normalizedRestoredElement) ? "elbow" : "simple"
}, width: ${normalizedRestoredElement.width}, height: ${
normalizedRestoredElement.height
}, x: ${normalizedRestoredElement.x}, y: ${
normalizedRestoredElement.y
})`,
);
return {
...normalizedRestoredElement,
x: 0,
y: 0,
width: 100,
height: 100,
points: [
pointFrom<LocalPoint>(0, 0),
pointFrom<LocalPoint>(100, 100),
],
isDeleted: true,
};
}
return normalizedRestoredElement;
}
// generic elements
@@ -700,7 +666,6 @@ export const restoreElements = <T extends ExcalidrawElement>(
const existingElementsMap = existingElements
? arrayToMap(existingElements)
: null;
const restoredElements = syncInvalidIndices(
(targetElements || []).reduce((elements, element) => {
// filtering out selection, which is legacy, no longer kept in elements,
@@ -797,7 +762,7 @@ export const restoreElements = <T extends ExcalidrawElement>(
}
}
// NOTE (mtolmacs): Temporary fix for invalid/self-bound elbow arrows
// NOTE (mtolmacs): Temporary fix for extremely large arrows
// Need to iterate again so we have attached text nodes in elementsMap
return restoredElements.map((element) => {
if (
+60 -10
View File
@@ -87,10 +87,22 @@ export class HistoryChangedEvent {
) {}
}
export type HistoryBeforeRecordListener = (delta: StoreDelta) => void;
export type HistoryPerformDirection = "undo" | "redo";
export type HistoryEffectiveDeltaResolverContext = {
direction: HistoryPerformDirection;
};
export type HistoryEffectiveDeltaResolver = (
delta: HistoryDelta,
context: HistoryEffectiveDeltaResolverContext,
) => HistoryDelta;
export class History {
public readonly onHistoryChangedEmitter = new Emitter<
[HistoryChangedEvent]
>();
private readonly onBeforeRecordEmitter = new Emitter<[StoreDelta]>();
private effectiveDeltaResolver: HistoryEffectiveDeltaResolver | null = null;
public readonly undoStack: HistoryDelta[] = [];
public readonly redoStack: HistoryDelta[] = [];
@@ -105,6 +117,20 @@ export class History {
constructor(private readonly store: Store) {}
/**
* Registers a hook that runs before a durable delta is converted
* into a history entry.
*/
public onBeforeRecord(callback: HistoryBeforeRecordListener) {
return this.onBeforeRecordEmitter.on(callback);
}
public setEffectiveDeltaResolver(
resolver: HistoryEffectiveDeltaResolver | null,
) {
this.effectiveDeltaResolver = resolver;
}
public clear() {
this.undoStack.length = 0;
this.redoStack.length = 0;
@@ -119,6 +145,8 @@ export class History {
return;
}
this.onBeforeRecordEmitter.trigger(delta);
// construct history entry, so once it's emitted, it's not recorded again
const historyDelta = HistoryDelta.inverse(delta);
@@ -131,15 +159,14 @@ export class History {
this.redoStack.length = 0;
}
this.onHistoryChangedEmitter.trigger(
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
);
this.emitHistoryChanged();
}
public undo(elements: SceneElementsMap, appState: AppState) {
return this.perform(
elements,
appState,
"undo",
() => History.pop(this.undoStack),
(entry: HistoryDelta) => History.push(this.redoStack, entry),
);
@@ -149,6 +176,7 @@ export class History {
return this.perform(
elements,
appState,
"redo",
() => History.pop(this.redoStack),
(entry: HistoryDelta) => History.push(this.undoStack, entry),
);
@@ -157,6 +185,7 @@ export class History {
private perform(
elements: SceneElementsMap,
appState: AppState,
direction: HistoryPerformDirection,
pop: () => HistoryDelta | null,
push: (entry: HistoryDelta) => void,
): [SceneElementsMap, AppState] | void {
@@ -177,9 +206,15 @@ export class History {
// iterate through the history entries in case they result in no visible changes
while (historyDelta) {
// Roundtrip invariant: whichever delta we execute must be the one that
// continues through applyLatestChanges -> inverse -> opposite stack.
let entryToPush = historyDelta;
try {
const effectiveDelta = this.resolveEffectiveDelta(historyDelta, {
direction,
});
[nextElements, nextAppState, containsVisibleChange] =
historyDelta.applyTo(nextElements, nextAppState, prevSnapshot);
effectiveDelta.applyTo(nextElements, nextAppState, prevSnapshot);
const prevElements = prevSnapshot.elements;
const nextSnapshot = prevSnapshot.maybeClone(
@@ -190,7 +225,7 @@ export class History {
const change = StoreChange.create(prevSnapshot, nextSnapshot);
const delta = HistoryDelta.applyLatestChanges(
historyDelta,
effectiveDelta,
prevElements,
nextElements,
);
@@ -203,12 +238,12 @@ export class History {
delta,
});
historyDelta = delta;
entryToPush = delta;
}
prevSnapshot = nextSnapshot;
} finally {
push(historyDelta);
push(entryToPush);
}
if (containsVisibleChange) {
@@ -222,12 +257,16 @@ export class History {
} finally {
// trigger the history change event before returning completely
// also trigger it just once, no need doing so on each entry
this.onHistoryChangedEmitter.trigger(
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
);
this.emitHistoryChanged();
}
}
private emitHistoryChanged() {
this.onHistoryChangedEmitter.trigger(
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
);
}
private static pop(stack: HistoryDelta[]): HistoryDelta | null {
if (!stack.length) {
return null;
@@ -246,4 +285,15 @@ export class History {
const inversedEntry = HistoryDelta.inverse(entry);
return stack.push(inversedEntry);
}
private resolveEffectiveDelta(
delta: HistoryDelta,
context: HistoryEffectiveDeltaResolverContext,
): HistoryDelta {
if (!this.effectiveDeltaResolver) {
return delta;
}
return this.effectiveDeltaResolver(delta, context);
}
}
+1 -1
View File
@@ -83,13 +83,13 @@
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/highlight": "^1.0.0",
"@excalidraw/common": "0.18.0",
"@excalidraw/element": "0.18.0",
"@excalidraw/laser-pointer": "1.3.1",
"@excalidraw/math": "0.18.0",
"@excalidraw/mermaid-to-excalidraw": "2.2.2",
"@excalidraw/random-username": "1.1.0",
"@lezer/highlight": "^1.0.0",
"browser-fs-access": "0.38.0",
"canvas-roundrect-polyfill": "0.0.1",
"clsx": "1.1.1",
+1 -2
View File
@@ -2,8 +2,7 @@ import { pointFrom, type GlobalPoint, type LocalPoint } from "@excalidraw/math";
import { THEME } from "@excalidraw/common";
import type { PointSnapLine, PointerSnapLine } from "@excalidraw/element";
import type { PointSnapLine, PointerSnapLine } from "../snapping";
import type { InteractiveCanvasAppState } from "../types";
const SNAP_COLOR_LIGHT = "#ff6b6b";
@@ -1,8 +1,4 @@
import {
isCloseTo,
line,
linesIntersectAt,
pointDistance,
pointFrom,
pointRotateRads,
rangeInclusive,
@@ -17,7 +13,7 @@ import {
getDraggedElementsBounds,
getElementAbsoluteCoords,
} from "@excalidraw/element";
import { isBoundToContainer, isElbowArrow } from "@excalidraw/element";
import { isBoundToContainer } from "@excalidraw/element";
import { getMaximumGroups } from "@excalidraw/element";
@@ -33,18 +29,14 @@ import type { MaybeTransformHandleType } from "@excalidraw/element";
import type {
ElementsMap,
ExcalidrawElement,
ExcalidrawLinearElement,
NonDeletedExcalidrawElement,
NonDeleted,
} from "@excalidraw/element/types";
import type {
AppClassProperties,
AppState,
KeyboardModifiersObject,
} from "@excalidraw/excalidraw/types";
import { LinearElementEditor } from "./linearElementEditor";
} from "./types";
const SNAP_DISTANCE = 8;
@@ -130,11 +122,6 @@ export type SnapLine = PointSnapLine | GapSnapLine | PointerSnapLine;
export class SnapCache {
private static referenceSnapPoints: GlobalPoint[] | null = null;
private static linearElementAxisSnapTargets: {
editingElementId: ExcalidrawElement["id"];
snapTargets: GlobalPoint[];
} | null = null;
private static visibleGaps: {
verticalGaps: Gap[];
horizontalGaps: Gap[];
@@ -148,27 +135,6 @@ export class SnapCache {
return SnapCache.referenceSnapPoints;
};
public static setLinearElementAxisSnapTargets = (
editingElementId: ExcalidrawElement["id"],
snapTargets: GlobalPoint[] | null,
) => {
SnapCache.linearElementAxisSnapTargets = snapTargets
? {
editingElementId,
snapTargets,
}
: null;
};
public static getLinearElementAxisSnapTargets = (
editingElementId: ExcalidrawElement["id"],
) => {
return SnapCache.linearElementAxisSnapTargets?.editingElementId ===
editingElementId
? SnapCache.linearElementAxisSnapTargets.snapTargets
: null;
};
public static setVisibleGaps = (
gaps: {
verticalGaps: Gap[];
@@ -184,7 +150,6 @@ export class SnapCache {
public static destroy = () => {
SnapCache.referenceSnapPoints = null;
SnapCache.linearElementAxisSnapTargets = null;
SnapCache.visibleGaps = null;
};
}
@@ -270,19 +235,6 @@ export const getElementsCorners = (
const halfHeight = (y2 - y1) / 2;
if (
(element.type === "line" || element.type === "arrow") &&
!boundingBoxCorners
) {
// For linear elements, use actual points instead of bounding box
const linearPoints = LinearElementEditor.getPointsGlobalCoordinates(
element as NonDeleted<ExcalidrawLinearElement>,
elementsMap,
{
dragOffset,
},
);
result = linearPoints;
} else if (
(element.type === "diamond" || element.type === "ellipse") &&
!boundingBoxCorners
) {
@@ -681,227 +633,6 @@ export const getReferenceSnapPoints = (
.flatMap((elementGroup) => getElementsCorners(elementGroup, elementsMap));
};
const getExternalAxisSnapTargets = (
elements: readonly NonDeletedExcalidrawElement[],
editingElement: ExcalidrawLinearElement,
appState: AppState,
elementsMap: ElementsMap,
) => {
const cachedAxisSnapTargets = SnapCache.getLinearElementAxisSnapTargets(
editingElement.id,
);
const externalAxisSnapTargets =
cachedAxisSnapTargets ??
getReferenceSnapPoints(elements, [editingElement], appState, elementsMap);
if (!cachedAxisSnapTargets) {
SnapCache.setLinearElementAxisSnapTargets(
editingElement.id,
externalAxisSnapTargets,
);
}
return externalAxisSnapTargets;
};
const getOwnAxisSnapTargets = (
editingElement: ExcalidrawLinearElement,
elementsMap: ElementsMap,
selectedPointsIndices?: readonly number[],
) => {
return LinearElementEditor.getPointsGlobalCoordinates(
editingElement as NonDeleted<ExcalidrawLinearElement>,
elementsMap,
{
excludePointsIndices: selectedPointsIndices,
},
);
};
export const getAxisSnapTargets = (
elements: readonly NonDeletedExcalidrawElement[],
editingElement: ExcalidrawLinearElement,
appState: AppState,
elementsMap: ElementsMap,
options: {
includeSelfPoints?: boolean;
selectedPointsIndices?: readonly number[];
} = {},
) => {
const externalAxisSnapTargets = getExternalAxisSnapTargets(
elements,
editingElement,
appState,
elementsMap,
);
if (!options.includeSelfPoints) {
return externalAxisSnapTargets;
}
return externalAxisSnapTargets.concat(
getOwnAxisSnapTargets(
editingElement,
elementsMap,
options.selectedPointsIndices,
),
);
};
const collectNearestAxisSnapCandidates = (
axisSnapTargets: readonly GlobalPoint[],
pointerPosition: GlobalPoint,
nearestSnapsX: Snaps,
nearestSnapsY: Snaps,
minOffset: Vector2D,
) => {
for (const snapTarget of axisSnapTargets) {
const offsetX = snapTarget[0] - pointerPosition[0];
const offsetY = snapTarget[1] - pointerPosition[1];
const absOffsetX = Math.abs(offsetX);
const absOffsetY = Math.abs(offsetY);
if (absOffsetX > minOffset.x && absOffsetY > minOffset.y) {
continue;
}
if (absOffsetX <= minOffset.x) {
if (absOffsetX < minOffset.x) {
nearestSnapsX.length = 0;
}
nearestSnapsX.push({
type: "point",
points: [pointerPosition, snapTarget],
offset: offsetX,
});
minOffset.x = absOffsetX;
}
if (absOffsetY <= minOffset.y) {
if (absOffsetY < minOffset.y) {
nearestSnapsY.length = 0;
}
nearestSnapsY.push({
type: "point",
points: [pointerPosition, snapTarget],
offset: offsetY,
});
minOffset.y = absOffsetY;
}
}
};
export const snapLinearElementPoint = (
elements: readonly NonDeletedExcalidrawElement[],
editingElement: ExcalidrawLinearElement,
pointerPosition: GlobalPoint,
app: AppClassProperties,
event: KeyboardModifiersObject,
elementsMap: ElementsMap,
options: {
includeExternalPoints?: boolean;
includeSelfPoints?: boolean;
selectedPointsIndices?: readonly number[];
} = {},
) => {
if (
!isSnappingEnabled({ app, event, selectedElements: [editingElement] }) ||
isElbowArrow(editingElement)
) {
return {
snapOffset: { x: 0, y: 0 },
snapLines: [],
};
}
const snapDistance = getSnapDistance(app.state.zoom.value);
const minOffset = {
x: snapDistance,
y: snapDistance,
};
const nearestSnapsX: Snaps = [];
const nearestSnapsY: Snaps = [];
if (options.includeExternalPoints !== false) {
collectNearestAxisSnapCandidates(
getExternalAxisSnapTargets(
elements,
editingElement,
app.state,
elementsMap,
),
pointerPosition,
nearestSnapsX,
nearestSnapsY,
minOffset,
);
}
if (options.includeSelfPoints) {
collectNearestAxisSnapCandidates(
getOwnAxisSnapTargets(
editingElement,
elementsMap,
options.selectedPointsIndices,
),
pointerPosition,
nearestSnapsX,
nearestSnapsY,
minOffset,
);
}
const snapOffset = {
x: nearestSnapsX[0]?.offset ?? 0,
y: nearestSnapsY[0]?.offset ?? 0,
};
// Create snap lines using the snapped position (fixed position)
let pointSnapLines: SnapLine[] = [];
if (snapOffset.x !== 0 || snapOffset.y !== 0) {
const snappedPosition = pointFrom<GlobalPoint>(
pointerPosition[0] + snapOffset.x,
pointerPosition[1] + snapOffset.y,
);
const snappedSnapsX = nearestSnapsX
.filter(
(snap): snap is PointSnap =>
snap.type === "point" && isCloseTo(snap.offset, snapOffset.x, 0.01),
)
.map((snap) => ({
type: "point" as const,
points: [snappedPosition, snap.points[1]] as [GlobalPoint, GlobalPoint],
offset: 0,
}));
const snappedSnapsY = nearestSnapsY
.filter(
(snap): snap is PointSnap =>
snap.type === "point" && isCloseTo(snap.offset, snapOffset.y, 0.01),
)
.map((snap) => ({
type: "point" as const,
points: [snappedPosition, snap.points[1]] as [GlobalPoint, GlobalPoint],
offset: 0,
}));
pointSnapLines = createPointSnapLines(snappedSnapsX, snappedSnapsY);
}
return {
snapOffset,
snapLines: pointSnapLines,
};
};
const getPointSnaps = (
selectedElements: ExcalidrawElement[],
selectionSnapPoints: GlobalPoint[],
@@ -1681,79 +1412,3 @@ export const isActiveToolNonLinearSnappable = (
activeToolType === TOOL_TYPE.text
);
};
/**
* Snaps to discrete angle rotation logic.
* This function handles the common pattern of finding intersections between
* angle lines and snap lines, and updating the snap lines accordingly.
*
* @param snapLines - The original snap lines from snapping
* @param angleLine - The line representing the discrete angle constraint
* @param gridPosition - The grid position (original pointer position)
* @param referencePosition - The reference position (usually the start point)
* @returns Object containing updated snap lines and position deltas
*/
export const snapToDiscreteAngle = (
snapLines: SnapLine[],
angleLine: [GlobalPoint, GlobalPoint],
gridPosition: GlobalPoint,
referencePosition: GlobalPoint,
): {
snapLines: SnapLine[];
dxFromReference: number;
dyFromReference: number;
} => {
if (snapLines.length === 0) {
return {
snapLines: [],
dxFromReference: gridPosition[0] - referencePosition[0],
dyFromReference: gridPosition[1] - referencePosition[1],
};
}
const firstSnapLine = snapLines[0];
if (firstSnapLine.type === "points" && firstSnapLine.points.length > 1) {
const snapLine = line(firstSnapLine.points[0], firstSnapLine.points[1]);
const intersection = linesIntersectAt<GlobalPoint>(
line(angleLine[0], angleLine[1]),
snapLine,
);
if (intersection) {
const dxFromReference = intersection[0] - referencePosition[0];
const dyFromReference = intersection[1] - referencePosition[1];
const furthestPoint = firstSnapLine.points.reduce(
(furthest, point) => {
const distance = pointDistance(intersection, point);
if (distance > furthest.distance) {
return { point, distance };
}
return furthest;
},
{
point: firstSnapLine.points[0],
distance: pointDistance(intersection, firstSnapLine.points[0]),
},
);
const updatedSnapLine: PointSnapLine = {
type: "points",
points: [furthestPoint.point, intersection],
};
return {
snapLines: [updatedSnapLine],
dxFromReference,
dyFromReference,
};
}
}
// If no intersection found, return original snap lines with grid position
return {
snapLines,
dxFromReference: gridPosition[0] - referencePosition[0],
dyFromReference: gridPosition[1] - referencePosition[1],
};
};
@@ -8665,14 +8665,7 @@ exports[`regression tests > key 5 selects arrow tool > [end of test] appState 1`
"openMenu": null,
"openPopup": null,
"openSidebar": null,
"originSnapOffset": {
"x": 0,
"y": 0,
},
"pasteDialog": {
"data": null,
"shown": false,
},
"originSnapOffset": null,
"penDetected": false,
"penMode": false,
"preferredSelectionTool": {
@@ -9329,14 +9322,7 @@ exports[`regression tests > key a selects arrow tool > [end of test] appState 1`
"openMenu": null,
"openPopup": null,
"openSidebar": null,
"originSnapOffset": {
"x": 0,
"y": 0,
},
"pasteDialog": {
"data": null,
"shown": false,
},
"originSnapOffset": null,
"penDetected": false,
"penMode": false,
"preferredSelectionTool": {
+19 -20
View File
@@ -449,29 +449,28 @@ const stripProps = (
}, {} as Record<string, any>);
export const checkpointHistory = (history: History, name: string) => {
expect(
history.undoStack.map((x) => ({
...x,
elements: {
...x.elements,
added: stripProps(x.elements.added, ["seed", "versionNonce"]),
removed: stripProps(x.elements.removed, ["seed", "versionNonce"]),
updated: stripProps(x.elements.updated, ["seed", "versionNonce"]),
},
})),
).toMatchSnapshot(`[${name}] undo stack`);
const normalizeHistoryEntry = (entry: History["undoStack"][number]) => {
const { markers, ...rest } = entry;
expect(
history.redoStack.map((x) => ({
...x,
return {
...rest,
...(markers ? { markers } : {}),
elements: {
...x.elements,
added: stripProps(x.elements.added, ["seed", "versionNonce"]),
removed: stripProps(x.elements.removed, ["seed", "versionNonce"]),
updated: stripProps(x.elements.updated, ["seed", "versionNonce"]),
...entry.elements,
added: stripProps(entry.elements.added, ["seed", "versionNonce"]),
removed: stripProps(entry.elements.removed, ["seed", "versionNonce"]),
updated: stripProps(entry.elements.updated, ["seed", "versionNonce"]),
},
})),
).toMatchSnapshot(`[${name}] redo stack`);
};
};
expect(history.undoStack.map(normalizeHistoryEntry)).toMatchSnapshot(
`[${name}] undo stack`,
);
expect(history.redoStack.map(normalizeHistoryEntry)).toMatchSnapshot(
`[${name}] redo stack`,
);
};
/**
File diff suppressed because it is too large Load Diff
+289
View File
@@ -0,0 +1,289 @@
import { type StoreDelta } from "@excalidraw/element";
import type { Delta } from "@excalidraw/element";
import type { Mutable } from "@excalidraw/common/utility-types";
import type {
ExcalidrawElement,
OrderedExcalidrawElement,
SceneElementsMap,
} from "@excalidraw/element/types";
import type {
ElementChange,
ElementPropName,
TouchedElementProps,
} from "./types";
const LEDGER_IGNORED_PROPS = new Set([
"version",
"versionNonce",
"seed",
"updated",
"index",
]);
export const TX_UNDO_OVERRIDE_IGNORED_PROPS = new Set([
"version",
"versionNonce",
"isDeleted",
]);
type ElementRecord = Record<string, unknown>;
export type ElementUpdatedProps = Omit<
Partial<OrderedExcalidrawElement>,
"id" | "updated" | "seed"
>;
export type ElementUpdatedPropName = Extract<keyof ElementUpdatedProps, string>;
type ElementPropValueMap = ElementUpdatedProps;
export type ElementUpdatedEntry = Delta<ElementPropValueMap>;
export type ElementUpdatedEntryMap = Record<string, ElementUpdatedEntry>;
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
!!value && typeof value === "object" && !Array.isArray(value);
export const getElementProp = <TProp extends ElementPropName>(
element: ExcalidrawElement,
prop: TProp,
): ExcalidrawElement[TProp] =>
(element as ElementRecord)[prop] as ExcalidrawElement[TProp];
export const setOrderedElementProp = <TProp extends ElementPropName>(
element: Mutable<OrderedExcalidrawElement>,
prop: TProp,
value: OrderedExcalidrawElement[TProp],
) => {
(element as ElementRecord)[prop] = value;
};
/** Deep equality used by ledger conflict/touched-prop detection. */
export const isLedgerValueEqual = (left: unknown, right: unknown): boolean => {
if (Object.is(left, right)) {
return true;
}
if (Array.isArray(left) && Array.isArray(right)) {
if (left.length !== right.length) {
return false;
}
for (let index = 0; index < left.length; index += 1) {
if (!isLedgerValueEqual(left[index], right[index])) {
return false;
}
}
return true;
}
if (isPlainObject(left) && isPlainObject(right)) {
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) {
return false;
}
for (const key of leftKeys) {
if (!Object.prototype.hasOwnProperty.call(right, key)) {
return false;
}
if (!isLedgerValueEqual(left[key], right[key])) {
return false;
}
}
return true;
}
return false;
};
/** Shallow-copies a scene map. Entries share references with the original. */
export const shallowCopySceneElements = (
elements: ReadonlyMap<string, ExcalidrawElement>,
): SceneElementsMap => new Map(elements) as SceneElementsMap;
export const createAllTouchedElementProps = (): TouchedElementProps => ({
kind: "all",
});
export const createPartialTouchedElementProps = (
props: Iterable<ElementPropName> = [],
): TouchedElementProps => ({
kind: "partial",
props: new Set(props),
});
export const hasTouchedProps = (touchedProps: TouchedElementProps): boolean =>
touchedProps.kind === "all" || touchedProps.props.size > 0;
export const touchesWholeElement = (
touchedProps: TouchedElementProps,
): boolean => touchedProps.kind === "all";
export const isPartialTouchedProps = (
touchedProps: TouchedElementProps,
): touchedProps is Extract<TouchedElementProps, { kind: "partial" }> =>
touchedProps.kind === "partial";
export const hasTouchedProp = (
touchedProps: TouchedElementProps,
prop: ElementPropName,
): boolean => touchedProps.kind === "all" || touchedProps.props.has(prop);
export const mergeTouchedProps = (
left: TouchedElementProps,
right: TouchedElementProps,
): TouchedElementProps => {
if (left.kind === "all" || right.kind === "all") {
return createAllTouchedElementProps();
}
return createPartialTouchedElementProps([...left.props, ...right.props]);
};
/** Returns changed property names between two element snapshots. */
export const collectTouchedProps = (
before: ExcalidrawElement | null,
after: ExcalidrawElement | null,
): TouchedElementProps => {
if (!before || !after) {
return createAllTouchedElementProps();
}
const touchedProps = new Set<ElementPropName>();
const keys = new Set<ElementPropName>([
...(Object.keys(before) as ElementPropName[]),
...(Object.keys(after) as ElementPropName[]),
]);
for (const key of keys) {
if (LEDGER_IGNORED_PROPS.has(key)) {
continue;
}
if (
!isLedgerValueEqual(
getElementProp(before, key),
getElementProp(after, key),
)
) {
touchedProps.add(key);
}
}
return createPartialTouchedElementProps(touchedProps);
};
/** Returns ids whose element snapshot changed between two points in time. */
export const collectChangedElementIds = (
before: ReadonlyMap<string, ExcalidrawElement>,
after: ReadonlyMap<string, ExcalidrawElement>,
) => collectElementChanges(before, after).map((change) => change.id);
export const collectElementChanges = (
before: ReadonlyMap<string, ExcalidrawElement>,
after: ReadonlyMap<string, ExcalidrawElement>,
): ElementChange[] => {
const changes: ElementChange[] = [];
const candidateIds = new Set<string>([...before.keys(), ...after.keys()]);
for (const id of candidateIds) {
const beforeElement = before.get(id) ?? null;
const afterElement = after.get(id) ?? null;
const touchedProps = collectTouchedProps(beforeElement, afterElement);
if (!hasTouchedProps(touchedProps)) {
continue;
}
changes.push({
id,
before: beforeElement,
after: afterElement,
touchedProps,
});
}
return changes;
};
export const serializeConsumedPropKey = (
elementId: string,
prop: ElementPropName,
) => `${elementId}\u0000${prop}`;
export const getUpdatedElementEntries = (delta: StoreDelta) =>
delta.elements.updated as ElementUpdatedEntryMap;
export const getElementPropEntries = (props: ElementPropValueMap) =>
Object.entries(props) as [
ElementUpdatedPropName,
ElementUpdatedProps[ElementUpdatedPropName],
][];
export const hasUpdatedElementEntries = (delta: StoreDelta) =>
Object.keys(getUpdatedElementEntries(delta)).length > 0;
export const serializeIntermediateValue = (value: unknown): string => {
const serialize = (input: unknown, seen: WeakSet<object>): string => {
if (input === null) {
return "null";
}
switch (typeof input) {
case "undefined":
return "undefined";
case "boolean":
return input ? "boolean:true" : "boolean:false";
case "number":
if (Number.isNaN(input)) {
return "number:NaN";
}
if (Object.is(input, -0)) {
return "number:-0";
}
return `number:${input}`;
case "bigint":
return `bigint:${input.toString()}`;
case "string":
return `string:${JSON.stringify(input)}`;
case "symbol":
return `symbol:${String(input)}`;
case "function":
return `function:${input.name}`;
case "object":
break;
default:
return `unknown:${String(input)}`;
}
if (Array.isArray(input)) {
if (seen.has(input)) {
return "[CircularArray]";
}
seen.add(input);
const serialized = `[${input
.map((item) => serialize(item, seen))
.join(",")}]`;
seen.delete(input);
return serialized;
}
if (isPlainObject(input)) {
if (seen.has(input)) {
return "{CircularObject}";
}
seen.add(input);
const serialized = `{${Object.keys(input)
.sort()
.map((key) => `${JSON.stringify(key)}:${serialize(input[key], seen)}`)
.join(",")}}`;
seen.delete(input);
return serialized;
}
try {
return `object:${JSON.stringify(input)}`;
} catch {
return `object:${Object.prototype.toString.call(input)}`;
}
};
return serialize(value, new WeakSet<object>());
};
+13
View File
@@ -0,0 +1,13 @@
export { collectChangedElementIds } from "./diff";
export { TransactionLedger } from "./ledger";
export { Transaction } from "./transaction";
export { TransactionManager } from "./manager";
export type {
AppStateResolver,
AppStateResolverContext,
TransactionElementUpdate,
TransactionLedgerEntry,
TransactionStatus,
TransactionSummary,
} from "./types";
+333
View File
@@ -0,0 +1,333 @@
import { deepCopyElement } from "@excalidraw/element";
import type { Mutable } from "@excalidraw/common/utility-types";
import type {
ExcalidrawElement,
OrderedExcalidrawElement,
SceneElementsMap,
} from "@excalidraw/element/types";
import {
collectElementChanges,
collectTouchedProps,
getElementProp,
hasTouchedProps,
isLedgerValueEqual,
mergeTouchedProps,
setOrderedElementProp,
shallowCopySceneElements,
touchesWholeElement,
} from "./diff";
import type { TransactionLedgerEntry } from "./types";
/**
* Keeps transaction-level scene mutations and materializes synthetic snapshots
* for a single durable history commit.
*/
export class TransactionLedger {
private readonly entries = new Map<string, TransactionLedgerEntry>();
/** Whether the transaction has any net element mutations. */
hasEntries() {
return this.entries.size > 0;
}
/** Returns the ledger entry for an element, if any. */
getEntry(elementId: string): TransactionLedgerEntry | undefined {
return this.entries.get(elementId);
}
/** Releases all ledger entries. */
clear() {
this.entries.clear();
}
/** Records one element mutation step into the ledger. */
recordStep(
before: ReadonlyMap<string, ExcalidrawElement>,
after: ReadonlyMap<string, ExcalidrawElement>,
) {
for (const change of collectElementChanges(before, after)) {
const {
id: elementId,
before: beforeElement,
after: afterElement,
touchedProps,
} = change;
const existing = this.entries.get(elementId);
if (!existing) {
this.entries.set(elementId, {
baselineElement: beforeElement
? deepCopyElement(beforeElement)
: null,
targetElement: afterElement ? deepCopyElement(afterElement) : null,
touchedProps,
});
continue;
}
existing.targetElement = afterElement
? deepCopyElement(afterElement)
: null;
existing.touchedProps = mergeTouchedProps(
existing.touchedProps,
touchedProps,
);
// Created then deleted inside one transaction leaves no durable footprint.
if (!existing.baselineElement && !existing.targetElement) {
this.entries.delete(elementId);
continue;
}
if (!existing.baselineElement && existing.targetElement?.isDeleted) {
this.entries.delete(elementId);
}
}
}
/**
* Builds synthetic element before/after snapshots with a fixed
* "live-wins-per-prop" strategy.
*/
buildSyntheticSnapshots(live: ReadonlyMap<string, ExcalidrawElement>) {
// Shallow copy — untouched elements stay as live references.
// Only elements mutated in-place (prop-level updates) are deep-copied below.
const elementsBefore = shallowCopySceneElements(live);
const elementsAfter = shallowCopySceneElements(live);
for (const [elementId, entry] of this.entries) {
this.reconcileEntrySnapshots(
elementId,
entry,
live,
elementsBefore,
elementsAfter,
);
}
return { elementsBefore, elementsAfter };
}
private reconcileEntrySnapshots(
elementId: string,
entry: TransactionLedgerEntry,
live: ReadonlyMap<string, ExcalidrawElement>,
elementsBefore: SceneElementsMap,
elementsAfter: SceneElementsMap,
) {
if (!entry.baselineElement) {
this.applyCreatedElementSnapshots(
elementId,
entry.targetElement,
live,
elementsBefore,
elementsAfter,
);
return;
}
if (!entry.targetElement) {
this.applyDeletedElementSnapshots(
elementId,
entry.baselineElement,
live,
elementsBefore,
elementsAfter,
);
return;
}
this.applyUpdatedElementSnapshots(
elementId,
entry,
live,
elementsBefore,
elementsAfter,
);
}
private applyCreatedElementSnapshots(
elementId: string,
targetElement: ExcalidrawElement | null,
live: ReadonlyMap<string, ExcalidrawElement>,
elementsBefore: SceneElementsMap,
elementsAfter: SceneElementsMap,
) {
if (!targetElement) {
return;
}
const liveElement = live.get(elementId) ?? null;
if (
!liveElement ||
liveElement.isDeleted ||
hasTouchedProps(collectTouchedProps(targetElement, liveElement))
) {
return;
}
elementsBefore.delete(elementId);
elementsAfter.set(
elementId,
deepCopyElement(targetElement) as OrderedExcalidrawElement,
);
}
private applyDeletedElementSnapshots(
elementId: string,
baselineElement: ExcalidrawElement,
live: ReadonlyMap<string, ExcalidrawElement>,
elementsBefore: SceneElementsMap,
elementsAfter: SceneElementsMap,
) {
const liveElement = live.get(elementId) ?? null;
if (liveElement && !liveElement.isDeleted) {
return;
}
elementsBefore.set(
elementId,
deepCopyElement(baselineElement) as OrderedExcalidrawElement,
);
elementsAfter.delete(elementId);
}
private applyUpdatedElementSnapshots(
elementId: string,
entry: TransactionLedgerEntry,
live: ReadonlyMap<string, ExcalidrawElement>,
elementsBefore: SceneElementsMap,
elementsAfter: SceneElementsMap,
) {
const liveElement = live.get(elementId) ?? null;
const targetElement = entry.targetElement;
const baselineElement = entry.baselineElement;
const beforeElement = elementsBefore.get(elementId);
const afterElement = elementsAfter.get(elementId);
if (
!liveElement ||
!baselineElement ||
!targetElement ||
!beforeElement ||
!afterElement
) {
return;
}
if (touchesWholeElement(entry.touchedProps)) {
this.applyWholeElementSnapshots(
elementId,
baselineElement,
targetElement,
liveElement,
elementsBefore,
elementsAfter,
);
return;
}
this.applyPerPropSnapshots({
entry,
liveElement,
baselineElement,
targetElement,
beforeElement,
afterElement,
elementId,
elementsBefore,
elementsAfter,
});
}
private applyWholeElementSnapshots(
elementId: string,
baselineElement: ExcalidrawElement,
targetElement: ExcalidrawElement,
liveElement: ExcalidrawElement,
elementsBefore: SceneElementsMap,
elementsAfter: SceneElementsMap,
) {
const hasLiveConflict = hasTouchedProps(
collectTouchedProps(targetElement, liveElement),
);
if (hasLiveConflict) {
return;
}
elementsBefore.set(
elementId,
deepCopyElement(baselineElement) as OrderedExcalidrawElement,
);
elementsAfter.set(
elementId,
deepCopyElement(targetElement) as OrderedExcalidrawElement,
);
}
private applyPerPropSnapshots(args: {
entry: TransactionLedgerEntry;
liveElement: ExcalidrawElement;
baselineElement: ExcalidrawElement;
targetElement: ExcalidrawElement;
beforeElement: ExcalidrawElement;
afterElement: ExcalidrawElement;
elementId: string;
elementsBefore: SceneElementsMap;
elementsAfter: SceneElementsMap;
}) {
const {
entry,
liveElement,
baselineElement,
targetElement,
beforeElement,
afterElement,
elementId,
elementsBefore,
elementsAfter,
} = args;
// Deep-copy before mutating so we never touch live elements.
const mutableBefore = deepCopyElement(
beforeElement,
) as Mutable<OrderedExcalidrawElement>;
const mutableAfter = deepCopyElement(
afterElement,
) as Mutable<OrderedExcalidrawElement>;
elementsBefore.set(elementId, mutableBefore as OrderedExcalidrawElement);
elementsAfter.set(elementId, mutableAfter as OrderedExcalidrawElement);
if (entry.touchedProps.kind !== "partial") {
return;
}
let appliedProps = 0;
for (const prop of entry.touchedProps.props) {
const liveValue = getElementProp(liveElement, prop);
const targetValue = getElementProp(targetElement, prop);
if (!isLedgerValueEqual(liveValue, targetValue)) {
continue;
}
setOrderedElementProp(
mutableBefore,
prop,
getElementProp(baselineElement, prop),
);
setOrderedElementProp(mutableAfter, prop, targetValue);
appliedProps += 1;
}
if (appliedProps === 0) {
return;
}
mutableBefore.version = baselineElement.version;
mutableBefore.versionNonce = baselineElement.versionNonce;
mutableAfter.version = targetElement.version;
mutableAfter.versionNonce = targetElement.versionNonce;
}
}
+291
View File
@@ -0,0 +1,291 @@
import {
Delta,
ElementsDelta,
mergeStoreDeltaMarkers,
type StoreDelta,
type TxUndoOverride,
} from "@excalidraw/element";
import type { Mutable } from "@excalidraw/common/utility-types";
import {
HistoryDelta,
type HistoryBeforeRecordListener,
type HistoryEffectiveDeltaResolverContext,
} from "../history";
import {
type ElementUpdatedPropName,
getUpdatedElementEntries,
hasUpdatedElementEntries,
isLedgerValueEqual,
type ElementUpdatedProps,
type ElementUpdatedEntryMap,
} from "./diff";
import { Transaction } from "./transaction";
import type { AppClassProperties } from "../types";
import type { TransactionStatus } from "./types";
type TransactionRecord = {
tx: Transaction | null;
phase: TransactionStatus;
};
type TransactionHistoryBridge = {
onBeforeRecord: (callback: HistoryBeforeRecordListener) => () => void;
setEffectiveDeltaResolver: (
resolver:
| ((
delta: HistoryDelta,
context: HistoryEffectiveDeltaResolverContext,
) => HistoryDelta)
| null,
) => void;
};
type MutableElementUpdatedProps = Mutable<ElementUpdatedProps>;
const setElementUpdatedOverride = (
overrides: MutableElementUpdatedProps,
prop: ElementUpdatedPropName,
value: unknown,
) => {
(overrides as Record<ElementUpdatedPropName, unknown>)[prop] = value;
};
/**
* Thin factory that holds the app reference and creates Transaction instances.
*/
export class TransactionManager {
private readonly app: AppClassProperties;
/**
* Single authoritative lifecycle registry for transactions.
*
* We retain ended/canceled metadata after the tx object is released because
* history markers only persist `txId`; undo/redo still needs to resolve
* whether a tx was active or already ended when applying effective deltas.
*/
private readonly transactionRecords = new Map<string, TransactionRecord>();
/**
* Active transaction ids ordered by most-recent registration first.
* This preserves deterministic priority when multiple active txs overlap on
* the same element+prop and compete to reserve override markers.
*/
private readonly activeTransactionIdsByPriority: string[] = [];
private detachBeforeRecordHook: (() => void) | null = null;
constructor(app: AppClassProperties) {
this.app = app;
}
/**
* Binds transaction bookkeeping to history lifecycle hooks.
* Call once during app initialization.
*/
attachHistory(history: TransactionHistoryBridge) {
this.detachBeforeRecordHook?.();
history.setEffectiveDeltaResolver((delta, context) =>
this.resolveEffectiveDelta(delta, context),
);
this.detachBeforeRecordHook = history.onBeforeRecord((delta) =>
this.onDurableIncrement(delta),
);
}
private removeActiveTransactionId(txId: string) {
const txIndex = this.activeTransactionIdsByPriority.indexOf(txId);
if (txIndex >= 0) {
this.activeTransactionIdsByPriority.splice(txIndex, 1);
}
}
private getRequiredTransactionRecord(txId: string): TransactionRecord {
const record = this.transactionRecords.get(txId);
if (!record) {
throw new Error(`Unknown transaction: ${txId}`);
}
return record;
}
registerTransaction(tx: Transaction) {
this.transactionRecords.set(tx.id, {
tx,
phase: "active",
});
this.activeTransactionIdsByPriority.unshift(tx.id);
}
detachTransactionInstance(txId: string) {
const record = this.getRequiredTransactionRecord(txId);
record.tx = null;
this.removeActiveTransactionId(txId);
}
getStatus(txId: string): TransactionStatus {
return this.getRequiredTransactionRecord(txId).phase;
}
private markTransactionFinished(
txId: string,
phase: Exclude<TransactionStatus, "active">,
): TransactionStatus {
const record = this.getRequiredTransactionRecord(txId);
if (record.phase !== "active") {
return record.phase;
}
record.phase = phase;
this.removeActiveTransactionId(txId);
return record.phase;
}
markTransactionCommitted(txId: string): TransactionStatus {
return this.markTransactionFinished(txId, "committed");
}
markTransactionCanceled(txId: string): TransactionStatus {
return this.markTransactionFinished(txId, "canceled");
}
onDurableIncrement(delta: StoreDelta) {
if (this.activeTransactionIdsByPriority.length === 0) {
return;
}
if (!hasUpdatedElementEntries(delta)) {
return;
}
const txUndoOverrides = this.collectUndoOverrides(delta);
if (txUndoOverrides.length === 0) {
return;
}
mergeStoreDeltaMarkers(delta, { txUndoOverrides });
}
private collectUndoOverrides(delta: StoreDelta): TxUndoOverride[] {
const overrides: TxUndoOverride[] = [];
const reservedConsumedKeys = new Set<string>();
for (const txId of this.activeTransactionIdsByPriority) {
const record = this.transactionRecords.get(txId);
if (!record || record.phase !== "active" || !record.tx) {
continue;
}
const txOverrides = record.tx.collectUndoOverridesForDelta(
delta,
reservedConsumedKeys,
);
for (const override of txOverrides) {
if (reservedConsumedKeys.has(override.consumedKey)) {
continue;
}
reservedConsumedKeys.add(override.consumedKey);
overrides.push(override);
}
}
return overrides;
}
private resolveEffectiveDelta(
delta: HistoryDelta,
_context: HistoryEffectiveDeltaResolverContext,
): HistoryDelta {
const txUndoOverrides = delta.markers?.txUndoOverrides;
if (!txUndoOverrides || txUndoOverrides.length === 0) {
return delta;
}
const updatedEntries = getUpdatedElementEntries(delta);
const insertedOverridesByElement = new Map<
string,
MutableElementUpdatedProps
>();
for (const override of txUndoOverrides) {
if (!this.shouldApplyUndoOverride(override.txId)) {
continue;
}
const currentEntry = updatedEntries[override.elementId];
if (!currentEntry) {
continue;
}
const prop = override.prop as ElementUpdatedPropName;
const currentInsertedValue = currentEntry.inserted[prop];
if (
!isLedgerValueEqual(
currentInsertedValue,
override.expectedInsertedValue,
)
) {
// Guard against over-applying once the delta has already evolved.
continue;
}
const elementOverrides = insertedOverridesByElement.get(
override.elementId,
);
if (elementOverrides) {
setElementUpdatedOverride(
elementOverrides,
prop,
override.preTxBaselineValue,
);
} else {
const nextOverrides: MutableElementUpdatedProps = {};
setElementUpdatedOverride(
nextOverrides,
prop,
override.preTxBaselineValue,
);
insertedOverridesByElement.set(override.elementId, nextOverrides);
}
}
if (insertedOverridesByElement.size === 0) {
return delta;
}
const nextUpdatedEntries: ElementUpdatedEntryMap = {
...updatedEntries,
};
for (const [elementId, insertedOverrides] of insertedOverridesByElement) {
const currentEntry = updatedEntries[elementId];
if (!currentEntry) {
continue;
}
nextUpdatedEntries[elementId] = Delta.create(
{ ...currentEntry.deleted },
{ ...currentEntry.inserted, ...insertedOverrides },
);
}
const effectiveElements = ElementsDelta.create(
delta.elements.added,
delta.elements.removed,
nextUpdatedEntries,
);
return HistoryDelta.create(effectiveElements, delta.appState, {
id: delta.id,
markers: delta.markers,
}) as HistoryDelta;
}
private shouldApplyUndoOverride(txId: string): boolean {
const record = this.transactionRecords.get(txId);
return !!record && record.phase !== "active";
}
create(): Transaction {
return new Transaction(this.app, this);
}
}
@@ -0,0 +1,286 @@
import { randomId } from "@excalidraw/common";
import {
CaptureUpdateAction,
newElementWith,
type ElementUpdate,
type StoreDelta,
type TxUndoOverride,
} from "@excalidraw/element";
import { shallowCopySceneElements } from "./diff";
import { TransactionLedger } from "./ledger";
import {
type AppStateResolver,
type AppStateResolverContext,
type TransactionElementOfType,
type TransactionElementUpdate,
type TransactionStatus,
type TransactionSummary,
} from "./types";
import { TxUndoOverridePlanner } from "./undoOverridePlanner";
import type { TransactionManager } from "./manager";
import type {
AppClassProperties,
AppState,
ObservedAppState,
SceneData,
} from "../types";
type CommitOptions = {
resolveAppState?: AppStateResolver;
};
/**
* A transaction that records mutations via `updateScene(NEVER)` and commits
* a single synthetic durable history entry at the end.
*/
export class Transaction {
public readonly id = `tx-${randomId()}`;
private readonly app: AppClassProperties;
private readonly manager: TransactionManager;
private readonly ledger = new TransactionLedger();
private readonly undoOverridePlanner = new TxUndoOverridePlanner();
private readonly initialAppState: Partial<ObservedAppState>;
private accumulatedAppState: Record<string, unknown> = {};
private cachedSummary: TransactionSummary | null = null;
constructor(app: AppClassProperties, manager: TransactionManager) {
this.app = app;
this.manager = manager;
this.initialAppState = { ...app.store.snapshot.appState };
this.manager.registerTransaction(this);
}
get status(): TransactionStatus {
return this.manager.getStatus(this.id);
}
private assertActive(action: string): void {
const status = this.status;
if (status !== "active") {
throw new Error(
`Cannot ${action} — transaction ${this.id} is already ${status}.`,
);
}
}
private closeTransaction() {
this.manager.detachTransactionInstance(this.id);
this.undoOverridePlanner.clear();
}
public collectUndoOverridesForDelta(
delta: StoreDelta,
reservedConsumedKeys: Set<string>,
): TxUndoOverride[] {
if (this.status !== "active") {
return [];
}
const candidates =
this.undoOverridePlanner.collectCandidatesForDurableDelta(
delta,
(elementId) => this.ledger.getEntry(elementId),
reservedConsumedKeys,
);
if (candidates.length === 0) {
return [];
}
const overrides: TxUndoOverride[] = [];
for (const candidate of candidates) {
this.undoOverridePlanner.markConsumed(candidate.consumedKey);
overrides.push({
txId: this.id,
...candidate,
});
}
return overrides;
}
updateScene<K extends keyof AppState>(data: {
elements?: SceneData["elements"];
appState?: Pick<AppState, K> | null;
}): void {
this.assertActive("updateScene");
// Snapshot before (shallow copy — replaceAllElements mutates the map in-place)
const before = shallowCopySceneElements(
this.app.scene.getElementsMapIncludingDeleted(),
);
// Apply through the real updateScene with NEVER.
this.app.api.updateScene({
elements: data.elements,
appState: data.appState,
captureUpdate: CaptureUpdateAction.NEVER,
});
// Snapshot after
const after = this.app.scene.getElementsMapIncludingDeleted();
this.undoOverridePlanner.recordStep(before, after);
// Record element diff into ledger
this.ledger.recordStep(before, after);
// Accumulate appState intent
if (data.appState) {
this.accumulatedAppState = {
...this.accumulatedAppState,
...(data.appState as Record<string, unknown>),
};
}
}
/**
* Partial element updates convenience API.
*
* Example:
* tx.updateElements({
* elements: [
* { id: "a", type: "rectangle", updates: { strokeColor: "#f00" } },
* { id: "b", type: "rectangle", updates: { x: 10, y: 20 } },
* ],
* })
*/
updateElements<K extends keyof AppState>(data: {
elements: readonly TransactionElementUpdate[];
appState?: Pick<AppState, K> | null;
}): void {
const updatesById = new Map<string, TransactionElementUpdate>();
for (const update of data.elements) {
updatesById.set(update.id, update);
}
if (updatesById.size === 0) {
this.updateScene({ appState: data.appState });
return;
}
const nextElements = this.app.scene
.getElementsIncludingDeleted()
.map((element) => {
const update = updatesById.get(element.id);
if (!update) {
return element;
}
if (element.type !== update.type) {
throw new Error(
`Cannot apply tx.updateElements update for "${update.id}": expected "${update.type}", got "${element.type}".`,
);
}
type MatchingElement = TransactionElementOfType<typeof update.type>;
return newElementWith(
element as MatchingElement,
update.updates as ElementUpdate<MatchingElement>,
);
});
this.updateScene({
elements: nextElements,
appState: data.appState,
});
}
commit(options?: CommitOptions): TransactionSummary {
if (this.cachedSummary) {
return this.cachedSummary;
}
this.manager.markTransactionCommitted(this.id);
let historyCommitted = false;
try {
historyCommitted = this.hasPendingWork()
? this.commitHistoryEntry(options)
: false;
} finally {
this.closeTransaction();
}
const status = this.status;
this.cachedSummary = {
id: this.id,
status,
historyCommitted,
};
this.ledger.clear();
return this.cachedSummary;
}
private hasPendingWork() {
return this.ledger.hasEntries() || this.hasAccumulatedAppStateIntent();
}
private hasAccumulatedAppStateIntent() {
return Object.keys(this.accumulatedAppState).length > 0;
}
private commitHistoryEntry(options?: CommitOptions) {
const liveMap = this.app.scene.getElementsMapIncludingDeleted();
const { elementsBefore, elementsAfter } =
this.ledger.buildSyntheticSnapshots(liveMap);
const appStateDelta = this.resolveCommitAppStateDelta(options);
return this.app.store.commitSyntheticIncrement({
logicalBefore: { elements: elementsBefore },
logicalAfter: {
elements: elementsAfter,
appState: appStateDelta,
},
});
}
private resolveCommitAppStateDelta(
options?: CommitOptions,
): Partial<ObservedAppState> | undefined {
if (!this.hasAccumulatedAppStateIntent()) {
return undefined;
}
if (!options?.resolveAppState) {
return this.accumulatedAppState as Partial<ObservedAppState>;
}
const context: AppStateResolverContext = {
initial: this.initialAppState,
accumulated: this.accumulatedAppState as Partial<ObservedAppState>,
live: { ...this.app.store.snapshot.appState },
};
const resolved = options.resolveAppState(context);
if (!resolved || Object.keys(resolved).length === 0) {
return undefined;
}
return resolved;
}
cancel(): TransactionSummary {
if (this.cachedSummary) {
return this.cachedSummary;
}
if (this.status === "active") {
this.manager.markTransactionCanceled(this.id);
}
this.closeTransaction();
const status = this.status;
this.cachedSummary = {
id: this.id,
status,
historyCommitted: false,
};
this.ledger.clear();
return this.cachedSummary;
}
}
+83
View File
@@ -0,0 +1,83 @@
import type { ElementUpdate } from "@excalidraw/element";
import type {
ExcalidrawElement,
ExcalidrawNonSelectionElement,
} from "@excalidraw/element/types";
import type { ObservedAppState } from "../types";
export type ElementPropName = Extract<keyof ExcalidrawElement, string>;
export type TouchedElementProps =
| { kind: "all" }
| { kind: "partial"; props: Set<ElementPropName> };
export type ElementChange = {
id: ExcalidrawElement["id"];
before: ExcalidrawElement | null;
after: ExcalidrawElement | null;
touchedProps: TouchedElementProps;
};
/** Per-element ledger record captured during a transaction session. */
export type TransactionLedgerEntry = {
baselineElement: ExcalidrawElement | null;
targetElement: ExcalidrawElement | null;
touchedProps: TouchedElementProps;
};
/** Lifecycle state of a transaction. */
export type TransactionStatus = "active" | "committed" | "canceled";
/** Per-element partial patch used by tx.updateElements(). */
export type TransactionUpdatableElementType =
ExcalidrawNonSelectionElement["type"];
export type TransactionElementOfType<
TType extends TransactionUpdatableElementType,
> = Extract<ExcalidrawNonSelectionElement, { type: TType }>;
export type TransactionElementUpdate<
TType extends TransactionUpdatableElementType = TransactionUpdatableElementType,
> = TType extends TransactionUpdatableElementType
? {
id: ExcalidrawElement["id"];
type: TType;
updates: ElementUpdate<TransactionElementOfType<TType>>;
}
: never;
/** Final summary returned when a transaction is committed or canceled. */
export type TransactionSummary = {
id: string;
status: TransactionStatus;
historyCommitted: boolean;
};
/** Three-way appState context provided to the resolver at commit time. */
export type AppStateResolverContext = {
/** AppState snapshot captured when the transaction was created. */
initial: Partial<ObservedAppState>;
/** Merged appState intent from all updateScene calls during the transaction. */
accumulated: Partial<ObservedAppState>;
/** Current live appState at commit time. */
live: Partial<ObservedAppState>;
};
/**
* Caller-provided resolver that determines which appState changes are
* recorded in the history entry.
*
* Unlike elements where per-property conflict detection works because
* element properties are largely independent appState keys are often
* interdependent (e.g. selectedElementIds selectedGroupIds must stay
* consistent). The correct merge strategy therefore depends on the
* caller's semantic context, not on a generic policy.
*
* Return the appState delta to record in history, or undefined to skip
* appState changes entirely.
*/
export type AppStateResolver = (
context: AppStateResolverContext,
) => Partial<ObservedAppState> | undefined;
@@ -0,0 +1,283 @@
import type { StoreDelta, TxUndoOverride } from "@excalidraw/element";
import type { ExcalidrawElement } from "@excalidraw/element/types";
import {
TX_UNDO_OVERRIDE_IGNORED_PROPS,
collectElementChanges,
getElementProp,
getElementPropEntries,
getUpdatedElementEntries,
hasTouchedProp,
isPartialTouchedProps,
isLedgerValueEqual,
serializeConsumedPropKey,
serializeIntermediateValue,
touchesWholeElement,
type ElementUpdatedEntry,
} from "./diff";
import type {
ElementPropName,
TouchedElementProps,
TransactionLedgerEntry,
} from "./types";
type TxUndoOverrideCandidate = Omit<TxUndoOverride, "txId">;
/**
* Per-element-prop history of tx intermediate values.
*
* We keep:
* - the full sequence for exact deep-equality fallback
* - a serialized signature set for fast negative lookups
* - the latest value for the most common positive lookup path
*/
class TxIntermediateValueHistory {
private readonly values: unknown[] = [];
private readonly signatures = new Set<string>();
private latestValue: unknown;
private hasLatestValue = false;
/** Appends a new intermediate value, skipping consecutive duplicates. */
add(value: unknown) {
if (this.hasLatestValue && isLedgerValueEqual(this.latestValue, value)) {
return;
}
this.values.push(value);
this.signatures.add(serializeIntermediateValue(value));
this.latestValue = value;
this.hasLatestValue = true;
}
/** Returns whether the candidate appeared in this tx prop history. */
contains(candidate: unknown) {
const candidateSignature = serializeIntermediateValue(candidate);
if (!this.signatures.has(candidateSignature)) {
return false;
}
if (
this.hasLatestValue &&
isLedgerValueEqual(this.latestValue, candidate)
) {
return true;
}
return this.values.some((value) => isLedgerValueEqual(value, candidate));
}
}
/**
* Tracks tx intermediate values and computes undo baseline override markers
* for durable user deltas recorded while tx is active.
*
* High-level flow:
* 1. `recordStep()` observes every in-tx scene mutation and records the
* intermediate value reached by each touched element prop.
* 2. When a durable user delta is about to be recorded,
* `collectCandidatesForDurableDelta()` checks whether that delta's
* deleted-baseline values match any tx intermediate value.
* 3. If they do, we emit override candidates so undo can restore the pre-tx
* baseline once the tx has ended.
* 4. `markConsumed()` ensures only the first polluted durable entry for a
* given element+prop gets patched; later user actions keep their own
* action-local undo baseline.
*/
export class TxUndoOverridePlanner {
private readonly intermediateValuesByElementProp = new Map<
string,
Map<ElementPropName, TxIntermediateValueHistory>
>();
private readonly consumedOverridePropKeys = new Set<string>();
/** Resets planner state when the transaction finishes. */
clear() {
this.consumedOverridePropKeys.clear();
this.intermediateValuesByElementProp.clear();
}
/** Records per-prop intermediate values reached by one in-tx scene step. */
recordStep(
before: ReadonlyMap<string, ExcalidrawElement>,
after: ReadonlyMap<string, ExcalidrawElement>,
) {
for (const change of collectElementChanges(before, after)) {
const { id: elementId, after: afterElement, touchedProps } = change;
if (!afterElement || !isPartialTouchedProps(touchedProps)) {
continue;
}
for (const prop of touchedProps.props) {
this.recordIntermediateValue(
elementId,
prop,
getElementProp(afterElement, prop),
);
}
}
}
/**
* Collects override candidates for one durable user delta recorded while the
* tx is active.
*/
collectCandidatesForDurableDelta(
delta: StoreDelta,
getLedgerEntry: (elementId: string) => TransactionLedgerEntry | undefined,
reservedConsumedKeys: Set<string>,
): TxUndoOverrideCandidate[] {
const candidates: TxUndoOverrideCandidate[] = [];
for (const [elementId, deltaEntry] of Object.entries(
getUpdatedElementEntries(delta),
)) {
const ledgerEntry = getLedgerEntry(elementId);
if (!ledgerEntry) {
continue;
}
const elementCandidates = this.collectCandidatesForElement(
elementId,
deltaEntry,
ledgerEntry,
reservedConsumedKeys,
);
if (elementCandidates.length > 0) {
candidates.push(...elementCandidates);
}
}
return candidates;
}
/** Evaluates one element's updated entry against the tx ledger snapshot. */
private collectCandidatesForElement(
elementId: string,
deltaEntry: ElementUpdatedEntry,
ledgerEntry: TransactionLedgerEntry,
reservedConsumedKeys: Set<string>,
): TxUndoOverrideCandidate[] {
const { baselineElement, touchedProps } = ledgerEntry;
if (!baselineElement || touchesWholeElement(touchedProps)) {
return [];
}
const candidates: TxUndoOverrideCandidate[] = [];
for (const [prop, deletedValue] of getElementPropEntries(
deltaEntry.deleted,
)) {
const candidate = this.createCandidateForProp({
elementId,
prop,
deletedValue,
baselineElement,
touchedProps,
reservedConsumedKeys,
});
if (candidate) {
candidates.push(candidate);
}
}
return candidates;
}
/**
* Returns an override candidate for one element+prop when the durable delta's
* deleted baseline was polluted by a tx intermediate value.
*/
private createCandidateForProp(args: {
elementId: string;
prop: ElementPropName;
deletedValue: unknown;
baselineElement: ExcalidrawElement;
touchedProps: TouchedElementProps;
reservedConsumedKeys: Set<string>;
}): TxUndoOverrideCandidate | null {
const { elementId, prop, deletedValue, baselineElement, touchedProps } =
args;
if (
TX_UNDO_OVERRIDE_IGNORED_PROPS.has(prop) ||
!hasTouchedProp(touchedProps, prop)
) {
return null;
}
const consumedPropKey = serializeConsumedPropKey(elementId, prop);
// Override only the first polluted user entry for this element+prop.
// Later user actions should keep action-local undo baselines.
if (
this.consumedOverridePropKeys.has(consumedPropKey) ||
args.reservedConsumedKeys.has(consumedPropKey)
) {
return null;
}
if (!this.matchesIntermediateValue(elementId, prop, deletedValue)) {
return null;
}
return {
elementId,
prop,
expectedInsertedValue: deletedValue,
preTxBaselineValue: getElementProp(baselineElement, prop),
consumedKey: consumedPropKey,
};
}
/** Marks an element+prop override as consumed by an earlier durable entry. */
markConsumed(consumedPropKey: string) {
this.consumedOverridePropKeys.add(consumedPropKey);
}
/** Returns the per-prop history map for one element, creating it if needed. */
private getOrCreatePropValues(elementId: string) {
const existing = this.intermediateValuesByElementProp.get(elementId);
if (existing) {
return existing;
}
const created = new Map<ElementPropName, TxIntermediateValueHistory>();
this.intermediateValuesByElementProp.set(elementId, created);
return created;
}
/** Appends one observed intermediate value for an element prop. */
private recordIntermediateValue(
elementId: string,
prop: ElementPropName,
value: unknown,
) {
const propValues = this.getOrCreatePropValues(elementId);
const history = propValues.get(prop);
if (history) {
history.add(value);
return;
}
const nextHistory = new TxIntermediateValueHistory();
nextHistory.add(value);
propValues.set(prop, nextHistory);
}
/** Checks whether a durable delta baseline matches any tx intermediate value. */
private matchesIntermediateValue(
elementId: string,
prop: ElementPropName,
candidate: unknown,
) {
const history = this.intermediateValuesByElementProp
.get(elementId)
?.get(prop);
if (!history) {
return false;
}
return history.contains(candidate);
}
}
+4 -2
View File
@@ -10,8 +10,6 @@ import type { LinearElementEditor } from "@excalidraw/element";
import type { MaybeTransformHandleType } from "@excalidraw/element";
import type { SnapLine } from "@excalidraw/element";
import type {
PointerType,
ExcalidrawLinearElement,
@@ -57,6 +55,7 @@ import type { ClipboardData } from "./clipboard";
import type App from "./components/App";
import type Library from "./data/library";
import type { ContextMenuItems } from "./components/ContextMenu";
import type { SnapLine } from "./snapping";
import type { ImportedDataState } from "./data/types";
import type { Language } from "./i18n";
@@ -797,6 +796,9 @@ export type AppClassProperties = {
files: BinaryFiles;
editorInterface: App["editorInterface"];
scene: App["scene"];
store: App["store"];
transactionManager: App["transactionManager"];
createTransaction: App["createTransaction"];
syncActionResult: App["syncActionResult"];
fonts: App["fonts"];
pasteFromClipboard: App["pasteFromClipboard"];
+2
View File
@@ -1,3 +1,5 @@
export const PRECISION = 10e-5;
// Legendre-Gauss abscissae (x values) and weights for n=24
// Refeerence: https://pomax.github.io/bezierinfo/legendre-gauss.html
export const LegendreGaussN24TValues = [