restore.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import {
  2. ExcalidrawElement,
  3. ExcalidrawSelectionElement,
  4. FontFamilyValues,
  5. } from "../element/types";
  6. import {
  7. AppState,
  8. BinaryFiles,
  9. LibraryItem,
  10. NormalizedZoomValue,
  11. } from "../types";
  12. import { ImportedDataState } from "./types";
  13. import { getNormalizedDimensions, isInvisiblySmallElement } from "../element";
  14. import { isLinearElementType } from "../element/typeChecks";
  15. import { randomId } from "../random";
  16. import {
  17. DEFAULT_FONT_FAMILY,
  18. DEFAULT_TEXT_ALIGN,
  19. DEFAULT_VERTICAL_ALIGN,
  20. FONT_FAMILY,
  21. } from "../constants";
  22. import { getDefaultAppState } from "../appState";
  23. import { LinearElementEditor } from "../element/linearElementEditor";
  24. import { bumpVersion } from "../element/mutateElement";
  25. import { getUpdatedTimestamp } from "../utils";
  26. import { arrayToMap } from "../utils";
  27. type RestoredAppState = Omit<
  28. AppState,
  29. "offsetTop" | "offsetLeft" | "width" | "height"
  30. >;
  31. export const AllowedExcalidrawActiveTools: Record<
  32. AppState["activeTool"]["type"],
  33. boolean
  34. > = {
  35. selection: true,
  36. text: true,
  37. rectangle: true,
  38. diamond: true,
  39. ellipse: true,
  40. line: true,
  41. image: true,
  42. arrow: true,
  43. freedraw: true,
  44. eraser: false,
  45. };
  46. export type RestoredDataState = {
  47. elements: ExcalidrawElement[];
  48. appState: RestoredAppState;
  49. files: BinaryFiles;
  50. };
  51. const getFontFamilyByName = (fontFamilyName: string): FontFamilyValues => {
  52. if (Object.keys(FONT_FAMILY).includes(fontFamilyName)) {
  53. return FONT_FAMILY[
  54. fontFamilyName as keyof typeof FONT_FAMILY
  55. ] as FontFamilyValues;
  56. }
  57. return DEFAULT_FONT_FAMILY;
  58. };
  59. const restoreElementWithProperties = <
  60. T extends ExcalidrawElement,
  61. K extends Pick<T, keyof Omit<Required<T>, keyof ExcalidrawElement>>,
  62. >(
  63. element: Required<T> & {
  64. /** @deprecated */
  65. boundElementIds?: readonly ExcalidrawElement["id"][];
  66. },
  67. extra: Pick<
  68. T,
  69. // This extra Pick<T, keyof K> ensure no excess properties are passed.
  70. // @ts-ignore TS complains here but type checks the call sites fine.
  71. keyof K
  72. > &
  73. Partial<Pick<ExcalidrawElement, "type" | "x" | "y">>,
  74. ): T => {
  75. const base: Pick<T, keyof ExcalidrawElement> = {
  76. type: extra.type || element.type,
  77. // all elements must have version > 0 so getSceneVersion() will pick up
  78. // newly added elements
  79. version: element.version || 1,
  80. versionNonce: element.versionNonce ?? 0,
  81. isDeleted: element.isDeleted ?? false,
  82. id: element.id || randomId(),
  83. fillStyle: element.fillStyle || "hachure",
  84. strokeWidth: element.strokeWidth || 1,
  85. strokeStyle: element.strokeStyle ?? "solid",
  86. roughness: element.roughness ?? 1,
  87. opacity: element.opacity == null ? 100 : element.opacity,
  88. angle: element.angle || 0,
  89. x: extra.x ?? element.x ?? 0,
  90. y: extra.y ?? element.y ?? 0,
  91. strokeColor: element.strokeColor,
  92. backgroundColor: element.backgroundColor,
  93. width: element.width || 0,
  94. height: element.height || 0,
  95. seed: element.seed ?? 1,
  96. groupIds: element.groupIds ?? [],
  97. strokeSharpness:
  98. element.strokeSharpness ??
  99. (isLinearElementType(element.type) ? "round" : "sharp"),
  100. boundElements: element.boundElementIds
  101. ? element.boundElementIds.map((id) => ({ type: "arrow", id }))
  102. : element.boundElements ?? [],
  103. updated: element.updated ?? getUpdatedTimestamp(),
  104. link: element.link ?? null,
  105. };
  106. return {
  107. ...base,
  108. ...getNormalizedDimensions(base),
  109. ...extra,
  110. } as unknown as T;
  111. };
  112. const restoreElement = (
  113. element: Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
  114. ): typeof element | null => {
  115. switch (element.type) {
  116. case "text":
  117. let fontSize = element.fontSize;
  118. let fontFamily = element.fontFamily;
  119. if ("font" in element) {
  120. const [fontPx, _fontFamily]: [string, string] = (
  121. element as any
  122. ).font.split(" ");
  123. fontSize = parseInt(fontPx, 10);
  124. fontFamily = getFontFamilyByName(_fontFamily);
  125. }
  126. return restoreElementWithProperties(element, {
  127. fontSize,
  128. fontFamily,
  129. text: element.text ?? "",
  130. baseline: element.baseline,
  131. textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
  132. verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
  133. containerId: element.containerId ?? null,
  134. originalText: element.originalText || element.text,
  135. });
  136. case "freedraw": {
  137. return restoreElementWithProperties(element, {
  138. points: element.points,
  139. lastCommittedPoint: null,
  140. simulatePressure: element.simulatePressure,
  141. pressures: element.pressures,
  142. });
  143. }
  144. case "image":
  145. return restoreElementWithProperties(element, {
  146. status: element.status || "pending",
  147. fileId: element.fileId,
  148. scale: element.scale || [1, 1],
  149. });
  150. case "line":
  151. // @ts-ignore LEGACY type
  152. // eslint-disable-next-line no-fallthrough
  153. case "draw":
  154. case "arrow": {
  155. const {
  156. startArrowhead = null,
  157. endArrowhead = element.type === "arrow" ? "arrow" : null,
  158. } = element;
  159. let x = element.x;
  160. let y = element.y;
  161. let points = // migrate old arrow model to new one
  162. !Array.isArray(element.points) || element.points.length < 2
  163. ? [
  164. [0, 0],
  165. [element.width, element.height],
  166. ]
  167. : element.points;
  168. if (points[0][0] !== 0 || points[0][1] !== 0) {
  169. ({ points, x, y } = LinearElementEditor.getNormalizedPoints(element));
  170. }
  171. return restoreElementWithProperties(element, {
  172. type:
  173. (element.type as ExcalidrawElement["type"] | "draw") === "draw"
  174. ? "line"
  175. : element.type,
  176. startBinding: element.startBinding,
  177. endBinding: element.endBinding,
  178. lastCommittedPoint: null,
  179. startArrowhead,
  180. endArrowhead,
  181. points,
  182. x,
  183. y,
  184. });
  185. }
  186. // generic elements
  187. case "ellipse":
  188. return restoreElementWithProperties(element, {});
  189. case "rectangle":
  190. return restoreElementWithProperties(element, {});
  191. case "diamond":
  192. return restoreElementWithProperties(element, {});
  193. // Don't use default case so as to catch a missing an element type case.
  194. // We also don't want to throw, but instead return void so we filter
  195. // out these unsupported elements from the restored array.
  196. }
  197. };
  198. export const restoreElements = (
  199. elements: ImportedDataState["elements"],
  200. /** NOTE doesn't serve for reconciliation */
  201. localElements: readonly ExcalidrawElement[] | null | undefined,
  202. ): ExcalidrawElement[] => {
  203. const localElementsMap = localElements ? arrayToMap(localElements) : null;
  204. return (elements || []).reduce((elements, element) => {
  205. // filtering out selection, which is legacy, no longer kept in elements,
  206. // and causing issues if retained
  207. if (element.type !== "selection" && !isInvisiblySmallElement(element)) {
  208. let migratedElement: ExcalidrawElement | null = restoreElement(element);
  209. if (migratedElement) {
  210. const localElement = localElementsMap?.get(element.id);
  211. if (localElement && localElement.version > migratedElement.version) {
  212. migratedElement = bumpVersion(migratedElement, localElement.version);
  213. }
  214. elements.push(migratedElement);
  215. }
  216. }
  217. return elements;
  218. }, [] as ExcalidrawElement[]);
  219. };
  220. export const restoreAppState = (
  221. appState: ImportedDataState["appState"],
  222. localAppState: Partial<AppState> | null | undefined,
  223. ): RestoredAppState => {
  224. appState = appState || {};
  225. const defaultAppState = getDefaultAppState();
  226. const nextAppState = {} as typeof defaultAppState;
  227. for (const [key, defaultValue] of Object.entries(defaultAppState) as [
  228. keyof typeof defaultAppState,
  229. any,
  230. ][]) {
  231. const suppliedValue = appState[key];
  232. const localValue = localAppState ? localAppState[key] : undefined;
  233. (nextAppState as any)[key] =
  234. suppliedValue !== undefined
  235. ? suppliedValue
  236. : localValue !== undefined
  237. ? localValue
  238. : defaultValue;
  239. }
  240. return {
  241. ...nextAppState,
  242. activeTool: {
  243. lastActiveToolBeforeEraser: null,
  244. locked: nextAppState.activeTool.locked ?? false,
  245. type: AllowedExcalidrawActiveTools[nextAppState.activeTool.type]
  246. ? nextAppState.activeTool.type ?? "selection"
  247. : "selection",
  248. },
  249. // Migrates from previous version where appState.zoom was a number
  250. zoom:
  251. typeof appState.zoom === "number"
  252. ? {
  253. value: appState.zoom as NormalizedZoomValue,
  254. }
  255. : appState.zoom || defaultAppState.zoom,
  256. };
  257. };
  258. export const restore = (
  259. data: ImportedDataState | null,
  260. /**
  261. * Local AppState (`this.state` or initial state from localStorage) so that we
  262. * don't overwrite local state with default values (when values not
  263. * explicitly specified).
  264. * Supply `null` if you can't get access to it.
  265. */
  266. localAppState: Partial<AppState> | null | undefined,
  267. localElements: readonly ExcalidrawElement[] | null | undefined,
  268. ): RestoredDataState => {
  269. return {
  270. elements: restoreElements(data?.elements, localElements),
  271. appState: restoreAppState(data?.appState, localAppState || null),
  272. files: data?.files || {},
  273. };
  274. };
  275. export const restoreLibraryItems = (
  276. libraryItems: NonOptional<ImportedDataState["libraryItems"]>,
  277. defaultStatus: LibraryItem["status"],
  278. ) => {
  279. const restoredItems: LibraryItem[] = [];
  280. for (const item of libraryItems) {
  281. // migrate older libraries
  282. if (Array.isArray(item)) {
  283. restoredItems.push({
  284. status: defaultStatus,
  285. elements: item,
  286. id: randomId(),
  287. created: Date.now(),
  288. });
  289. } else {
  290. const _item = item as MarkOptional<LibraryItem, "id" | "status">;
  291. restoredItems.push({
  292. ..._item,
  293. id: _item.id || randomId(),
  294. status: _item.status || defaultStatus,
  295. created: _item.created || Date.now(),
  296. });
  297. }
  298. }
  299. return restoredItems;
  300. };