excalidraw/src/scene/data.ts

349 lines
8.9 KiB
TypeScript
Raw Normal View History

import { ExcalidrawElement } from "../element/types";
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
import { getDefaultAppState, cleanAppStateForExport } from "../appState";
import { AppState } from "../types";
import { ExportType, PreviousScene } from "./types";
import { exportToCanvas, exportToSvg } from "./export";
import nanoid from "nanoid";
import { fileOpen, fileSave } from "browser-nativefs";
import { getCommonBounds } from "../element";
import i18n from "../i18n";
const LOCAL_STORAGE_KEY = "excalidraw";
const LOCAL_STORAGE_SCENE_PREVIOUS_KEY = "excalidraw-previos-scenes";
const LOCAL_STORAGE_KEY_STATE = "excalidraw-state";
const BACKEND_POST = "https://json.excalidraw.com/api/v1/post/";
const BACKEND_GET = "https://json.excalidraw.com/api/v1/";
// TODO: Defined globally, since file handles aren't yet serializable.
// Once `FileSystemFileHandle` can be serialized, make this
// part of `AppState`.
(window as any).handle = null;
interface DataState {
elements: readonly ExcalidrawElement[];
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
appState: AppState | null;
selectedId?: number;
}
export function serializeAsJSON(
elements: readonly ExcalidrawElement[],
appState: AppState,
): string {
return JSON.stringify(
{
type: "excalidraw",
version: 1,
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
source: window.location.origin,
elements: elements.map(({ shape, isSelected, ...el }) => el),
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
appState: cleanAppStateForExport(appState),
},
null,
2,
);
}
function calculateScrollCenter(
elements: readonly ExcalidrawElement[],
): { scrollX: number; scrollY: number } {
let [x1, y1, x2, y2] = getCommonBounds(elements);
const centerX = (x1 + x2) / 2;
const centerY = (y1 + y2) / 2;
return {
scrollX: window.innerWidth / 2 - centerX,
scrollY: window.innerHeight / 2 - centerY,
};
}
export async function saveAsJSON(
elements: readonly ExcalidrawElement[],
2020-01-24 12:04:54 +02:00
appState: AppState,
) {
const serialized = serializeAsJSON(elements, appState);
const name = `${appState.name}.json`;
await fileSave(
new Blob([serialized], { type: "application/json" }),
{
fileName: name,
2020-01-24 12:04:54 +02:00
description: "Excalidraw file",
},
2020-01-24 12:04:54 +02:00
(window as any).handle,
);
}
export async function loadFromJSON() {
const updateAppState = (contents: string) => {
const defaultAppState = getDefaultAppState();
let elements = [];
let appState = defaultAppState;
try {
const data = JSON.parse(contents);
elements = data.elements || [];
appState = { ...defaultAppState, ...data.appState };
} catch (e) {
// Do nothing because elements array is already empty
}
return { elements, appState };
};
const blob = await fileOpen({
description: "Excalidraw files",
extensions: ["json"],
2020-01-24 12:04:54 +02:00
mimeTypes: ["application/json"],
});
if (blob.handle) {
(window as any).handle = blob.handle;
}
let contents;
if ("text" in Blob) {
contents = await blob.text();
} else {
contents = await (async () => {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsText(blob, "utf8");
reader.onloadend = () => {
if (reader.readyState === FileReader.DONE) {
resolve(reader.result as string);
}
};
});
})();
}
const { elements, appState } = updateAppState(contents);
return new Promise<DataState>(resolve => {
resolve(
restore(elements, { ...appState, ...calculateScrollCenter(elements) }),
);
});
}
export async function exportToBackend(
elements: readonly ExcalidrawElement[],
2020-01-24 12:04:54 +02:00
appState: AppState,
) {
let response;
try {
response = await fetch(BACKEND_POST, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: serializeAsJSON(elements, appState),
});
const json = await response.json();
if (json.id) {
const url = new URL(window.location.href);
url.searchParams.append("id", json.id);
await navigator.clipboard.writeText(url.toString());
window.alert(
i18n.t("alerts.copiedToClipboard", {
url: url.toString(),
interpolation: { escapeValue: false },
}),
);
} else {
window.alert(i18n.t("alerts.couldNotCreateShareableLink"));
}
} catch (e) {
window.alert(i18n.t("alerts.couldNotCreateShareableLink"));
return;
}
}
export async function importFromBackend(id: string | null) {
let elements: readonly ExcalidrawElement[] = [];
let appState: AppState = getDefaultAppState();
const response = await fetch(`${BACKEND_GET}${id}.json`).then(data =>
2020-01-24 12:04:54 +02:00
data.clone().json(),
);
if (response != null) {
try {
elements = response.elements || elements;
appState = response.appState || appState;
} catch (error) {
window.alert(i18n.t("alerts.importBackendFailed"));
console.error(error);
}
}
return restore(elements, { ...appState, ...calculateScrollCenter(elements) });
}
export async function exportCanvas(
type: ExportType,
elements: readonly ExcalidrawElement[],
canvas: HTMLCanvasElement,
{
exportBackground,
exportPadding = 10,
viewBackgroundColor,
name,
2020-01-24 12:04:54 +02:00
scale = 1,
}: {
exportBackground: boolean;
exportPadding?: number;
viewBackgroundColor: string;
name: string;
scale?: number;
2020-01-24 12:04:54 +02:00
},
) {
if (!elements.length)
return window.alert(i18n.t("alerts.cannotExportEmptyCanvas"));
// calculate smallest area to fit the contents in
if (type === "svg") {
const tempSvg = exportToSvg(elements, {
exportBackground,
viewBackgroundColor,
exportPadding,
});
await fileSave(new Blob([tempSvg.outerHTML], { type: "image/svg+xml" }), {
fileName: `${name}.svg`,
});
return;
}
const tempCanvas = exportToCanvas(elements, {
exportBackground,
viewBackgroundColor,
exportPadding,
2020-01-24 12:04:54 +02:00
scale,
});
tempCanvas.style.display = "none";
document.body.appendChild(tempCanvas);
if (type === "png") {
const fileName = `${name}.png`;
tempCanvas.toBlob(async (blob: any) => {
if (blob) {
await fileSave(blob, {
fileName: fileName,
});
}
});
} else if (type === "clipboard") {
const errorMsg = i18n.t("alerts.couldNotCopyToClipboard");
try {
2020-01-19 13:21:33 -08:00
tempCanvas.toBlob(async function(blob: any) {
try {
await navigator.clipboard.write([
2020-01-24 12:04:54 +02:00
new window.ClipboardItem({ "image/png": blob }),
]);
} catch (err) {
window.alert(errorMsg);
}
});
} catch (err) {
window.alert(errorMsg);
}
} else if (type === "backend") {
const appState = getDefaultAppState();
if (exportBackground) {
appState.viewBackgroundColor = viewBackgroundColor;
}
exportToBackend(elements, appState);
}
// clean up the DOM
if (tempCanvas !== canvas) tempCanvas.remove();
}
function restore(
savedElements: readonly ExcalidrawElement[],
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
savedState: AppState | null,
): DataState {
return {
elements: savedElements.map(element => ({
...element,
id: element.id || nanoid(),
fillStyle: element.fillStyle || "hachure",
strokeWidth: element.strokeWidth || 1,
roughness: element.roughness || 1,
opacity:
element.opacity === null || element.opacity === undefined
? 100
2020-01-24 12:04:54 +02:00
: element.opacity,
})),
2020-01-24 12:04:54 +02:00
appState: savedState,
};
}
export function restoreFromLocalStorage() {
const savedElements = localStorage.getItem(LOCAL_STORAGE_KEY);
const savedState = localStorage.getItem(LOCAL_STORAGE_KEY_STATE);
let elements = [];
if (savedElements) {
try {
elements = JSON.parse(savedElements).map(
2020-01-24 12:04:54 +02:00
({ shape, ...element }: ExcalidrawElement) => element,
);
} catch (e) {
// Do nothing because elements array is already empty
}
}
let appState = null;
if (savedState) {
try {
Feature: Multi Point Arrows (#338) * Add points to arrow on double click * Use line generator instead of path to generate line segments * Switch color of the circle when it is on an existing point in the segment * Check point against both ends of the line segment to find collinearity * Keep drawing the arrow based on mouse position until shape is changed * Always select the arrow when in multi element mode * Use curves instead of lines when drawing arrow points * Add basic collision detection with some debug points * Use roughjs shape when performing hit testing * Draw proper handler rectangles for arrows * Add argument to renderScene in export * Globally resize all points on the arrow when bounds are resized * Hide handler rectangles if an arrow has no size - Allow continuing adding arrows when selected element is deleted * Add dragging functionality to arrows * Add SHIFT functionality to two point arrows - Fix arrow positions when scrolling - Revert the element back to selection when not in multi select mode * Clean app state for export (JSON) * Set curve options manually instead of using global options - For some reason, this fixed the flickering issue in all shapes when arrows are rendered * Set proper options for the arrow * Increaase accuracy of hit testing arrows - Additionally, skip testing if point is outside the domain of arrow and each curve * Calculate bounding box of arrow based on roughjs curves - Remove domain check per curve * Change bounding box threshold to 10 and remove unnecessary code * Fix handler rectangles for 2 and multi point arrows - Fix margins of handler rectangles when using arrows - Show handler rectangles in endpoints of 2-point arrows * Remove unnecessary values from app state for export * Use `resetTransform` instead of "retranslating" canvas space after each element rendering * Allow resizing 2-point arrows - Fix position of one of the handler rectangles * refactor variable initialization * Refactored to extract out mult-point generation to the abstracted function * prevent dragging on arrow creation if under threshold * Finalize selection during multi element mode when ENTER or ESC is clicked * Set dragging element to null when finalizing * Remove pathSegmentCircle from code * Check if element is any "non-value" instead of NULL * Show two points on any two point arrow and fix visibility of arrows during scroll * Resume recording when done with drawing - When deleting a multi select element, revert back to selection element type * Resize arrow starting points perfectly * Fix direction of arrow resize based for NW * Resume recording history when there is more than one arrow * Set dragging element to NULL when element is not locked * Blur active element when finalizing * Disable undo/redo for multielement, editingelement, and resizing element - Allow undoing parts of the arrow * Disable element visibility for arrow * Use points array for arrow bounds when bezier curve shape is not available Co-authored-by: David Luzar <luzar.david@gmail.com> Co-authored-by: Preet <833927+pshihn@users.noreply.github.com>
2020-01-31 21:16:33 +04:00
appState = JSON.parse(savedState) as AppState;
} catch (e) {
// Do nothing because appState is already null
}
}
return restore(elements, appState);
}
export function saveToLocalStorage(
elements: readonly ExcalidrawElement[],
2020-01-24 12:04:54 +02:00
state: AppState,
) {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(elements));
localStorage.setItem(LOCAL_STORAGE_KEY_STATE, JSON.stringify(state));
}
/**
* Returns the list of ids in Local Storage
* @returns array
*/
export function loadedScenes(): PreviousScene[] {
const storedPreviousScenes = localStorage.getItem(
LOCAL_STORAGE_SCENE_PREVIOUS_KEY,
);
if (storedPreviousScenes) {
try {
return JSON.parse(storedPreviousScenes);
} catch (e) {
console.error("Could not parse previously stored ids");
return [];
}
}
return [];
}
/**
* Append id to the list of Previous Scenes in Local Storage if not there yet
* @param id string
*/
export function addToLoadedScenes(id: string): void {
const scenes = [...loadedScenes()];
const newScene = scenes.every(scene => scene.id !== id);
if (newScene) {
scenes.push({
timestamp: Date.now(),
id,
});
}
localStorage.setItem(
LOCAL_STORAGE_SCENE_PREVIOUS_KEY,
JSON.stringify(scenes),
);
}