restore.ts 9.4 KB

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