restore.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import {
  2. ExcalidrawElement,
  3. FontFamily,
  4. ExcalidrawSelectionElement,
  5. } from "../element/types";
  6. import { AppState } from "../types";
  7. import { DataState, ImportedDataState } from "./types";
  8. import { isInvisiblySmallElement, getNormalizedDimensions } from "../element";
  9. import { isLinearElementType } from "../element/typeChecks";
  10. import { randomId } from "../random";
  11. import {
  12. FONT_FAMILY,
  13. DEFAULT_FONT_FAMILY,
  14. DEFAULT_TEXT_ALIGN,
  15. DEFAULT_VERTICAL_ALIGN,
  16. } from "../constants";
  17. import { getDefaultAppState } from "../appState";
  18. const getFontFamilyByName = (fontFamilyName: string): FontFamily => {
  19. for (const [id, fontFamilyString] of Object.entries(FONT_FAMILY)) {
  20. if (fontFamilyString.includes(fontFamilyName)) {
  21. return parseInt(id) as FontFamily;
  22. }
  23. }
  24. return DEFAULT_FONT_FAMILY;
  25. };
  26. const restoreElementWithProperties = <T extends ExcalidrawElement>(
  27. element: Required<T>,
  28. extra: Omit<Required<T>, keyof ExcalidrawElement>,
  29. ): T => {
  30. const base: Pick<T, keyof ExcalidrawElement> = {
  31. type: element.type,
  32. // all elements must have version > 0 so getSceneVersion() will pick up
  33. // newly added elements
  34. version: element.version || 1,
  35. versionNonce: element.versionNonce ?? 0,
  36. isDeleted: element.isDeleted ?? false,
  37. id: element.id || randomId(),
  38. fillStyle: element.fillStyle || "hachure",
  39. strokeWidth: element.strokeWidth || 1,
  40. strokeStyle: element.strokeStyle ?? "solid",
  41. roughness: element.roughness ?? 1,
  42. opacity: element.opacity == null ? 100 : element.opacity,
  43. angle: element.angle || 0,
  44. x: element.x || 0,
  45. y: element.y || 0,
  46. strokeColor: element.strokeColor,
  47. backgroundColor: element.backgroundColor,
  48. width: element.width || 0,
  49. height: element.height || 0,
  50. seed: element.seed ?? 1,
  51. groupIds: element.groupIds ?? [],
  52. strokeSharpness:
  53. element.strokeSharpness ??
  54. (isLinearElementType(element.type) ? "round" : "sharp"),
  55. boundElementIds: element.boundElementIds ?? [],
  56. };
  57. return ({
  58. ...base,
  59. ...getNormalizedDimensions(base),
  60. ...extra,
  61. } as unknown) as T;
  62. };
  63. const restoreElement = (
  64. element: Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
  65. ): typeof element => {
  66. switch (element.type) {
  67. case "text":
  68. let fontSize = element.fontSize;
  69. let fontFamily = element.fontFamily;
  70. if ("font" in element) {
  71. const [fontPx, _fontFamily]: [
  72. string,
  73. string,
  74. ] = (element as any).font.split(" ");
  75. fontSize = parseInt(fontPx, 10);
  76. fontFamily = getFontFamilyByName(_fontFamily);
  77. }
  78. return restoreElementWithProperties(element, {
  79. fontSize,
  80. fontFamily,
  81. text: element.text ?? "",
  82. baseline: element.baseline,
  83. textAlign: element.textAlign || DEFAULT_TEXT_ALIGN,
  84. verticalAlign: element.verticalAlign || DEFAULT_VERTICAL_ALIGN,
  85. });
  86. case "draw":
  87. case "line":
  88. case "arrow": {
  89. return restoreElementWithProperties(element, {
  90. startBinding: element.startBinding,
  91. endBinding: element.endBinding,
  92. points:
  93. // migrate old arrow model to new one
  94. !Array.isArray(element.points) || element.points.length < 2
  95. ? [
  96. [0, 0],
  97. [element.width, element.height],
  98. ]
  99. : element.points,
  100. lastCommittedPoint: null,
  101. });
  102. }
  103. // generic elements
  104. case "ellipse":
  105. return restoreElementWithProperties(element, {});
  106. case "rectangle":
  107. return restoreElementWithProperties(element, {});
  108. case "diamond":
  109. return restoreElementWithProperties(element, {});
  110. // don't use default case so as to catch a missing an element type case
  111. // (we also don't want to throw, but instead return void so we
  112. // filter out these unsupported elements from the restored array)
  113. }
  114. };
  115. export const restoreElements = (
  116. elements: ImportedDataState["elements"],
  117. ): ExcalidrawElement[] => {
  118. return (elements || []).reduce((elements, element) => {
  119. // filtering out selection, which is legacy, no longer kept in elements,
  120. // and causing issues if retained
  121. if (element.type !== "selection" && !isInvisiblySmallElement(element)) {
  122. const migratedElement = restoreElement(element);
  123. if (migratedElement) {
  124. elements.push(migratedElement);
  125. }
  126. }
  127. return elements;
  128. }, [] as ExcalidrawElement[]);
  129. };
  130. const restoreAppState = (
  131. appState: ImportedDataState["appState"],
  132. localAppState: Partial<AppState> | null,
  133. ): AppState => {
  134. appState = appState || {};
  135. const defaultAppState = getDefaultAppState();
  136. const nextAppState = {} as typeof defaultAppState;
  137. for (const [key, val] of Object.entries(defaultAppState) as [
  138. keyof typeof defaultAppState,
  139. any,
  140. ][]) {
  141. const restoredValue = appState[key];
  142. const localValue = localAppState ? localAppState[key] : undefined;
  143. (nextAppState as any)[key] =
  144. restoredValue !== undefined
  145. ? restoredValue
  146. : localValue !== undefined
  147. ? localValue
  148. : val;
  149. }
  150. return {
  151. ...nextAppState,
  152. offsetLeft: appState.offsetLeft || 0,
  153. offsetTop: appState.offsetTop || 0,
  154. };
  155. };
  156. export const restore = (
  157. data: ImportedDataState,
  158. /**
  159. * Local AppState (`this.state` or initial state from localStorage) so that we
  160. * don't overwrite local state with default values (when values not
  161. * explicitly specified).
  162. * Supply `null` if you can't get access to it.
  163. */
  164. localAppState: Partial<AppState> | null | undefined,
  165. ): DataState => {
  166. return {
  167. elements: restoreElements(data.elements),
  168. appState: restoreAppState(data.appState, localAppState || null),
  169. };
  170. };