newElement.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import {
  2. ExcalidrawElement,
  3. ExcalidrawImageElement,
  4. ExcalidrawTextElement,
  5. ExcalidrawLinearElement,
  6. ExcalidrawGenericElement,
  7. NonDeleted,
  8. TextAlign,
  9. GroupId,
  10. VerticalAlign,
  11. Arrowhead,
  12. ExcalidrawFreeDrawElement,
  13. FontFamilyValues,
  14. } from "../element/types";
  15. import { measureText, getFontString } from "../utils";
  16. import { randomInteger, randomId } from "../random";
  17. import { newElementWith } from "./mutateElement";
  18. import { getNewGroupIdsForDuplication } from "../groups";
  19. import { AppState } from "../types";
  20. import { getElementAbsoluteCoords } from ".";
  21. import { adjustXYWithRotation } from "../math";
  22. import { getResizedElementAbsoluteCoords } from "./bounds";
  23. type ElementConstructorOpts = MarkOptional<
  24. Omit<ExcalidrawGenericElement, "id" | "type" | "isDeleted">,
  25. | "width"
  26. | "height"
  27. | "angle"
  28. | "groupIds"
  29. | "boundElementIds"
  30. | "seed"
  31. | "version"
  32. | "versionNonce"
  33. >;
  34. const _newElementBase = <T extends ExcalidrawElement>(
  35. type: T["type"],
  36. {
  37. x,
  38. y,
  39. strokeColor,
  40. backgroundColor,
  41. fillStyle,
  42. strokeWidth,
  43. strokeStyle,
  44. roughness,
  45. opacity,
  46. width = 0,
  47. height = 0,
  48. angle = 0,
  49. groupIds = [],
  50. strokeSharpness,
  51. boundElementIds = null,
  52. ...rest
  53. }: ElementConstructorOpts & Omit<Partial<ExcalidrawGenericElement>, "type">,
  54. ) => ({
  55. id: rest.id || randomId(),
  56. type,
  57. x,
  58. y,
  59. width,
  60. height,
  61. angle,
  62. strokeColor,
  63. backgroundColor,
  64. fillStyle,
  65. strokeWidth,
  66. strokeStyle,
  67. roughness,
  68. opacity,
  69. groupIds,
  70. strokeSharpness,
  71. seed: rest.seed ?? randomInteger(),
  72. version: rest.version || 1,
  73. versionNonce: rest.versionNonce ?? 0,
  74. isDeleted: false as false,
  75. boundElementIds,
  76. });
  77. export const newElement = (
  78. opts: {
  79. type: ExcalidrawGenericElement["type"];
  80. } & ElementConstructorOpts,
  81. ): NonDeleted<ExcalidrawGenericElement> =>
  82. _newElementBase<ExcalidrawGenericElement>(opts.type, opts);
  83. /** computes element x/y offset based on textAlign/verticalAlign */
  84. const getTextElementPositionOffsets = (
  85. opts: {
  86. textAlign: ExcalidrawTextElement["textAlign"];
  87. verticalAlign: ExcalidrawTextElement["verticalAlign"];
  88. },
  89. metrics: {
  90. width: number;
  91. height: number;
  92. },
  93. ) => {
  94. return {
  95. x:
  96. opts.textAlign === "center"
  97. ? metrics.width / 2
  98. : opts.textAlign === "right"
  99. ? metrics.width
  100. : 0,
  101. y: opts.verticalAlign === "middle" ? metrics.height / 2 : 0,
  102. };
  103. };
  104. export const newTextElement = (
  105. opts: {
  106. text: string;
  107. fontSize: number;
  108. fontFamily: FontFamilyValues;
  109. textAlign: TextAlign;
  110. verticalAlign: VerticalAlign;
  111. } & ElementConstructorOpts,
  112. ): NonDeleted<ExcalidrawTextElement> => {
  113. const metrics = measureText(opts.text, getFontString(opts));
  114. const offsets = getTextElementPositionOffsets(opts, metrics);
  115. const textElement = newElementWith(
  116. {
  117. ..._newElementBase<ExcalidrawTextElement>("text", opts),
  118. text: opts.text,
  119. fontSize: opts.fontSize,
  120. fontFamily: opts.fontFamily,
  121. textAlign: opts.textAlign,
  122. verticalAlign: opts.verticalAlign,
  123. x: opts.x - offsets.x,
  124. y: opts.y - offsets.y,
  125. width: metrics.width,
  126. height: metrics.height,
  127. baseline: metrics.baseline,
  128. },
  129. {},
  130. );
  131. return textElement;
  132. };
  133. const getAdjustedDimensions = (
  134. element: ExcalidrawTextElement,
  135. nextText: string,
  136. ): {
  137. x: number;
  138. y: number;
  139. width: number;
  140. height: number;
  141. baseline: number;
  142. } => {
  143. const {
  144. width: nextWidth,
  145. height: nextHeight,
  146. baseline: nextBaseline,
  147. } = measureText(nextText, getFontString(element));
  148. const { textAlign, verticalAlign } = element;
  149. let x: number;
  150. let y: number;
  151. if (textAlign === "center" && verticalAlign === "middle") {
  152. const prevMetrics = measureText(element.text, getFontString(element));
  153. const offsets = getTextElementPositionOffsets(element, {
  154. width: nextWidth - prevMetrics.width,
  155. height: nextHeight - prevMetrics.height,
  156. });
  157. x = element.x - offsets.x;
  158. y = element.y - offsets.y;
  159. } else {
  160. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  161. const [nextX1, nextY1, nextX2, nextY2] = getResizedElementAbsoluteCoords(
  162. element,
  163. nextWidth,
  164. nextHeight,
  165. );
  166. const deltaX1 = (x1 - nextX1) / 2;
  167. const deltaY1 = (y1 - nextY1) / 2;
  168. const deltaX2 = (x2 - nextX2) / 2;
  169. const deltaY2 = (y2 - nextY2) / 2;
  170. [x, y] = adjustXYWithRotation(
  171. {
  172. s: true,
  173. e: textAlign === "center" || textAlign === "left",
  174. w: textAlign === "center" || textAlign === "right",
  175. },
  176. element.x,
  177. element.y,
  178. element.angle,
  179. deltaX1,
  180. deltaY1,
  181. deltaX2,
  182. deltaY2,
  183. );
  184. }
  185. return {
  186. width: nextWidth,
  187. height: nextHeight,
  188. x: Number.isFinite(x) ? x : element.x,
  189. y: Number.isFinite(y) ? y : element.y,
  190. baseline: nextBaseline,
  191. };
  192. };
  193. export const updateTextElement = (
  194. element: ExcalidrawTextElement,
  195. { text, isDeleted }: { text: string; isDeleted?: boolean },
  196. ): ExcalidrawTextElement => {
  197. return newElementWith(element, {
  198. text,
  199. isDeleted: isDeleted ?? element.isDeleted,
  200. ...getAdjustedDimensions(element, text),
  201. });
  202. };
  203. export const newFreeDrawElement = (
  204. opts: {
  205. type: "freedraw";
  206. points?: ExcalidrawFreeDrawElement["points"];
  207. simulatePressure: boolean;
  208. } & ElementConstructorOpts,
  209. ): NonDeleted<ExcalidrawFreeDrawElement> => {
  210. return {
  211. ..._newElementBase<ExcalidrawFreeDrawElement>(opts.type, opts),
  212. points: opts.points || [],
  213. pressures: [],
  214. simulatePressure: opts.simulatePressure,
  215. lastCommittedPoint: null,
  216. };
  217. };
  218. export const newLinearElement = (
  219. opts: {
  220. type: ExcalidrawLinearElement["type"];
  221. startArrowhead: Arrowhead | null;
  222. endArrowhead: Arrowhead | null;
  223. points?: ExcalidrawLinearElement["points"];
  224. } & ElementConstructorOpts,
  225. ): NonDeleted<ExcalidrawLinearElement> => {
  226. return {
  227. ..._newElementBase<ExcalidrawLinearElement>(opts.type, opts),
  228. points: opts.points || [],
  229. lastCommittedPoint: null,
  230. startBinding: null,
  231. endBinding: null,
  232. startArrowhead: opts.startArrowhead,
  233. endArrowhead: opts.endArrowhead,
  234. };
  235. };
  236. export const newImageElement = (
  237. opts: {
  238. type: ExcalidrawImageElement["type"];
  239. } & ElementConstructorOpts,
  240. ): NonDeleted<ExcalidrawImageElement> => {
  241. return {
  242. ..._newElementBase<ExcalidrawImageElement>("image", opts),
  243. // in the future we'll support changing stroke color for some SVG elements,
  244. // and `transparent` will likely mean "use original colors of the image"
  245. strokeColor: "transparent",
  246. status: "pending",
  247. fileId: null,
  248. scale: [1, 1],
  249. };
  250. };
  251. // Simplified deep clone for the purpose of cloning ExcalidrawElement only
  252. // (doesn't clone Date, RegExp, Map, Set, Typed arrays etc.)
  253. //
  254. // Adapted from https://github.com/lukeed/klona
  255. export const deepCopyElement = (val: any, depth: number = 0) => {
  256. if (val == null || typeof val !== "object") {
  257. return val;
  258. }
  259. if (Object.prototype.toString.call(val) === "[object Object]") {
  260. const tmp =
  261. typeof val.constructor === "function"
  262. ? Object.create(Object.getPrototypeOf(val))
  263. : {};
  264. for (const key in val) {
  265. if (val.hasOwnProperty(key)) {
  266. // don't copy top-level shape property, which we want to regenerate
  267. if (depth === 0 && (key === "shape" || key === "canvas")) {
  268. continue;
  269. }
  270. tmp[key] = deepCopyElement(val[key], depth + 1);
  271. }
  272. }
  273. return tmp;
  274. }
  275. if (Array.isArray(val)) {
  276. let k = val.length;
  277. const arr = new Array(k);
  278. while (k--) {
  279. arr[k] = deepCopyElement(val[k], depth + 1);
  280. }
  281. return arr;
  282. }
  283. return val;
  284. };
  285. /**
  286. * Duplicate an element, often used in the alt-drag operation.
  287. * Note that this method has gotten a bit complicated since the
  288. * introduction of gruoping/ungrouping elements.
  289. * @param editingGroupId The current group being edited. The new
  290. * element will inherit this group and its
  291. * parents.
  292. * @param groupIdMapForOperation A Map that maps old group IDs to
  293. * duplicated ones. If you are duplicating
  294. * multiple elements at once, share this map
  295. * amongst all of them
  296. * @param element Element to duplicate
  297. * @param overrides Any element properties to override
  298. */
  299. export const duplicateElement = <TElement extends Mutable<ExcalidrawElement>>(
  300. editingGroupId: AppState["editingGroupId"],
  301. groupIdMapForOperation: Map<GroupId, GroupId>,
  302. element: TElement,
  303. overrides?: Partial<TElement>,
  304. ): TElement => {
  305. let copy: TElement = deepCopyElement(element);
  306. if (process.env.NODE_ENV === "test") {
  307. copy.id = `${copy.id}_copy`;
  308. // `window.h` may not be defined in some unit tests
  309. if (
  310. window.h?.app
  311. ?.getSceneElementsIncludingDeleted()
  312. .find((el) => el.id === copy.id)
  313. ) {
  314. copy.id += "_copy";
  315. }
  316. } else {
  317. copy.id = randomId();
  318. }
  319. copy.seed = randomInteger();
  320. copy.groupIds = getNewGroupIdsForDuplication(
  321. copy.groupIds,
  322. editingGroupId,
  323. (groupId) => {
  324. if (!groupIdMapForOperation.has(groupId)) {
  325. groupIdMapForOperation.set(groupId, randomId());
  326. }
  327. return groupIdMapForOperation.get(groupId)!;
  328. },
  329. );
  330. if (overrides) {
  331. copy = Object.assign(copy, overrides);
  332. }
  333. return copy;
  334. };