Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
638c544bd1 | ||
|
|
79b5bab273 | ||
|
|
b2920f0baf | ||
|
|
4be8dd9879 | ||
|
|
801c936fd4 | ||
|
|
d4836f9e25 | ||
|
|
75192db663 | ||
|
|
ef9afb0d37 | ||
|
|
a5769f96cd | ||
|
|
2c6f513aed | ||
|
|
bfd4af2367 | ||
|
|
2177e1cfa0 | ||
|
|
5cd609cea7 | ||
|
|
226a6eef0a |
@@ -1,4 +1,4 @@
|
|||||||
FROM node:24-bullseye
|
FROM node:18-bullseye
|
||||||
|
|
||||||
# Vite wants to open the browser using `open`, so we
|
# Vite wants to open the browser using `open`, so we
|
||||||
# need to install those utils.
|
# need to install those utils.
|
||||||
|
|||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
FROM --platform=${BUILDPLATFORM} node:24 AS build
|
FROM --platform=${BUILDPLATFORM} node:18 AS build
|
||||||
|
|
||||||
WORKDIR /opt/node_app
|
WORKDIR /opt/node_app
|
||||||
|
|
||||||
@@ -13,7 +13,7 @@ ARG NODE_ENV=production
|
|||||||
|
|
||||||
RUN npm_config_target_arch=${TARGETARCH} yarn build:app:docker
|
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
|
COPY --from=build /opt/node_app/excalidraw-app/build /usr/share/nginx/html
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -1943,9 +1943,9 @@ export const calculateFixedPointForElbowArrowBinding = (
|
|||||||
return {
|
return {
|
||||||
fixedPoint: normalizeFixedPoint([
|
fixedPoint: normalizeFixedPoint([
|
||||||
(nonRotatedSnappedGlobalPoint[0] - hoveredElement.x) /
|
(nonRotatedSnappedGlobalPoint[0] - hoveredElement.x) /
|
||||||
Math.max(hoveredElement.width, PRECISION),
|
hoveredElement.width,
|
||||||
(nonRotatedSnappedGlobalPoint[1] - hoveredElement.y) /
|
(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
|
// Calculate the ratio relative to the element's bounds
|
||||||
const fixedPointX =
|
const fixedPointX =
|
||||||
(nonRotatedPoint[0] - hoveredElement.x) /
|
(nonRotatedPoint[0] - hoveredElement.x) / hoveredElement.width;
|
||||||
Math.max(hoveredElement.width, PRECISION);
|
|
||||||
const fixedPointY =
|
const fixedPointY =
|
||||||
(nonRotatedPoint[1] - hoveredElement.y) /
|
(nonRotatedPoint[1] - hoveredElement.y) / hoveredElement.height;
|
||||||
Math.max(hoveredElement.height, PRECISION);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
fixedPoint: normalizeFixedPoint([fixedPointX, fixedPointY]),
|
fixedPoint: normalizeFixedPoint([fixedPointX, fixedPointY]),
|
||||||
|
|||||||
@@ -2124,8 +2124,8 @@ const normalizeArrowElementUpdate = (
|
|||||||
offsetY < -MAX_POS ||
|
offsetY < -MAX_POS ||
|
||||||
offsetY > MAX_POS ||
|
offsetY > MAX_POS ||
|
||||||
offsetX + points[points.length - 1][0] < -MAX_POS ||
|
offsetX + points[points.length - 1][0] < -MAX_POS ||
|
||||||
offsetX + points[points.length - 1][0] > MAX_POS ||
|
offsetY + points[points.length - 1][0] > MAX_POS ||
|
||||||
offsetY + points[points.length - 1][1] < -MAX_POS ||
|
offsetX + points[points.length - 1][1] < -MAX_POS ||
|
||||||
offsetY + points[points.length - 1][1] > MAX_POS
|
offsetY + points[points.length - 1][1] > MAX_POS
|
||||||
) {
|
) {
|
||||||
console.error(
|
console.error(
|
||||||
|
|||||||
@@ -88,7 +88,6 @@ export * from "./selection";
|
|||||||
export * from "./shape";
|
export * from "./shape";
|
||||||
export * from "./showSelectedShapeActions";
|
export * from "./showSelectedShapeActions";
|
||||||
export * from "./sizeHelpers";
|
export * from "./sizeHelpers";
|
||||||
export * from "./snapping";
|
|
||||||
export * from "./sortElements";
|
export * from "./sortElements";
|
||||||
export * from "./store";
|
export * from "./store";
|
||||||
export * from "./textElement";
|
export * from "./textElement";
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
type LocalPoint,
|
type LocalPoint,
|
||||||
pointDistance,
|
pointDistance,
|
||||||
vectorFromPoint,
|
vectorFromPoint,
|
||||||
line,
|
|
||||||
curveLength,
|
curveLength,
|
||||||
curvePointAtLength,
|
curvePointAtLength,
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
@@ -30,9 +29,6 @@ import {
|
|||||||
isPathALoop,
|
isPathALoop,
|
||||||
moveArrowAboveBindable,
|
moveArrowAboveBindable,
|
||||||
projectFixedPointOntoDiagonal,
|
projectFixedPointOntoDiagonal,
|
||||||
snapLinearElementPoint,
|
|
||||||
snapToDiscreteAngle,
|
|
||||||
type SnapLine,
|
|
||||||
type Store,
|
type Store,
|
||||||
} from "@excalidraw/element";
|
} from "@excalidraw/element";
|
||||||
|
|
||||||
@@ -52,7 +48,6 @@ import {
|
|||||||
calculateFixedPointForNonElbowArrowBinding,
|
calculateFixedPointForNonElbowArrowBinding,
|
||||||
getBindingStrategyForDraggingBindingElementEndpoints,
|
getBindingStrategyForDraggingBindingElementEndpoints,
|
||||||
isBindingEnabled,
|
isBindingEnabled,
|
||||||
maxBindingDistance_simple,
|
|
||||||
snapToMid,
|
snapToMid,
|
||||||
updateBoundPoint,
|
updateBoundPoint,
|
||||||
} from "./binding";
|
} from "./binding";
|
||||||
@@ -61,7 +56,6 @@ import {
|
|||||||
getElementPointsCoords,
|
getElementPointsCoords,
|
||||||
getMinMaxXYFromCurvePathOps,
|
getMinMaxXYFromCurvePathOps,
|
||||||
} from "./bounds";
|
} from "./bounds";
|
||||||
import { getHoveredElementForBinding } from "./collision";
|
|
||||||
|
|
||||||
import { headingIsHorizontal, vectorToHeading } from "./heading";
|
import { headingIsHorizontal, vectorToHeading } from "./heading";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
@@ -300,10 +294,7 @@ export class LinearElementEditor {
|
|||||||
scenePointerX: number,
|
scenePointerX: number,
|
||||||
scenePointerY: number,
|
scenePointerY: number,
|
||||||
linearElementEditor: LinearElementEditor,
|
linearElementEditor: LinearElementEditor,
|
||||||
): Pick<
|
): Pick<AppState, "suggestedBinding" | "selectedLinearElement"> | null {
|
||||||
AppState,
|
|
||||||
"suggestedBinding" | "selectedLinearElement" | "snapLines"
|
|
||||||
> | null {
|
|
||||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||||
const elements = app.scene.getNonDeletedElements();
|
const elements = app.scene.getNonDeletedElements();
|
||||||
const { elementId } = linearElementEditor;
|
const { elementId } = linearElementEditor;
|
||||||
@@ -320,26 +311,36 @@ export class LinearElementEditor {
|
|||||||
linearElementEditor.customLineAngle ??
|
linearElementEditor.customLineAngle ??
|
||||||
determineCustomLinearAngle(pivotPoint, element.points[idx]);
|
determineCustomLinearAngle(pivotPoint, element.points[idx]);
|
||||||
|
|
||||||
const { point: newDraggingPointPosition, snapLines } =
|
// Determine if point movement should happen and how much
|
||||||
LinearElementEditor._getSnappedPointForLinearElement({
|
let deltaX = 0;
|
||||||
app,
|
let deltaY = 0;
|
||||||
event,
|
if (shouldRotateWithDiscreteAngle(event)) {
|
||||||
elements,
|
const [width, height] = LinearElementEditor._getShiftLockedDelta(
|
||||||
elementsMap,
|
|
||||||
element,
|
element,
|
||||||
pointIndex: idx,
|
elementsMap,
|
||||||
scenePointerX,
|
pivotPoint,
|
||||||
scenePointerY,
|
pointFrom(scenePointerX, scenePointerY),
|
||||||
pointerOffset: linearElementEditor.pointerOffset,
|
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
|
||||||
referencePoint: shouldRotateWithDiscreteAngle(event)
|
|
||||||
? pivotPoint
|
|
||||||
: null,
|
|
||||||
selectedPointsIndices: [idx],
|
|
||||||
customLineAngle,
|
customLineAngle,
|
||||||
});
|
);
|
||||||
|
const target = pointFrom<LocalPoint>(
|
||||||
|
width + pivotPoint[0],
|
||||||
|
height + pivotPoint[1],
|
||||||
|
);
|
||||||
|
|
||||||
const deltaX = newDraggingPointPosition[0] - point[0];
|
deltaX = target[0] - point[0];
|
||||||
const deltaY = newDraggingPointPosition[1] - point[1];
|
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
|
// Apply the point movement if needed
|
||||||
let suggestedBinding: AppState["suggestedBinding"] = null;
|
let suggestedBinding: AppState["suggestedBinding"] = null;
|
||||||
@@ -397,8 +398,6 @@ export class LinearElementEditor {
|
|||||||
// PERF: Avoid state updates if not absolutely necessary
|
// PERF: Avoid state updates if not absolutely necessary
|
||||||
if (
|
if (
|
||||||
app.state.selectedLinearElement?.customLineAngle === customLineAngle &&
|
app.state.selectedLinearElement?.customLineAngle === customLineAngle &&
|
||||||
app.state.snapLines.length === 0 &&
|
|
||||||
snapLines.length === 0 &&
|
|
||||||
linearElementEditor.initialState.altFocusPoint &&
|
linearElementEditor.initialState.altFocusPoint &&
|
||||||
(!suggestedBinding ||
|
(!suggestedBinding ||
|
||||||
isShallowEqual(app.state.suggestedBinding ?? [], suggestedBinding))
|
isShallowEqual(app.state.suggestedBinding ?? [], suggestedBinding))
|
||||||
@@ -437,7 +436,6 @@ export class LinearElementEditor {
|
|||||||
return {
|
return {
|
||||||
selectedLinearElement: newLinearElementEditor,
|
selectedLinearElement: newLinearElementEditor,
|
||||||
suggestedBinding,
|
suggestedBinding,
|
||||||
snapLines,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -447,10 +445,7 @@ export class LinearElementEditor {
|
|||||||
scenePointerX: number,
|
scenePointerX: number,
|
||||||
scenePointerY: number,
|
scenePointerY: number,
|
||||||
linearElementEditor: LinearElementEditor,
|
linearElementEditor: LinearElementEditor,
|
||||||
): Pick<
|
): Pick<AppState, "suggestedBinding" | "selectedLinearElement"> | null {
|
||||||
AppState,
|
|
||||||
"suggestedBinding" | "selectedLinearElement" | "snapLines"
|
|
||||||
> | null {
|
|
||||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||||
const elements = app.scene.getNonDeletedElements();
|
const elements = app.scene.getNonDeletedElements();
|
||||||
const { elbowed, elementId, initialState } = linearElementEditor;
|
const { elbowed, elementId, initialState } = linearElementEditor;
|
||||||
@@ -498,6 +493,7 @@ export class LinearElementEditor {
|
|||||||
lastClickedPoint = element.points.length - 1;
|
lastClickedPoint = element.points.length - 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// point that's being dragged (out of all selected points)
|
||||||
const draggingPoint = element.points[lastClickedPoint];
|
const draggingPoint = element.points[lastClickedPoint];
|
||||||
// The adjacent point to the one dragged point
|
// The adjacent point to the one dragged point
|
||||||
const pivotPoint =
|
const pivotPoint =
|
||||||
@@ -511,27 +507,35 @@ export class LinearElementEditor {
|
|||||||
element.points.length - 1,
|
element.points.length - 1,
|
||||||
);
|
);
|
||||||
|
|
||||||
const { point: newDraggingPointPosition, snapLines } =
|
// Determine if point movement should happen and how much
|
||||||
LinearElementEditor._getSnappedPointForLinearElement({
|
let deltaX = 0;
|
||||||
app,
|
let deltaY = 0;
|
||||||
event,
|
if (shouldRotateWithDiscreteAngle(event) && singlePointDragged) {
|
||||||
elements,
|
const [width, height] = LinearElementEditor._getShiftLockedDelta(
|
||||||
elementsMap,
|
|
||||||
element,
|
element,
|
||||||
pointIndex: lastClickedPoint,
|
elementsMap,
|
||||||
scenePointerX,
|
pivotPoint,
|
||||||
scenePointerY,
|
pointFrom(scenePointerX, scenePointerY),
|
||||||
pointerOffset: linearElementEditor.pointerOffset,
|
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
|
||||||
referencePoint:
|
|
||||||
shouldRotateWithDiscreteAngle(event) && singlePointDragged
|
|
||||||
? pivotPoint
|
|
||||||
: null,
|
|
||||||
selectedPointsIndices,
|
|
||||||
customLineAngle,
|
customLineAngle,
|
||||||
});
|
);
|
||||||
|
const target = pointFrom<LocalPoint>(
|
||||||
const deltaX = newDraggingPointPosition[0] - draggingPoint[0];
|
width + pivotPoint[0],
|
||||||
const deltaY = newDraggingPointPosition[1] - draggingPoint[1];
|
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
|
// Apply the point movement if needed
|
||||||
let suggestedBinding: AppState["suggestedBinding"] = null;
|
let suggestedBinding: AppState["suggestedBinding"] = null;
|
||||||
@@ -670,7 +674,6 @@ export class LinearElementEditor {
|
|||||||
return {
|
return {
|
||||||
selectedLinearElement: newLinearElementEditor,
|
selectedLinearElement: newLinearElementEditor,
|
||||||
suggestedBinding,
|
suggestedBinding,
|
||||||
snapLines,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1175,10 +1178,7 @@ export class LinearElementEditor {
|
|||||||
scenePointerX: number,
|
scenePointerX: number,
|
||||||
scenePointerY: number,
|
scenePointerY: number,
|
||||||
app: AppClassProperties,
|
app: AppClassProperties,
|
||||||
): {
|
): LinearElementEditor | null {
|
||||||
editingLinearElement: LinearElementEditor;
|
|
||||||
snapLines: readonly SnapLine[];
|
|
||||||
} | null {
|
|
||||||
const appState = app.state;
|
const appState = app.state;
|
||||||
if (!appState.selectedLinearElement?.isEditing) {
|
if (!appState.selectedLinearElement?.isEditing) {
|
||||||
return null;
|
return null;
|
||||||
@@ -1187,10 +1187,7 @@ export class LinearElementEditor {
|
|||||||
const elementsMap = app.scene.getNonDeletedElementsMap();
|
const elementsMap = app.scene.getNonDeletedElementsMap();
|
||||||
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
const element = LinearElementEditor.getElement(elementId, elementsMap);
|
||||||
if (!element) {
|
if (!element) {
|
||||||
return {
|
return appState.selectedLinearElement;
|
||||||
editingLinearElement: appState.selectedLinearElement,
|
|
||||||
snapLines: appState.snapLines,
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const { points } = element;
|
const { points } = element;
|
||||||
@@ -1202,37 +1199,36 @@ export class LinearElementEditor {
|
|||||||
}
|
}
|
||||||
return appState.selectedLinearElement?.lastUncommittedPoint
|
return appState.selectedLinearElement?.lastUncommittedPoint
|
||||||
? {
|
? {
|
||||||
editingLinearElement: {
|
...appState.selectedLinearElement,
|
||||||
...appState.selectedLinearElement,
|
lastUncommittedPoint: null,
|
||||||
lastUncommittedPoint: null,
|
|
||||||
},
|
|
||||||
snapLines: [],
|
|
||||||
}
|
}
|
||||||
: {
|
: appState.selectedLinearElement;
|
||||||
editingLinearElement: appState.selectedLinearElement,
|
|
||||||
snapLines: [],
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const anchor = points[points.length - 2];
|
let newPoint: LocalPoint;
|
||||||
const elements = app.scene.getNonDeletedElements();
|
|
||||||
const { point: newPoint, snapLines } =
|
if (shouldRotateWithDiscreteAngle(event) && points.length >= 2) {
|
||||||
LinearElementEditor._getSnappedPointForLinearElement({
|
const anchor = points[points.length - 2];
|
||||||
app,
|
const [width, height] = LinearElementEditor._getShiftLockedDelta(
|
||||||
event,
|
|
||||||
elements,
|
|
||||||
elementsMap,
|
|
||||||
element,
|
element,
|
||||||
pointIndex: points.length - 1,
|
elementsMap,
|
||||||
scenePointerX,
|
anchor,
|
||||||
scenePointerY,
|
pointFrom(scenePointerX, scenePointerY),
|
||||||
pointerOffset: appState.selectedLinearElement.pointerOffset,
|
event[KEYS.CTRL_OR_CMD] ? null : app.getEffectiveGridSize(),
|
||||||
referencePoint:
|
);
|
||||||
shouldRotateWithDiscreteAngle(event) && points.length >= 2
|
|
||||||
? anchor
|
newPoint = pointFrom(width + anchor[0], height + anchor[1]);
|
||||||
: null,
|
} else {
|
||||||
selectedPointsIndices: [points.length - 1],
|
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) {
|
if (lastPoint === lastUncommittedPoint) {
|
||||||
LinearElementEditor.movePoints(
|
LinearElementEditor.movePoints(
|
||||||
@@ -1240,7 +1236,7 @@ export class LinearElementEditor {
|
|||||||
app.scene,
|
app.scene,
|
||||||
new Map([
|
new Map([
|
||||||
[
|
[
|
||||||
points.length - 1,
|
element.points.length - 1,
|
||||||
{
|
{
|
||||||
point: newPoint,
|
point: newPoint,
|
||||||
},
|
},
|
||||||
@@ -1250,13 +1246,9 @@ export class LinearElementEditor {
|
|||||||
} else {
|
} else {
|
||||||
LinearElementEditor.addPoints(element, app.scene, [newPoint]);
|
LinearElementEditor.addPoints(element, app.scene, [newPoint]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
editingLinearElement: {
|
...appState.selectedLinearElement,
|
||||||
...appState.selectedLinearElement,
|
lastUncommittedPoint: element.points[element.points.length - 1],
|
||||||
lastUncommittedPoint: element.points[element.points.length - 1],
|
|
||||||
},
|
|
||||||
snapLines,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1282,53 +1274,18 @@ export class LinearElementEditor {
|
|||||||
static getPointsGlobalCoordinates(
|
static getPointsGlobalCoordinates(
|
||||||
element: NonDeleted<ExcalidrawLinearElement>,
|
element: NonDeleted<ExcalidrawLinearElement>,
|
||||||
elementsMap: ElementsMap,
|
elementsMap: ElementsMap,
|
||||||
options: {
|
|
||||||
dragOffset?: { x: number; y: number };
|
|
||||||
excludePointsIndices?: readonly number[];
|
|
||||||
} = {},
|
|
||||||
): GlobalPoint[] {
|
): GlobalPoint[] {
|
||||||
const { dragOffset, excludePointsIndices } = options;
|
|
||||||
|
|
||||||
if (!element.points || element.points.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
||||||
const cx = (x1 + x2) / 2;
|
const cx = (x1 + x2) / 2;
|
||||||
const cy = (y1 + y2) / 2;
|
const cy = (y1 + y2) / 2;
|
||||||
|
return element.points.map((p) => {
|
||||||
let elementX = element.x;
|
const { x, y } = element;
|
||||||
let elementY = element.y;
|
return pointRotateRads(
|
||||||
|
pointFrom(x + p[0], y + p[1]),
|
||||||
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),
|
|
||||||
pointFrom(cx, cy),
|
pointFrom(cx, cy),
|
||||||
element.angle,
|
element.angle,
|
||||||
);
|
);
|
||||||
globalPoints.push(rotated);
|
});
|
||||||
}
|
|
||||||
|
|
||||||
return globalPoints;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static getPointAtIndexGlobalCoordinates(
|
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 = (
|
static getBoundTextElementPosition = (
|
||||||
element: ExcalidrawLinearElement,
|
element: ExcalidrawLinearElement,
|
||||||
boundTextElement: ExcalidrawTextElementWithContainer,
|
boundTextElement: ExcalidrawTextElementWithContainer,
|
||||||
|
|||||||
@@ -111,6 +111,67 @@ export class Store {
|
|||||||
this.scheduleAction(CaptureUpdateAction.IMMEDIATELY);
|
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.
|
* 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 {
|
public clear(): void {
|
||||||
this.snapshot = StoreSnapshot.empty();
|
this.snapshot = StoreSnapshot.empty();
|
||||||
this.scheduledMacroActions = new Set();
|
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.
|
* 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.
|
* Represents a captured delta by the Store.
|
||||||
*/
|
*/
|
||||||
@@ -499,6 +662,7 @@ export class StoreDelta {
|
|||||||
public readonly id: string,
|
public readonly id: string,
|
||||||
public readonly elements: ElementsDelta,
|
public readonly elements: ElementsDelta,
|
||||||
public readonly appState: AppStateDelta,
|
public readonly appState: AppStateDelta,
|
||||||
|
public markers?: StoreDeltaMarkers,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -508,12 +672,16 @@ export class StoreDelta {
|
|||||||
elements: ElementsDelta,
|
elements: ElementsDelta,
|
||||||
appState: AppStateDelta,
|
appState: AppStateDelta,
|
||||||
opts: {
|
opts: {
|
||||||
id: string;
|
id?: string;
|
||||||
} = {
|
markers?: StoreDeltaMarkers;
|
||||||
id: randomId(),
|
} = {},
|
||||||
},
|
|
||||||
) {
|
) {
|
||||||
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.
|
* Restore a store delta instance from a DTO.
|
||||||
*/
|
*/
|
||||||
public static restore(storeDeltaDTO: DTO<StoreDelta>) {
|
public static restore(storeDeltaDTO: DTO<StoreDelta>) {
|
||||||
const { id, elements, appState } = storeDeltaDTO;
|
const { id, elements, appState, markers } = storeDeltaDTO;
|
||||||
return new this(
|
return new this(
|
||||||
id,
|
id,
|
||||||
ElementsDelta.restore(elements),
|
ElementsDelta.restore(elements),
|
||||||
AppStateDelta.restore(appState),
|
AppStateDelta.restore(appState),
|
||||||
|
cloneStoreDeltaMarkers(markers),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -553,11 +722,12 @@ export class StoreDelta {
|
|||||||
id,
|
id,
|
||||||
elements: { added, removed, updated },
|
elements: { added, removed, updated },
|
||||||
appState: { delta: appStateDelta },
|
appState: { delta: appStateDelta },
|
||||||
|
markers,
|
||||||
}: DTO<StoreDelta>) {
|
}: DTO<StoreDelta>) {
|
||||||
const elements = ElementsDelta.create(added, removed, updated);
|
const elements = ElementsDelta.create(added, removed, updated);
|
||||||
const appState = AppStateDelta.create(appStateDelta);
|
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) {
|
for (const delta of deltas) {
|
||||||
aggregatedDelta.elements.squash(delta.elements);
|
aggregatedDelta.elements.squash(delta.elements);
|
||||||
aggregatedDelta.appState.squash(delta.appState);
|
aggregatedDelta.appState.squash(delta.appState);
|
||||||
|
mergeStoreDeltaMarkers(aggregatedDelta, delta.markers ?? {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pruneStoreDeltaMarkers(aggregatedDelta);
|
||||||
return aggregatedDelta;
|
return aggregatedDelta;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -578,7 +750,12 @@ export class StoreDelta {
|
|||||||
* Inverse store delta, creates new instance of `StoreDelta`.
|
* Inverse store delta, creates new instance of `StoreDelta`.
|
||||||
*/
|
*/
|
||||||
public static inverse(delta: 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,
|
nextElements: SceneElementsMap,
|
||||||
modifierOptions?: "deleted" | "inserted",
|
modifierOptions?: "deleted" | "inserted",
|
||||||
): StoreDelta {
|
): StoreDelta {
|
||||||
return this.create(
|
const nextDelta = this.create(
|
||||||
delta.elements.applyLatestChanges(
|
delta.elements.applyLatestChanges(
|
||||||
prevElements,
|
prevElements,
|
||||||
nextElements,
|
nextElements,
|
||||||
@@ -623,8 +800,11 @@ export class StoreDelta {
|
|||||||
delta.appState,
|
delta.appState,
|
||||||
{
|
{
|
||||||
id: delta.id,
|
id: delta.id,
|
||||||
|
markers: delta.markers,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
pruneStoreDeltaMarkers(nextDelta);
|
||||||
|
return nextDelta;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static empty() {
|
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) => {
|
const deletePoint = (point: GlobalPoint) => {
|
||||||
fireEvent.pointerDown(interactiveCanvas, {
|
fireEvent.pointerDown(interactiveCanvas, {
|
||||||
clientX: point[0],
|
clientX: point[0],
|
||||||
@@ -276,73 +258,6 @@ describe("Test Linear Elements", () => {
|
|||||||
expect(h.state.selectedLinearElement?.elementId).toEqual(h.elements[0].id);
|
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)", () => {
|
it("should enter line editor via enter (line)", () => {
|
||||||
createTwoPointerLinearElement("line");
|
createTwoPointerLinearElement("line");
|
||||||
expect(h.state.selectedLinearElement?.isEditing).toBe(false);
|
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 () => {
|
it("should update the midpoints when element roundness changed", async () => {
|
||||||
createThreePointerLinearElement("line");
|
createThreePointerLinearElement("line");
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -239,16 +239,6 @@ import {
|
|||||||
hitElementBoundingBox,
|
hitElementBoundingBox,
|
||||||
isLineElement,
|
isLineElement,
|
||||||
isSimpleArrow,
|
isSimpleArrow,
|
||||||
isGridModeEnabled,
|
|
||||||
SnapCache,
|
|
||||||
isActiveToolNonLinearSnappable,
|
|
||||||
getSnapLinesAtPointer,
|
|
||||||
isSnappingEnabled,
|
|
||||||
getReferenceSnapPoints,
|
|
||||||
getVisibleGaps,
|
|
||||||
snapDraggedElements,
|
|
||||||
snapNewElement,
|
|
||||||
snapResizingElements,
|
|
||||||
StoreDelta,
|
StoreDelta,
|
||||||
type ApplyToOptions,
|
type ApplyToOptions,
|
||||||
positionElementsOnGrid,
|
positionElementsOnGrid,
|
||||||
@@ -371,6 +361,7 @@ import { restoreAppState, restoreElements } from "../data/restore";
|
|||||||
import { getCenter, getDistance } from "../gesture";
|
import { getCenter, getDistance } from "../gesture";
|
||||||
import { History } from "../history";
|
import { History } from "../history";
|
||||||
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
|
import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
|
||||||
|
import { TransactionManager } from "../transaction";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
calculateScrollCenter,
|
calculateScrollCenter,
|
||||||
@@ -406,6 +397,18 @@ import {
|
|||||||
import { Fonts } from "../fonts";
|
import { Fonts } from "../fonts";
|
||||||
import { editorJotaiStore, type WritableAtom } from "../editor-jotai";
|
import { editorJotaiStore, type WritableAtom } from "../editor-jotai";
|
||||||
import { ImageSceneDataError } from "../errors";
|
import { ImageSceneDataError } from "../errors";
|
||||||
|
import {
|
||||||
|
getSnapLinesAtPointer,
|
||||||
|
snapDraggedElements,
|
||||||
|
isActiveToolNonLinearSnappable,
|
||||||
|
snapNewElement,
|
||||||
|
snapResizingElements,
|
||||||
|
isSnappingEnabled,
|
||||||
|
getVisibleGaps,
|
||||||
|
getReferenceSnapPoints,
|
||||||
|
SnapCache,
|
||||||
|
isGridModeEnabled,
|
||||||
|
} from "../snapping";
|
||||||
import { Renderer } from "../scene/Renderer";
|
import { Renderer } from "../scene/Renderer";
|
||||||
import {
|
import {
|
||||||
setEraserCursor,
|
setEraserCursor,
|
||||||
@@ -635,7 +638,8 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
public library: AppClassProperties["library"];
|
public library: AppClassProperties["library"];
|
||||||
public libraryItemsFromStorage: LibraryItems | undefined;
|
public libraryItemsFromStorage: LibraryItems | undefined;
|
||||||
public id: string;
|
public id: string;
|
||||||
private store: Store;
|
public transactionManager: TransactionManager;
|
||||||
|
public store: Store;
|
||||||
private history: History;
|
private history: History;
|
||||||
public excalidrawContainerValue: {
|
public excalidrawContainerValue: {
|
||||||
container: HTMLDivElement | null;
|
container: HTMLDivElement | null;
|
||||||
@@ -783,29 +787,6 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
return api;
|
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) {
|
constructor(props: AppProps) {
|
||||||
super(props);
|
super(props);
|
||||||
const defaultAppState = getDefaultAppState();
|
const defaultAppState = getDefaultAppState();
|
||||||
@@ -853,6 +834,8 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
|
|
||||||
this.store = new Store(this);
|
this.store = new Store(this);
|
||||||
this.history = new History(this.store);
|
this.history = new History(this.store);
|
||||||
|
this.transactionManager = new TransactionManager(this);
|
||||||
|
this.transactionManager.attachHistory(this.history);
|
||||||
|
|
||||||
this.excalidrawContainerValue = {
|
this.excalidrawContainerValue = {
|
||||||
container: this.excalidrawContainerRef.current,
|
container: this.excalidrawContainerRef.current,
|
||||||
@@ -860,7 +843,6 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.fonts = new Fonts(this.scene);
|
this.fonts = new Fonts(this.scene);
|
||||||
this.history = new History(this.store);
|
|
||||||
|
|
||||||
this.actionManager.registerAll(actions);
|
this.actionManager.registerAll(actions);
|
||||||
this.actionManager.registerAction(createUndoAction(this.history));
|
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>>(
|
public mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
||||||
element: TElement,
|
element: TElement,
|
||||||
updates: ElementUpdate<TElement>,
|
updates: ElementUpdate<TElement>,
|
||||||
@@ -6807,10 +6794,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
!this.state.newElement &&
|
!this.state.newElement &&
|
||||||
(isActiveToolNonLinearSnappable(this.state.activeTool.type) ||
|
isActiveToolNonLinearSnappable(this.state.activeTool.type)
|
||||||
((this.state.activeTool.type === "line" ||
|
|
||||||
this.state.activeTool.type === "arrow") &&
|
|
||||||
this.state.currentItemArrowType !== ARROW_TYPE.elbow))
|
|
||||||
) {
|
) {
|
||||||
const { originOffset, snapLines } = getSnapLinesAtPointer(
|
const { originOffset, snapLines } = getSnapLinesAtPointer(
|
||||||
this.scene.getNonDeletedElements(),
|
this.scene.getNonDeletedElements(),
|
||||||
@@ -6859,7 +6843,7 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
this.state.selectedLinearElement?.isEditing &&
|
this.state.selectedLinearElement?.isEditing &&
|
||||||
!this.state.selectedLinearElement.isDragging
|
!this.state.selectedLinearElement.isDragging
|
||||||
) {
|
) {
|
||||||
const result = this.state.newElement
|
const editingLinearElement = this.state.newElement
|
||||||
? null
|
? null
|
||||||
: LinearElementEditor.handlePointerMoveInEditMode(
|
: LinearElementEditor.handlePointerMoveInEditMode(
|
||||||
event,
|
event,
|
||||||
@@ -6868,33 +6852,18 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
this,
|
this,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (result) {
|
if (
|
||||||
const { editingLinearElement, snapLines } = result;
|
editingLinearElement &&
|
||||||
const nextState = this.withStableSnapLines({
|
editingLinearElement !== this.state.selectedLinearElement
|
||||||
selectedLinearElement: editingLinearElement,
|
) {
|
||||||
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.
|
||||||
if (
|
flushSync(() => {
|
||||||
editingLinearElement &&
|
this.setState({
|
||||||
this.shouldUpdateSelectedLinearElementState(
|
selectedLinearElement: editingLinearElement,
|
||||||
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.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.x = pointerCoords.x;
|
||||||
pointerDownState.lastCoords.y = pointerCoords.y;
|
pointerDownState.lastCoords.y = pointerCoords.y;
|
||||||
pointerDownState.drag.hasOccurred = true;
|
pointerDownState.drag.hasOccurred = true;
|
||||||
const nextState = this.withStableSnapLines(newState);
|
|
||||||
|
|
||||||
// NOTE: Optimize setState calls because it
|
// NOTE: Optimize setState calls because it
|
||||||
// affects history and performance
|
// affects history and performance
|
||||||
if (
|
if (
|
||||||
nextState.suggestedBinding !== this.state.suggestedBinding ||
|
newState.suggestedBinding !== this.state.suggestedBinding ||
|
||||||
!isShallowEqual(
|
!isShallowEqual(
|
||||||
nextState.selectedLinearElement?.selectedPointsIndices ?? [],
|
newState.selectedLinearElement?.selectedPointsIndices ?? [],
|
||||||
this.state.selectedLinearElement?.selectedPointsIndices ?? [],
|
this.state.selectedLinearElement?.selectedPointsIndices ?? [],
|
||||||
) ||
|
) ||
|
||||||
nextState.selectedLinearElement?.hoverPointIndex !==
|
newState.selectedLinearElement?.hoverPointIndex !==
|
||||||
this.state.selectedLinearElement?.hoverPointIndex ||
|
this.state.selectedLinearElement?.hoverPointIndex ||
|
||||||
nextState.selectedLinearElement?.customLineAngle !==
|
newState.selectedLinearElement?.customLineAngle !==
|
||||||
this.state.selectedLinearElement?.customLineAngle ||
|
this.state.selectedLinearElement?.customLineAngle ||
|
||||||
this.state.selectedLinearElement.isDragging !==
|
this.state.selectedLinearElement.isDragging !==
|
||||||
nextState.selectedLinearElement?.isDragging ||
|
newState.selectedLinearElement?.isDragging ||
|
||||||
this.state.selectedLinearElement?.initialState?.altFocusPoint !==
|
this.state.selectedLinearElement?.initialState?.altFocusPoint !==
|
||||||
nextState.selectedLinearElement?.initialState?.altFocusPoint ||
|
newState.selectedLinearElement?.initialState?.altFocusPoint
|
||||||
nextState.snapLines !== this.state.snapLines
|
|
||||||
) {
|
) {
|
||||||
this.setState(nextState);
|
this.setState(newState);
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
@@ -10461,7 +10428,8 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
this.lassoTrail.endPath();
|
this.lassoTrail.endPath();
|
||||||
this.previousPointerMoveCoords = null;
|
this.previousPointerMoveCoords = null;
|
||||||
|
|
||||||
SnapCache.destroy();
|
SnapCache.setReferenceSnapPoints(null);
|
||||||
|
SnapCache.setVisibleGaps(null);
|
||||||
|
|
||||||
this.savePointer(childEvent.clientX, childEvent.clientY, "up");
|
this.savePointer(childEvent.clientX, childEvent.clientY, "up");
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ import { CANVAS_SEARCH_TAB, DEFAULT_SIDEBAR } from "@excalidraw/common";
|
|||||||
import {
|
import {
|
||||||
isFlowchartNodeElement,
|
isFlowchartNodeElement,
|
||||||
isImageElement,
|
isImageElement,
|
||||||
isGridModeEnabled,
|
|
||||||
isLinearElement,
|
isLinearElement,
|
||||||
isLineElement,
|
isLineElement,
|
||||||
isTextBindableContainer,
|
isTextBindableContainer,
|
||||||
@@ -17,6 +16,7 @@ import type { EditorInterface } from "@excalidraw/common";
|
|||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
import { getShortcutKey } from "../shortcut";
|
import { getShortcutKey } from "../shortcut";
|
||||||
import { isEraserActive } from "../appState";
|
import { isEraserActive } from "../appState";
|
||||||
|
import { isGridModeEnabled } from "../snapping";
|
||||||
|
|
||||||
import "./HintViewer.scss";
|
import "./HintViewer.scss";
|
||||||
|
|
||||||
|
|||||||
@@ -12,11 +12,10 @@ import { frameAndChildrenSelectedTogether } from "@excalidraw/element";
|
|||||||
|
|
||||||
import { elementsAreInSameGroup } from "@excalidraw/element";
|
import { elementsAreInSameGroup } from "@excalidraw/element";
|
||||||
|
|
||||||
import { isGridModeEnabled } from "@excalidraw/element";
|
|
||||||
|
|
||||||
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
|
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
|
||||||
|
|
||||||
import { t } from "../../i18n";
|
import { t } from "../../i18n";
|
||||||
|
import { isGridModeEnabled } from "../../snapping";
|
||||||
import { useExcalidrawAppState, useExcalidrawSetAppState } from "../App";
|
import { useExcalidrawAppState, useExcalidrawSetAppState } from "../App";
|
||||||
import { Island } from "../Island";
|
import { Island } from "../Island";
|
||||||
import { CloseIcon } from "../icons";
|
import { CloseIcon } from "../icons";
|
||||||
|
|||||||
@@ -96,8 +96,6 @@ type RestoredAppState = Omit<
|
|||||||
"offsetTop" | "offsetLeft" | "width" | "height"
|
"offsetTop" | "offsetLeft" | "width" | "height"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
const MAX_ARROW_PX = 75_000;
|
|
||||||
|
|
||||||
export const AllowedExcalidrawActiveTools: Record<
|
export const AllowedExcalidrawActiveTools: Record<
|
||||||
AppState["activeTool"]["type"],
|
AppState["activeTool"]["type"],
|
||||||
boolean
|
boolean
|
||||||
@@ -469,8 +467,8 @@ export const restoreElement = (
|
|||||||
element.endArrowhead === undefined
|
element.endArrowhead === undefined
|
||||||
? "arrow"
|
? "arrow"
|
||||||
: normalizeArrowhead(element.endArrowhead);
|
: normalizeArrowhead(element.endArrowhead);
|
||||||
const x = element.x as number | undefined;
|
const x: number | undefined = element.x;
|
||||||
const y = element.y as number | undefined;
|
const y: number | undefined = element.y;
|
||||||
const points: readonly LocalPoint[] | undefined = // migrate old arrow model to new one
|
const points: readonly LocalPoint[] | undefined = // migrate old arrow model to new one
|
||||||
!Array.isArray(element.points) || element.points.length < 2
|
!Array.isArray(element.points) || element.points.length < 2
|
||||||
? [pointFrom(0, 0), pointFrom(element.width, element.height)]
|
? [pointFrom(0, 0), pointFrom(element.width, element.height)]
|
||||||
@@ -495,8 +493,8 @@ export const restoreElement = (
|
|||||||
startArrowhead,
|
startArrowhead,
|
||||||
endArrowhead,
|
endArrowhead,
|
||||||
points,
|
points,
|
||||||
x: x ?? 0,
|
x,
|
||||||
y: y ?? 0,
|
y,
|
||||||
elbowed: (element as ExcalidrawArrowElement).elbowed,
|
elbowed: (element as ExcalidrawArrowElement).elbowed,
|
||||||
...getSizeFromPoints(points),
|
...getSizeFromPoints(points),
|
||||||
};
|
};
|
||||||
@@ -515,44 +513,12 @@ export const restoreElement = (
|
|||||||
})
|
})
|
||||||
: restoreElementWithProperties(element as ExcalidrawArrowElement, base);
|
: restoreElementWithProperties(element as ExcalidrawArrowElement, base);
|
||||||
|
|
||||||
const normalizedRestoredElement = {
|
return {
|
||||||
...restoredElement,
|
...restoredElement,
|
||||||
...LinearElementEditor.getNormalizeElementPointsAndCoords(
|
...LinearElementEditor.getNormalizeElementPointsAndCoords(
|
||||||
restoredElement,
|
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
|
// generic elements
|
||||||
@@ -700,7 +666,6 @@ export const restoreElements = <T extends ExcalidrawElement>(
|
|||||||
const existingElementsMap = existingElements
|
const existingElementsMap = existingElements
|
||||||
? arrayToMap(existingElements)
|
? arrayToMap(existingElements)
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
const restoredElements = syncInvalidIndices(
|
const restoredElements = syncInvalidIndices(
|
||||||
(targetElements || []).reduce((elements, element) => {
|
(targetElements || []).reduce((elements, element) => {
|
||||||
// filtering out selection, which is legacy, no longer kept in elements,
|
// 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
|
// Need to iterate again so we have attached text nodes in elementsMap
|
||||||
return restoredElements.map((element) => {
|
return restoredElements.map((element) => {
|
||||||
if (
|
if (
|
||||||
|
|||||||
@@ -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 {
|
export class History {
|
||||||
public readonly onHistoryChangedEmitter = new Emitter<
|
public readonly onHistoryChangedEmitter = new Emitter<
|
||||||
[HistoryChangedEvent]
|
[HistoryChangedEvent]
|
||||||
>();
|
>();
|
||||||
|
private readonly onBeforeRecordEmitter = new Emitter<[StoreDelta]>();
|
||||||
|
private effectiveDeltaResolver: HistoryEffectiveDeltaResolver | null = null;
|
||||||
|
|
||||||
public readonly undoStack: HistoryDelta[] = [];
|
public readonly undoStack: HistoryDelta[] = [];
|
||||||
public readonly redoStack: HistoryDelta[] = [];
|
public readonly redoStack: HistoryDelta[] = [];
|
||||||
@@ -105,6 +117,20 @@ export class History {
|
|||||||
|
|
||||||
constructor(private readonly store: Store) {}
|
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() {
|
public clear() {
|
||||||
this.undoStack.length = 0;
|
this.undoStack.length = 0;
|
||||||
this.redoStack.length = 0;
|
this.redoStack.length = 0;
|
||||||
@@ -119,6 +145,8 @@ export class History {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.onBeforeRecordEmitter.trigger(delta);
|
||||||
|
|
||||||
// construct history entry, so once it's emitted, it's not recorded again
|
// construct history entry, so once it's emitted, it's not recorded again
|
||||||
const historyDelta = HistoryDelta.inverse(delta);
|
const historyDelta = HistoryDelta.inverse(delta);
|
||||||
|
|
||||||
@@ -131,15 +159,14 @@ export class History {
|
|||||||
this.redoStack.length = 0;
|
this.redoStack.length = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.onHistoryChangedEmitter.trigger(
|
this.emitHistoryChanged();
|
||||||
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public undo(elements: SceneElementsMap, appState: AppState) {
|
public undo(elements: SceneElementsMap, appState: AppState) {
|
||||||
return this.perform(
|
return this.perform(
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState,
|
||||||
|
"undo",
|
||||||
() => History.pop(this.undoStack),
|
() => History.pop(this.undoStack),
|
||||||
(entry: HistoryDelta) => History.push(this.redoStack, entry),
|
(entry: HistoryDelta) => History.push(this.redoStack, entry),
|
||||||
);
|
);
|
||||||
@@ -149,6 +176,7 @@ export class History {
|
|||||||
return this.perform(
|
return this.perform(
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState,
|
||||||
|
"redo",
|
||||||
() => History.pop(this.redoStack),
|
() => History.pop(this.redoStack),
|
||||||
(entry: HistoryDelta) => History.push(this.undoStack, entry),
|
(entry: HistoryDelta) => History.push(this.undoStack, entry),
|
||||||
);
|
);
|
||||||
@@ -157,6 +185,7 @@ export class History {
|
|||||||
private perform(
|
private perform(
|
||||||
elements: SceneElementsMap,
|
elements: SceneElementsMap,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
|
direction: HistoryPerformDirection,
|
||||||
pop: () => HistoryDelta | null,
|
pop: () => HistoryDelta | null,
|
||||||
push: (entry: HistoryDelta) => void,
|
push: (entry: HistoryDelta) => void,
|
||||||
): [SceneElementsMap, AppState] | void {
|
): [SceneElementsMap, AppState] | void {
|
||||||
@@ -177,9 +206,15 @@ export class History {
|
|||||||
|
|
||||||
// iterate through the history entries in case they result in no visible changes
|
// iterate through the history entries in case they result in no visible changes
|
||||||
while (historyDelta) {
|
while (historyDelta) {
|
||||||
|
// Roundtrip invariant: whichever delta we execute must be the one that
|
||||||
|
// continues through applyLatestChanges -> inverse -> opposite stack.
|
||||||
|
let entryToPush = historyDelta;
|
||||||
try {
|
try {
|
||||||
|
const effectiveDelta = this.resolveEffectiveDelta(historyDelta, {
|
||||||
|
direction,
|
||||||
|
});
|
||||||
[nextElements, nextAppState, containsVisibleChange] =
|
[nextElements, nextAppState, containsVisibleChange] =
|
||||||
historyDelta.applyTo(nextElements, nextAppState, prevSnapshot);
|
effectiveDelta.applyTo(nextElements, nextAppState, prevSnapshot);
|
||||||
|
|
||||||
const prevElements = prevSnapshot.elements;
|
const prevElements = prevSnapshot.elements;
|
||||||
const nextSnapshot = prevSnapshot.maybeClone(
|
const nextSnapshot = prevSnapshot.maybeClone(
|
||||||
@@ -190,7 +225,7 @@ export class History {
|
|||||||
|
|
||||||
const change = StoreChange.create(prevSnapshot, nextSnapshot);
|
const change = StoreChange.create(prevSnapshot, nextSnapshot);
|
||||||
const delta = HistoryDelta.applyLatestChanges(
|
const delta = HistoryDelta.applyLatestChanges(
|
||||||
historyDelta,
|
effectiveDelta,
|
||||||
prevElements,
|
prevElements,
|
||||||
nextElements,
|
nextElements,
|
||||||
);
|
);
|
||||||
@@ -203,12 +238,12 @@ export class History {
|
|||||||
delta,
|
delta,
|
||||||
});
|
});
|
||||||
|
|
||||||
historyDelta = delta;
|
entryToPush = delta;
|
||||||
}
|
}
|
||||||
|
|
||||||
prevSnapshot = nextSnapshot;
|
prevSnapshot = nextSnapshot;
|
||||||
} finally {
|
} finally {
|
||||||
push(historyDelta);
|
push(entryToPush);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (containsVisibleChange) {
|
if (containsVisibleChange) {
|
||||||
@@ -222,12 +257,16 @@ export class History {
|
|||||||
} finally {
|
} finally {
|
||||||
// trigger the history change event before returning completely
|
// trigger the history change event before returning completely
|
||||||
// also trigger it just once, no need doing so on each entry
|
// also trigger it just once, no need doing so on each entry
|
||||||
this.onHistoryChangedEmitter.trigger(
|
this.emitHistoryChanged();
|
||||||
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private emitHistoryChanged() {
|
||||||
|
this.onHistoryChangedEmitter.trigger(
|
||||||
|
new HistoryChangedEvent(this.isUndoStackEmpty, this.isRedoStackEmpty),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private static pop(stack: HistoryDelta[]): HistoryDelta | null {
|
private static pop(stack: HistoryDelta[]): HistoryDelta | null {
|
||||||
if (!stack.length) {
|
if (!stack.length) {
|
||||||
return null;
|
return null;
|
||||||
@@ -246,4 +285,15 @@ export class History {
|
|||||||
const inversedEntry = HistoryDelta.inverse(entry);
|
const inversedEntry = HistoryDelta.inverse(entry);
|
||||||
return stack.push(inversedEntry);
|
return stack.push(inversedEntry);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private resolveEffectiveDelta(
|
||||||
|
delta: HistoryDelta,
|
||||||
|
context: HistoryEffectiveDeltaResolverContext,
|
||||||
|
): HistoryDelta {
|
||||||
|
if (!this.effectiveDeltaResolver) {
|
||||||
|
return delta;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.effectiveDeltaResolver(delta, context);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,13 +83,13 @@
|
|||||||
"@codemirror/language": "^6.0.0",
|
"@codemirror/language": "^6.0.0",
|
||||||
"@codemirror/state": "^6.0.0",
|
"@codemirror/state": "^6.0.0",
|
||||||
"@codemirror/view": "^6.0.0",
|
"@codemirror/view": "^6.0.0",
|
||||||
"@lezer/highlight": "^1.0.0",
|
|
||||||
"@excalidraw/common": "0.18.0",
|
"@excalidraw/common": "0.18.0",
|
||||||
"@excalidraw/element": "0.18.0",
|
"@excalidraw/element": "0.18.0",
|
||||||
"@excalidraw/laser-pointer": "1.3.1",
|
"@excalidraw/laser-pointer": "1.3.1",
|
||||||
"@excalidraw/math": "0.18.0",
|
"@excalidraw/math": "0.18.0",
|
||||||
"@excalidraw/mermaid-to-excalidraw": "2.2.2",
|
"@excalidraw/mermaid-to-excalidraw": "2.2.2",
|
||||||
"@excalidraw/random-username": "1.1.0",
|
"@excalidraw/random-username": "1.1.0",
|
||||||
|
"@lezer/highlight": "^1.0.0",
|
||||||
"browser-fs-access": "0.38.0",
|
"browser-fs-access": "0.38.0",
|
||||||
"canvas-roundrect-polyfill": "0.0.1",
|
"canvas-roundrect-polyfill": "0.0.1",
|
||||||
"clsx": "1.1.1",
|
"clsx": "1.1.1",
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ import { pointFrom, type GlobalPoint, type LocalPoint } from "@excalidraw/math";
|
|||||||
|
|
||||||
import { THEME } from "@excalidraw/common";
|
import { THEME } from "@excalidraw/common";
|
||||||
|
|
||||||
import type { PointSnapLine, PointerSnapLine } from "@excalidraw/element";
|
import type { PointSnapLine, PointerSnapLine } from "../snapping";
|
||||||
|
|
||||||
import type { InteractiveCanvasAppState } from "../types";
|
import type { InteractiveCanvasAppState } from "../types";
|
||||||
|
|
||||||
const SNAP_COLOR_LIGHT = "#ff6b6b";
|
const SNAP_COLOR_LIGHT = "#ff6b6b";
|
||||||
|
|||||||
@@ -1,8 +1,4 @@
|
|||||||
import {
|
import {
|
||||||
isCloseTo,
|
|
||||||
line,
|
|
||||||
linesIntersectAt,
|
|
||||||
pointDistance,
|
|
||||||
pointFrom,
|
pointFrom,
|
||||||
pointRotateRads,
|
pointRotateRads,
|
||||||
rangeInclusive,
|
rangeInclusive,
|
||||||
@@ -17,7 +13,7 @@ import {
|
|||||||
getDraggedElementsBounds,
|
getDraggedElementsBounds,
|
||||||
getElementAbsoluteCoords,
|
getElementAbsoluteCoords,
|
||||||
} from "@excalidraw/element";
|
} from "@excalidraw/element";
|
||||||
import { isBoundToContainer, isElbowArrow } from "@excalidraw/element";
|
import { isBoundToContainer } from "@excalidraw/element";
|
||||||
|
|
||||||
import { getMaximumGroups } from "@excalidraw/element";
|
import { getMaximumGroups } from "@excalidraw/element";
|
||||||
|
|
||||||
@@ -33,18 +29,14 @@ import type { MaybeTransformHandleType } from "@excalidraw/element";
|
|||||||
import type {
|
import type {
|
||||||
ElementsMap,
|
ElementsMap,
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
ExcalidrawLinearElement,
|
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
NonDeleted,
|
|
||||||
} from "@excalidraw/element/types";
|
} from "@excalidraw/element/types";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
AppClassProperties,
|
AppClassProperties,
|
||||||
AppState,
|
AppState,
|
||||||
KeyboardModifiersObject,
|
KeyboardModifiersObject,
|
||||||
} from "@excalidraw/excalidraw/types";
|
} from "./types";
|
||||||
|
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
|
||||||
|
|
||||||
const SNAP_DISTANCE = 8;
|
const SNAP_DISTANCE = 8;
|
||||||
|
|
||||||
@@ -130,11 +122,6 @@ export type SnapLine = PointSnapLine | GapSnapLine | PointerSnapLine;
|
|||||||
export class SnapCache {
|
export class SnapCache {
|
||||||
private static referenceSnapPoints: GlobalPoint[] | null = null;
|
private static referenceSnapPoints: GlobalPoint[] | null = null;
|
||||||
|
|
||||||
private static linearElementAxisSnapTargets: {
|
|
||||||
editingElementId: ExcalidrawElement["id"];
|
|
||||||
snapTargets: GlobalPoint[];
|
|
||||||
} | null = null;
|
|
||||||
|
|
||||||
private static visibleGaps: {
|
private static visibleGaps: {
|
||||||
verticalGaps: Gap[];
|
verticalGaps: Gap[];
|
||||||
horizontalGaps: Gap[];
|
horizontalGaps: Gap[];
|
||||||
@@ -148,27 +135,6 @@ export class SnapCache {
|
|||||||
return SnapCache.referenceSnapPoints;
|
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 = (
|
public static setVisibleGaps = (
|
||||||
gaps: {
|
gaps: {
|
||||||
verticalGaps: Gap[];
|
verticalGaps: Gap[];
|
||||||
@@ -184,7 +150,6 @@ export class SnapCache {
|
|||||||
|
|
||||||
public static destroy = () => {
|
public static destroy = () => {
|
||||||
SnapCache.referenceSnapPoints = null;
|
SnapCache.referenceSnapPoints = null;
|
||||||
SnapCache.linearElementAxisSnapTargets = null;
|
|
||||||
SnapCache.visibleGaps = null;
|
SnapCache.visibleGaps = null;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -270,19 +235,6 @@ export const getElementsCorners = (
|
|||||||
const halfHeight = (y2 - y1) / 2;
|
const halfHeight = (y2 - y1) / 2;
|
||||||
|
|
||||||
if (
|
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") &&
|
(element.type === "diamond" || element.type === "ellipse") &&
|
||||||
!boundingBoxCorners
|
!boundingBoxCorners
|
||||||
) {
|
) {
|
||||||
@@ -681,227 +633,6 @@ export const getReferenceSnapPoints = (
|
|||||||
.flatMap((elementGroup) => getElementsCorners(elementGroup, elementsMap));
|
.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 = (
|
const getPointSnaps = (
|
||||||
selectedElements: ExcalidrawElement[],
|
selectedElements: ExcalidrawElement[],
|
||||||
selectionSnapPoints: GlobalPoint[],
|
selectionSnapPoints: GlobalPoint[],
|
||||||
@@ -1681,79 +1412,3 @@ export const isActiveToolNonLinearSnappable = (
|
|||||||
activeToolType === TOOL_TYPE.text
|
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,
|
"openMenu": null,
|
||||||
"openPopup": null,
|
"openPopup": null,
|
||||||
"openSidebar": null,
|
"openSidebar": null,
|
||||||
"originSnapOffset": {
|
"originSnapOffset": null,
|
||||||
"x": 0,
|
|
||||||
"y": 0,
|
|
||||||
},
|
|
||||||
"pasteDialog": {
|
|
||||||
"data": null,
|
|
||||||
"shown": false,
|
|
||||||
},
|
|
||||||
"penDetected": false,
|
"penDetected": false,
|
||||||
"penMode": false,
|
"penMode": false,
|
||||||
"preferredSelectionTool": {
|
"preferredSelectionTool": {
|
||||||
@@ -9329,14 +9322,7 @@ exports[`regression tests > key a selects arrow tool > [end of test] appState 1`
|
|||||||
"openMenu": null,
|
"openMenu": null,
|
||||||
"openPopup": null,
|
"openPopup": null,
|
||||||
"openSidebar": null,
|
"openSidebar": null,
|
||||||
"originSnapOffset": {
|
"originSnapOffset": null,
|
||||||
"x": 0,
|
|
||||||
"y": 0,
|
|
||||||
},
|
|
||||||
"pasteDialog": {
|
|
||||||
"data": null,
|
|
||||||
"shown": false,
|
|
||||||
},
|
|
||||||
"penDetected": false,
|
"penDetected": false,
|
||||||
"penMode": false,
|
"penMode": false,
|
||||||
"preferredSelectionTool": {
|
"preferredSelectionTool": {
|
||||||
|
|||||||
@@ -449,29 +449,28 @@ const stripProps = (
|
|||||||
}, {} as Record<string, any>);
|
}, {} as Record<string, any>);
|
||||||
|
|
||||||
export const checkpointHistory = (history: History, name: string) => {
|
export const checkpointHistory = (history: History, name: string) => {
|
||||||
expect(
|
const normalizeHistoryEntry = (entry: History["undoStack"][number]) => {
|
||||||
history.undoStack.map((x) => ({
|
const { markers, ...rest } = entry;
|
||||||
...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`);
|
|
||||||
|
|
||||||
expect(
|
return {
|
||||||
history.redoStack.map((x) => ({
|
...rest,
|
||||||
...x,
|
...(markers ? { markers } : {}),
|
||||||
elements: {
|
elements: {
|
||||||
...x.elements,
|
...entry.elements,
|
||||||
added: stripProps(x.elements.added, ["seed", "versionNonce"]),
|
added: stripProps(entry.elements.added, ["seed", "versionNonce"]),
|
||||||
removed: stripProps(x.elements.removed, ["seed", "versionNonce"]),
|
removed: stripProps(entry.elements.removed, ["seed", "versionNonce"]),
|
||||||
updated: stripProps(x.elements.updated, ["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
@@ -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>());
|
||||||
|
};
|
||||||
@@ -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";
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,8 +10,6 @@ import type { LinearElementEditor } from "@excalidraw/element";
|
|||||||
|
|
||||||
import type { MaybeTransformHandleType } from "@excalidraw/element";
|
import type { MaybeTransformHandleType } from "@excalidraw/element";
|
||||||
|
|
||||||
import type { SnapLine } from "@excalidraw/element";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
PointerType,
|
PointerType,
|
||||||
ExcalidrawLinearElement,
|
ExcalidrawLinearElement,
|
||||||
@@ -57,6 +55,7 @@ import type { ClipboardData } from "./clipboard";
|
|||||||
import type App from "./components/App";
|
import type App from "./components/App";
|
||||||
import type Library from "./data/library";
|
import type Library from "./data/library";
|
||||||
import type { ContextMenuItems } from "./components/ContextMenu";
|
import type { ContextMenuItems } from "./components/ContextMenu";
|
||||||
|
import type { SnapLine } from "./snapping";
|
||||||
import type { ImportedDataState } from "./data/types";
|
import type { ImportedDataState } from "./data/types";
|
||||||
|
|
||||||
import type { Language } from "./i18n";
|
import type { Language } from "./i18n";
|
||||||
@@ -797,6 +796,9 @@ export type AppClassProperties = {
|
|||||||
files: BinaryFiles;
|
files: BinaryFiles;
|
||||||
editorInterface: App["editorInterface"];
|
editorInterface: App["editorInterface"];
|
||||||
scene: App["scene"];
|
scene: App["scene"];
|
||||||
|
store: App["store"];
|
||||||
|
transactionManager: App["transactionManager"];
|
||||||
|
createTransaction: App["createTransaction"];
|
||||||
syncActionResult: App["syncActionResult"];
|
syncActionResult: App["syncActionResult"];
|
||||||
fonts: App["fonts"];
|
fonts: App["fonts"];
|
||||||
pasteFromClipboard: App["pasteFromClipboard"];
|
pasteFromClipboard: App["pasteFromClipboard"];
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
export const PRECISION = 10e-5;
|
||||||
|
|
||||||
// Legendre-Gauss abscissae (x values) and weights for n=24
|
// Legendre-Gauss abscissae (x values) and weights for n=24
|
||||||
// Refeerence: https://pomax.github.io/bezierinfo/legendre-gauss.html
|
// Refeerence: https://pomax.github.io/bezierinfo/legendre-gauss.html
|
||||||
export const LegendreGaussN24TValues = [
|
export const LegendreGaussN24TValues = [
|
||||||
|
|||||||
Reference in New Issue
Block a user