DebugCanvas.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import {
  2. ArrowheadArrowIcon,
  3. CloseIcon,
  4. TrashIcon,
  5. } from "@excalidraw/excalidraw/components/icons";
  6. import {
  7. bootstrapCanvas,
  8. getNormalizedCanvasDimensions,
  9. } from "@excalidraw/excalidraw/renderer/helpers";
  10. import { type AppState } from "@excalidraw/excalidraw/types";
  11. import { throttleRAF } from "@excalidraw/common";
  12. import { useCallback } from "react";
  13. import {
  14. isLineSegment,
  15. type GlobalPoint,
  16. type LineSegment,
  17. } from "@excalidraw/math";
  18. import { isCurve } from "@excalidraw/math/curve";
  19. import React from "react";
  20. import type { Curve } from "@excalidraw/math";
  21. import type { DebugElement } from "@excalidraw/utils/visualdebug";
  22. import { STORAGE_KEYS } from "../app_constants";
  23. const renderLine = (
  24. context: CanvasRenderingContext2D,
  25. zoom: number,
  26. segment: LineSegment<GlobalPoint>,
  27. color: string,
  28. ) => {
  29. context.save();
  30. context.strokeStyle = color;
  31. context.beginPath();
  32. context.moveTo(segment[0][0] * zoom, segment[0][1] * zoom);
  33. context.lineTo(segment[1][0] * zoom, segment[1][1] * zoom);
  34. context.stroke();
  35. context.restore();
  36. };
  37. const renderCubicBezier = (
  38. context: CanvasRenderingContext2D,
  39. zoom: number,
  40. [start, control1, control2, end]: Curve<GlobalPoint>,
  41. color: string,
  42. ) => {
  43. context.save();
  44. context.strokeStyle = color;
  45. context.beginPath();
  46. context.moveTo(start[0] * zoom, start[1] * zoom);
  47. context.bezierCurveTo(
  48. control1[0] * zoom,
  49. control1[1] * zoom,
  50. control2[0] * zoom,
  51. control2[1] * zoom,
  52. end[0] * zoom,
  53. end[1] * zoom,
  54. );
  55. context.stroke();
  56. context.restore();
  57. };
  58. const renderOrigin = (context: CanvasRenderingContext2D, zoom: number) => {
  59. context.strokeStyle = "#888";
  60. context.save();
  61. context.beginPath();
  62. context.moveTo(-10 * zoom, -10 * zoom);
  63. context.lineTo(10 * zoom, 10 * zoom);
  64. context.moveTo(10 * zoom, -10 * zoom);
  65. context.lineTo(-10 * zoom, 10 * zoom);
  66. context.stroke();
  67. context.save();
  68. };
  69. const render = (
  70. frame: DebugElement[],
  71. context: CanvasRenderingContext2D,
  72. appState: AppState,
  73. ) => {
  74. frame.forEach((el: DebugElement) => {
  75. switch (true) {
  76. case isLineSegment(el.data):
  77. renderLine(
  78. context,
  79. appState.zoom.value,
  80. el.data as LineSegment<GlobalPoint>,
  81. el.color,
  82. );
  83. break;
  84. case isCurve(el.data):
  85. renderCubicBezier(
  86. context,
  87. appState.zoom.value,
  88. el.data as Curve<GlobalPoint>,
  89. el.color,
  90. );
  91. break;
  92. default:
  93. throw new Error(`Unknown element type ${JSON.stringify(el)}`);
  94. }
  95. });
  96. };
  97. const _debugRenderer = (
  98. canvas: HTMLCanvasElement,
  99. appState: AppState,
  100. scale: number,
  101. refresh: () => void,
  102. ) => {
  103. const [normalizedWidth, normalizedHeight] = getNormalizedCanvasDimensions(
  104. canvas,
  105. scale,
  106. );
  107. const context = bootstrapCanvas({
  108. canvas,
  109. scale,
  110. normalizedWidth,
  111. normalizedHeight,
  112. viewBackgroundColor: "transparent",
  113. });
  114. // Apply zoom
  115. context.save();
  116. context.translate(
  117. appState.scrollX * appState.zoom.value,
  118. appState.scrollY * appState.zoom.value,
  119. );
  120. renderOrigin(context, appState.zoom.value);
  121. if (
  122. window.visualDebug?.currentFrame &&
  123. window.visualDebug?.data &&
  124. window.visualDebug.data.length > 0
  125. ) {
  126. // Render only one frame
  127. const [idx] = debugFrameData();
  128. render(window.visualDebug.data[idx], context, appState);
  129. } else {
  130. // Render all debug frames
  131. window.visualDebug?.data.forEach((frame) => {
  132. render(frame, context, appState);
  133. });
  134. }
  135. if (window.visualDebug) {
  136. window.visualDebug!.data =
  137. window.visualDebug?.data.map((frame) =>
  138. frame.filter((el) => el.permanent),
  139. ) ?? [];
  140. }
  141. };
  142. const debugFrameData = (): [number, number] => {
  143. const currentFrame = window.visualDebug?.currentFrame ?? 0;
  144. const frameCount = window.visualDebug?.data.length ?? 0;
  145. if (frameCount > 0) {
  146. return [currentFrame % frameCount, window.visualDebug?.currentFrame ?? 0];
  147. }
  148. return [0, 0];
  149. };
  150. export const saveDebugState = (debug: { enabled: boolean }) => {
  151. try {
  152. localStorage.setItem(
  153. STORAGE_KEYS.LOCAL_STORAGE_DEBUG,
  154. JSON.stringify(debug),
  155. );
  156. } catch (error: any) {
  157. console.error(error);
  158. }
  159. };
  160. export const debugRenderer = throttleRAF(
  161. (
  162. canvas: HTMLCanvasElement,
  163. appState: AppState,
  164. scale: number,
  165. refresh: () => void,
  166. ) => {
  167. _debugRenderer(canvas, appState, scale, refresh);
  168. },
  169. { trailing: true },
  170. );
  171. export const loadSavedDebugState = () => {
  172. let debug;
  173. try {
  174. const savedDebugState = localStorage.getItem(
  175. STORAGE_KEYS.LOCAL_STORAGE_DEBUG,
  176. );
  177. if (savedDebugState) {
  178. debug = JSON.parse(savedDebugState) as { enabled: boolean };
  179. }
  180. } catch (error: any) {
  181. console.error(error);
  182. }
  183. return debug ?? { enabled: false };
  184. };
  185. export const isVisualDebuggerEnabled = () =>
  186. Array.isArray(window.visualDebug?.data);
  187. export const DebugFooter = ({ onChange }: { onChange: () => void }) => {
  188. const moveForward = useCallback(() => {
  189. if (
  190. !window.visualDebug?.currentFrame ||
  191. isNaN(window.visualDebug?.currentFrame ?? -1)
  192. ) {
  193. window.visualDebug!.currentFrame = 0;
  194. }
  195. window.visualDebug!.currentFrame += 1;
  196. onChange();
  197. }, [onChange]);
  198. const moveBackward = useCallback(() => {
  199. if (
  200. !window.visualDebug?.currentFrame ||
  201. isNaN(window.visualDebug?.currentFrame ?? -1) ||
  202. window.visualDebug?.currentFrame < 1
  203. ) {
  204. window.visualDebug!.currentFrame = 1;
  205. }
  206. window.visualDebug!.currentFrame -= 1;
  207. onChange();
  208. }, [onChange]);
  209. const reset = useCallback(() => {
  210. window.visualDebug!.currentFrame = undefined;
  211. onChange();
  212. }, [onChange]);
  213. const trashFrames = useCallback(() => {
  214. if (window.visualDebug) {
  215. window.visualDebug.currentFrame = undefined;
  216. window.visualDebug.data = [];
  217. }
  218. onChange();
  219. }, [onChange]);
  220. return (
  221. <>
  222. <button
  223. className="ToolIcon_type_button"
  224. data-testid="debug-forward"
  225. aria-label="Move forward"
  226. type="button"
  227. onClick={trashFrames}
  228. >
  229. <div
  230. className="ToolIcon__icon"
  231. aria-hidden="true"
  232. aria-disabled="false"
  233. >
  234. {TrashIcon}
  235. </div>
  236. </button>
  237. <button
  238. className="ToolIcon_type_button"
  239. data-testid="debug-forward"
  240. aria-label="Move forward"
  241. type="button"
  242. onClick={moveBackward}
  243. >
  244. <div
  245. className="ToolIcon__icon"
  246. aria-hidden="true"
  247. aria-disabled="false"
  248. >
  249. <ArrowheadArrowIcon flip />
  250. </div>
  251. </button>
  252. <button
  253. className="ToolIcon_type_button"
  254. data-testid="debug-forward"
  255. aria-label="Move forward"
  256. type="button"
  257. onClick={reset}
  258. >
  259. <div
  260. className="ToolIcon__icon"
  261. aria-hidden="true"
  262. aria-disabled="false"
  263. >
  264. {CloseIcon}
  265. </div>
  266. </button>
  267. <button
  268. className="ToolIcon_type_button"
  269. data-testid="debug-backward"
  270. aria-label="Move backward"
  271. type="button"
  272. onClick={moveForward}
  273. >
  274. <div
  275. className="ToolIcon__icon"
  276. aria-hidden="true"
  277. aria-disabled="false"
  278. >
  279. <ArrowheadArrowIcon />
  280. </div>
  281. </button>
  282. </>
  283. );
  284. };
  285. interface DebugCanvasProps {
  286. appState: AppState;
  287. scale: number;
  288. }
  289. const DebugCanvas = React.forwardRef<HTMLCanvasElement, DebugCanvasProps>(
  290. ({ appState, scale }, ref) => {
  291. const { width, height } = appState;
  292. return (
  293. <canvas
  294. style={{
  295. width,
  296. height,
  297. position: "absolute",
  298. zIndex: 2,
  299. pointerEvents: "none",
  300. }}
  301. width={width * scale}
  302. height={height * scale}
  303. ref={ref}
  304. >
  305. Debug Canvas
  306. </canvas>
  307. );
  308. },
  309. );
  310. export default DebugCanvas;