Compare commits

..

3 Commits

Author SHA1 Message Date
Mark Tolmacs
8d359427d1 Trigger Rebuild 2025-09-22 17:07:22 +02:00
Mark Tolmacs
06251ef8ed fix: Actual segments not approximations 2025-09-22 17:05:07 +02:00
Mark Tolmacs
54ca52e063 fix: Arrow eraser precision & lasso arrow selection 2025-09-22 16:44:34 +02:00
9 changed files with 129 additions and 171 deletions

View File

@@ -530,10 +530,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
return null;
}
if (existingRoomLinkData) {
// when joining existing room, don't merge it with current scene data
this.excalidrawAPI.resetScene();
} else {
if (!existingRoomLinkData) {
const elements = this.excalidrawAPI.getSceneElements().map((element) => {
if (isImageElement(element) && element.status === "saved") {
return newElementWith(element, { status: "pending" });

View File

@@ -266,10 +266,7 @@ export const STRING_MIME_TYPES = {
json: "application/json",
// excalidraw data
excalidraw: "application/vnd.excalidraw+json",
// LEGACY: fully-qualified library JSON data
excalidrawlib: "application/vnd.excalidrawlib+json",
// list of excalidraw library item ids
excalidrawlibIds: "application/vnd.excalidrawlib.ids+json",
} as const;
export const MIME_TYPES = {

View File

@@ -42,6 +42,7 @@ import {
isBoundToContainer,
isFreeDrawElement,
isLinearElement,
isLineElement,
isTextElement,
} from "./typeChecks";
@@ -321,19 +322,42 @@ export const getElementLineSegments = (
if (shape.type === "polycurve") {
const curves = shape.data;
const points = curves
.map((curve) => pointsOnBezierCurves(curve, 10))
.flat();
let i = 0;
const pointsOnCurves = curves.map((curve) =>
pointsOnBezierCurves(curve, 10),
);
const segments: LineSegment<GlobalPoint>[] = [];
while (i < points.length - 1) {
segments.push(
lineSegment(
pointFrom(points[i][0], points[i][1]),
pointFrom(points[i + 1][0], points[i + 1][1]),
),
);
i++;
if (
(isLineElement(element) && !element.polygon) ||
isArrowElement(element)
) {
for (const points of pointsOnCurves) {
let i = 0;
while (i < points.length - 1) {
segments.push(
lineSegment(
pointFrom(points[i][0], points[i][1]),
pointFrom(points[i + 1][0], points[i + 1][1]),
),
);
i++;
}
}
} else {
const points = pointsOnCurves.flat();
let i = 0;
while (i < points.length - 1) {
segments.push(
lineSegment(
pointFrom(points[i][0], points[i][1]),
pointFrom(points[i + 1][0], points[i + 1][1]),
),
);
i++;
}
}
return segments;

View File

@@ -433,8 +433,6 @@ import { findShapeByKey } from "./shapes";
import UnlockPopup from "./UnlockPopup";
import type { ExcalidrawLibraryIds } from "../data/types";
import type {
RenderInteractiveSceneCallback,
ScrollBars,
@@ -10547,44 +10545,16 @@ class App extends React.Component<AppProps, AppState> {
if (imageFiles.length > 0 && this.isToolSupported("image")) {
return this.insertImages(imageFiles, sceneX, sceneY);
}
const excalidrawLibrary_ids = dataTransferList.getData(
MIME_TYPES.excalidrawlibIds,
);
const excalidrawLibrary_data = dataTransferList.getData(
MIME_TYPES.excalidrawlib,
);
if (excalidrawLibrary_ids || excalidrawLibrary_data) {
try {
let libraryItems: LibraryItems | null = null;
if (excalidrawLibrary_ids) {
const { itemIds } = JSON.parse(
excalidrawLibrary_ids,
) as ExcalidrawLibraryIds;
const allLibraryItems = await this.library.getLatestLibrary();
libraryItems = allLibraryItems.filter((item) =>
itemIds.includes(item.id),
);
// legacy library dataTransfer format
} else if (excalidrawLibrary_data) {
libraryItems = parseLibraryJSON(excalidrawLibrary_data);
}
if (libraryItems?.length) {
libraryItems = libraryItems.map((item) => ({
...item,
// #6465
elements: duplicateElements({
type: "everything",
elements: item.elements,
randomizeSeed: true,
}).duplicatedElements,
}));
this.addElementsFromPasteOrLibrary({
elements: distributeLibraryItemsOnSquareGrid(libraryItems),
position: event,
files: null,
});
}
const libraryJSON = dataTransferList.getData(MIME_TYPES.excalidrawlib);
if (libraryJSON && typeof libraryJSON === "string") {
try {
const libraryItems = parseLibraryJSON(libraryJSON);
this.addElementsFromPasteOrLibrary({
elements: distributeLibraryItemsOnSquareGrid(libraryItems),
position: event,
files: null,
});
} catch (error: any) {
this.setState({ errorMessage: error.message });
}

View File

@@ -10,6 +10,7 @@ import { MIME_TYPES, arrayToMap } from "@excalidraw/common";
import { duplicateElements } from "@excalidraw/element";
import { serializeLibraryAsJSON } from "../data/json";
import { useLibraryCache } from "../hooks/useLibraryItemSvg";
import { useScrollPosition } from "../hooks/useScrollPosition";
import { t } from "../i18n";
@@ -26,8 +27,6 @@ import Stack from "./Stack";
import "./LibraryMenuItems.scss";
import type { ExcalidrawLibraryIds } from "../data/types";
import type {
ExcalidrawProps,
LibraryItem,
@@ -176,17 +175,12 @@ export default function LibraryMenuItems({
const onItemDrag = useCallback(
(id: LibraryItem["id"], event: React.DragEvent) => {
// we want to serialize just the ids so the operation is fast and there's
// no race condition if people drop the library items on canvas too fast
const data: ExcalidrawLibraryIds = {
itemIds: selectedItems.includes(id) ? selectedItems : [id],
};
event.dataTransfer.setData(
MIME_TYPES.excalidrawlibIds,
JSON.stringify(data),
MIME_TYPES.excalidrawlib,
serializeLibraryAsJSON(getInsertedElements(id)),
);
},
[selectedItems],
[getInsertedElements],
);
const isItemSelected = useCallback(

View File

@@ -192,7 +192,6 @@ const createLibraryUpdate = (
class Library {
/** latest libraryItems */
private currLibraryItems: LibraryItems = [];
/** snapshot of library items since last onLibraryChange call */
private prevLibraryItems = cloneLibraryItems(this.currLibraryItems);

View File

@@ -6,7 +6,6 @@ import type { cleanAppStateForExport } from "../appState";
import type {
AppState,
BinaryFiles,
LibraryItem,
LibraryItems,
LibraryItems_anyVersion,
} from "../types";
@@ -60,7 +59,3 @@ export interface ImportedLibraryData extends Partial<ExportedLibraryData> {
/** @deprecated v1 */
library?: LibraryItems;
}
export type ExcalidrawLibraryIds = {
itemIds: LibraryItem["id"][];
};

View File

@@ -2,10 +2,10 @@ import { arrayToMap, easeOut, THEME } from "@excalidraw/common";
import {
computeBoundTextPosition,
distanceToElement,
doBoundsIntersect,
getBoundTextElement,
getElementBounds,
getElementLineSegments,
getFreedrawOutlineAsSegments,
getFreedrawOutlinePoints,
intersectElementWithLineSegment,
@@ -265,19 +265,28 @@ const eraserTest = (
}
return false;
} else if (
isArrowElement(element) ||
(isLineElement(element) && !element.polygon)
) {
}
const boundTextElement = getBoundTextElement(element, elementsMap);
if (isArrowElement(element) || (isLineElement(element) && !element.polygon)) {
const tolerance = Math.max(
element.strokeWidth,
(element.strokeWidth * 2) / zoom,
);
return distanceToElement(element, elementsMap, lastPoint) <= tolerance;
}
// If the eraser movement is so fast that a large distance is covered
// between the last two points, the distanceToElement miss, so we test
// agaist each segment of the linear element
const segments = getElementLineSegments(element, elementsMap);
for (const seg of segments) {
if (lineSegmentsDistance(seg, pathSegment) <= tolerance) {
return true;
}
}
const boundTextElement = getBoundTextElement(element, elementsMap);
return false;
}
return (
intersectElementWithLineSegment(element, elementsMap, pathSegment, 0, true)

View File

@@ -15,7 +15,7 @@ import { Excalidraw } from "../index";
import { API } from "./helpers/api";
import { UI } from "./helpers/ui";
import { fireEvent, render, waitFor } from "./test-utils";
import { fireEvent, getCloneByOrigId, render, waitFor } from "./test-utils";
import type { LibraryItem, LibraryItems } from "../types";
@@ -46,8 +46,52 @@ vi.mock("../data/filesystem.ts", async (importOriginal) => {
};
});
describe("library items inserting", () => {
describe("library", () => {
beforeEach(async () => {
await render(<Excalidraw />);
await act(() => {
return h.app.library.resetLibrary();
});
});
it("import library via drag&drop", async () => {
expect(await h.app.library.getLatestLibrary()).toEqual([]);
await API.drop([
{
kind: "file",
type: MIME_TYPES.excalidrawlib,
file: await API.loadFile("./fixtures/fixture_library.excalidrawlib"),
},
]);
await waitFor(async () => {
expect(await h.app.library.getLatestLibrary()).toEqual([
{
status: "unpublished",
elements: [expect.objectContaining({ id: "A" })],
id: "id0",
created: expect.any(Number),
},
]);
});
});
// NOTE: mocked to test logic, not actual drag&drop via UI
it("drop library item onto canvas", async () => {
expect(h.elements).toEqual([]);
const libraryItems = parseLibraryJSON(await libraryJSONPromise);
await API.drop([
{
kind: "string",
value: serializeLibraryAsJSON(libraryItems),
type: MIME_TYPES.excalidrawlib,
},
]);
await waitFor(() => {
expect(h.elements).toEqual([expect.objectContaining({ [ORIG_ID]: "A" })]);
});
});
it("should regenerate ids but retain bindings on library insert", async () => {
const rectangle = API.createElement({
id: "rectangle1",
type: "rectangle",
@@ -73,116 +117,45 @@ describe("library items inserting", () => {
},
});
const libraryItems: LibraryItems = [
{
id: "libraryItem_id0",
status: "unpublished",
elements: [rectangle, text, arrow],
created: 0,
name: "test",
},
];
await render(<Excalidraw initialData={{ libraryItems }} />);
});
afterEach(async () => {
await act(() => {
return h.app.library.resetLibrary();
});
});
it("should regenerate ids but retain bindings on library insert", async () => {
const libraryItems = await h.app.library.getLatestLibrary();
expect(libraryItems.length).toBe(1);
await API.drop([
{
kind: "string",
value: JSON.stringify({
itemIds: [libraryItems[0].id],
}),
type: MIME_TYPES.excalidrawlibIds,
value: serializeLibraryAsJSON([
{
id: "item1",
status: "published",
elements: [rectangle, text, arrow],
created: 1,
},
]),
type: MIME_TYPES.excalidrawlib,
},
]);
await waitFor(() => {
const rectangle = h.elements.find((e) => e.type === "rectangle")!;
const text = h.elements.find((e) => e.type === "text")!;
const arrow = h.elements.find((e) => e.type === "arrow")!;
expect(h.elements).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "rectangle",
id: expect.not.stringMatching("rectangle1"),
[ORIG_ID]: "rectangle1",
boundElements: expect.arrayContaining([
{ type: "text", id: text.id },
{ type: "arrow", id: arrow.id },
{ type: "text", id: getCloneByOrigId("text1").id },
{ type: "arrow", id: getCloneByOrigId("arrow1").id },
]),
}),
expect.objectContaining({
type: "text",
id: expect.not.stringMatching("text1"),
containerId: rectangle.id,
[ORIG_ID]: "text1",
containerId: getCloneByOrigId("rectangle1").id,
}),
expect.objectContaining({
type: "arrow",
id: expect.not.stringMatching("arrow1"),
[ORIG_ID]: "arrow1",
endBinding: expect.objectContaining({
elementId: rectangle.id,
elementId: getCloneByOrigId("rectangle1").id,
}),
}),
]),
);
});
});
});
describe("library", () => {
beforeEach(async () => {
await render(<Excalidraw />);
await act(() => {
return h.app.library.resetLibrary();
});
});
it("import library via drag&drop", async () => {
expect(await h.app.library.getLatestLibrary()).toEqual([]);
await API.drop([
{
kind: "file",
type: MIME_TYPES.excalidrawlib,
file: await API.loadFile("./fixtures/fixture_library.excalidrawlib"),
},
]);
await waitFor(async () => {
expect(await h.app.library.getLatestLibrary()).toEqual([
{
status: "unpublished",
elements: [expect.objectContaining({ id: "A" })],
id: expect.any(String),
created: expect.any(Number),
},
]);
});
});
// NOTE: mocked to test logic, not actual drag&drop via UI
it("drop library item onto canvas", async () => {
expect(h.elements).toEqual([]);
const libraryItems = parseLibraryJSON(await libraryJSONPromise);
await API.drop([
{
kind: "string",
value: serializeLibraryAsJSON(libraryItems),
type: MIME_TYPES.excalidrawlib,
},
]);
await waitFor(() => {
expect(h.elements).toEqual([expect.objectContaining({ [ORIG_ID]: "A" })]);
});
});
it("should fix duplicate ids between items on insert", async () => {
// note, we're not testing for duplicate group ids and such because