App.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import { useEffect, useState, useRef, useCallback } from "react";
  2. import InitialData from "./initialData";
  3. import Sidebar from "./sidebar/Sidebar";
  4. import "./App.scss";
  5. import initialData from "./initialData";
  6. import { MIME_TYPES } from "../../../constants";
  7. // This is so that we use the bundled excalidraw.development.js file instead
  8. // of the actual source code
  9. const { exportToCanvas, exportToSvg, exportToBlob } = window.Excalidraw;
  10. const Excalidraw = window.Excalidraw.default;
  11. const resolvablePromise = () => {
  12. let resolve;
  13. let reject;
  14. const promise = new Promise((_resolve, _reject) => {
  15. resolve = _resolve;
  16. reject = _reject;
  17. });
  18. promise.resolve = resolve;
  19. promise.reject = reject;
  20. return promise;
  21. };
  22. const renderTopRightUI = () => {
  23. return (
  24. <button onClick={() => alert("This is dummy top right UI")}>
  25. {" "}
  26. Click me{" "}
  27. </button>
  28. );
  29. };
  30. const renderFooter = () => {
  31. return (
  32. <button onClick={() => alert("This is dummy footer")}>
  33. {" "}
  34. custom footer{" "}
  35. </button>
  36. );
  37. };
  38. export default function App() {
  39. const excalidrawRef = useRef(null);
  40. const [viewModeEnabled, setViewModeEnabled] = useState(false);
  41. const [zenModeEnabled, setZenModeEnabled] = useState(false);
  42. const [gridModeEnabled, setGridModeEnabled] = useState(false);
  43. const [blobUrl, setBlobUrl] = useState(null);
  44. const [canvasUrl, setCanvasUrl] = useState(null);
  45. const [exportWithDarkMode, setExportWithDarkMode] = useState(false);
  46. const [theme, setTheme] = useState("light");
  47. const initialStatePromiseRef = useRef({ promise: null });
  48. if (!initialStatePromiseRef.current.promise) {
  49. initialStatePromiseRef.current.promise = resolvablePromise();
  50. }
  51. useEffect(() => {
  52. const fetchData = async () => {
  53. const res = await fetch("/rocket.jpeg");
  54. const imageData = await res.blob();
  55. const reader = new FileReader();
  56. reader.readAsDataURL(imageData);
  57. reader.onload = function () {
  58. const imagesArray = [
  59. {
  60. id: "rocket",
  61. dataURL: reader.result,
  62. mimeType: MIME_TYPES.jpg,
  63. created: 1644915140367,
  64. },
  65. ];
  66. initialStatePromiseRef.current.promise.resolve(InitialData);
  67. excalidrawRef.current.addFiles(imagesArray);
  68. };
  69. };
  70. fetchData();
  71. const onHashChange = () => {
  72. const hash = new URLSearchParams(window.location.hash.slice(1));
  73. const libraryUrl = hash.get("addLibrary");
  74. if (libraryUrl) {
  75. excalidrawRef.current.importLibrary(libraryUrl, hash.get("token"));
  76. }
  77. };
  78. window.addEventListener("hashchange", onHashChange, false);
  79. return () => {
  80. window.removeEventListener("hashchange", onHashChange);
  81. };
  82. }, []);
  83. const updateScene = () => {
  84. const sceneData = {
  85. elements: [
  86. {
  87. type: "rectangle",
  88. version: 141,
  89. versionNonce: 361174001,
  90. isDeleted: false,
  91. id: "oDVXy8D6rom3H1-LLH2-f",
  92. fillStyle: "hachure",
  93. strokeWidth: 1,
  94. strokeStyle: "solid",
  95. roughness: 1,
  96. opacity: 100,
  97. angle: 0,
  98. x: 100.50390625,
  99. y: 93.67578125,
  100. strokeColor: "#c92a2a",
  101. backgroundColor: "transparent",
  102. width: 186.47265625,
  103. height: 141.9765625,
  104. seed: 1968410350,
  105. groupIds: [],
  106. },
  107. ],
  108. appState: {
  109. viewBackgroundColor: "#edf2ff",
  110. },
  111. };
  112. excalidrawRef.current.updateScene(sceneData);
  113. };
  114. const onLinkOpen = useCallback((element, event) => {
  115. const link = element.link;
  116. const { nativeEvent } = event.detail;
  117. const isNewTab = nativeEvent.ctrlKey || nativeEvent.metaKey;
  118. const isNewWindow = nativeEvent.shiftKey;
  119. const isInternalLink =
  120. link.startsWith("/") || link.includes(window.location.origin);
  121. if (isInternalLink && !isNewTab && !isNewWindow) {
  122. // signal that we're handling the redirect ourselves
  123. event.preventDefault();
  124. // do a custom redirect, such as passing to react-router
  125. // ...
  126. }
  127. }, []);
  128. return (
  129. <div className="App">
  130. <h1> Excalidraw Example</h1>
  131. <Sidebar>
  132. <div className="button-wrapper">
  133. <button className="update-scene" onClick={updateScene}>
  134. Update Scene
  135. </button>
  136. <button
  137. className="reset-scene"
  138. onClick={() => {
  139. excalidrawRef.current.resetScene();
  140. }}
  141. >
  142. Reset Scene
  143. </button>
  144. <button
  145. onClick={() => {
  146. excalidrawRef.current.updateScene({
  147. libraryItems: [
  148. {
  149. status: "published",
  150. elements: initialData.libraryItems[0],
  151. },
  152. {
  153. status: "unpublished",
  154. elements: initialData.libraryItems[1],
  155. },
  156. ],
  157. });
  158. }}
  159. >
  160. Update Library
  161. </button>
  162. <label>
  163. <input
  164. type="checkbox"
  165. checked={viewModeEnabled}
  166. onChange={() => setViewModeEnabled(!viewModeEnabled)}
  167. />
  168. View mode
  169. </label>
  170. <label>
  171. <input
  172. type="checkbox"
  173. checked={zenModeEnabled}
  174. onChange={() => setZenModeEnabled(!zenModeEnabled)}
  175. />
  176. Zen mode
  177. </label>
  178. <label>
  179. <input
  180. type="checkbox"
  181. checked={gridModeEnabled}
  182. onChange={() => setGridModeEnabled(!gridModeEnabled)}
  183. />
  184. Grid mode
  185. </label>
  186. <label>
  187. <input
  188. type="checkbox"
  189. checked={theme === "dark"}
  190. onChange={() => {
  191. let newTheme = "light";
  192. if (theme === "light") {
  193. newTheme = "dark";
  194. }
  195. setTheme(newTheme);
  196. }}
  197. />
  198. Switch to Dark Theme
  199. </label>
  200. </div>
  201. <div className="excalidraw-wrapper">
  202. <Excalidraw
  203. ref={excalidrawRef}
  204. initialData={initialStatePromiseRef.current.promise}
  205. onChange={(elements, state) =>
  206. console.info("Elements :", elements, "State : ", state)
  207. }
  208. onPointerUpdate={(payload) => console.info(payload)}
  209. onCollabButtonClick={() =>
  210. window.alert("You clicked on collab button")
  211. }
  212. viewModeEnabled={viewModeEnabled}
  213. zenModeEnabled={zenModeEnabled}
  214. gridModeEnabled={gridModeEnabled}
  215. theme={theme}
  216. name="Custom name of drawing"
  217. UIOptions={{ canvasActions: { loadScene: false } }}
  218. renderTopRightUI={renderTopRightUI}
  219. renderFooter={renderFooter}
  220. onLinkOpen={onLinkOpen}
  221. />
  222. </div>
  223. <div className="export-wrapper button-wrapper">
  224. <label className="export-wrapper__checkbox">
  225. <input
  226. type="checkbox"
  227. checked={exportWithDarkMode}
  228. onChange={() => setExportWithDarkMode(!exportWithDarkMode)}
  229. />
  230. Export with dark mode
  231. </label>
  232. <button
  233. onClick={async () => {
  234. const svg = await exportToSvg({
  235. elements: excalidrawRef.current.getSceneElements(),
  236. appState: {
  237. ...initialData.appState,
  238. exportWithDarkMode,
  239. width: 300,
  240. height: 100,
  241. },
  242. embedScene: true,
  243. files: excalidrawRef.current.getFiles(),
  244. });
  245. document.querySelector(".export-svg").innerHTML = svg.outerHTML;
  246. }}
  247. >
  248. Export to SVG
  249. </button>
  250. <div className="export export-svg"></div>
  251. <button
  252. onClick={async () => {
  253. const blob = await exportToBlob({
  254. elements: excalidrawRef.current.getSceneElements(),
  255. mimeType: "image/png",
  256. appState: {
  257. ...initialData.appState,
  258. exportWithDarkMode,
  259. },
  260. files: excalidrawRef.current.getFiles(),
  261. });
  262. setBlobUrl(window.URL.createObjectURL(blob));
  263. }}
  264. >
  265. Export to Blob
  266. </button>
  267. <div className="export export-blob">
  268. <img src={blobUrl} alt="" />
  269. </div>
  270. <button
  271. onClick={async () => {
  272. const canvas = await exportToCanvas({
  273. elements: excalidrawRef.current.getSceneElements(),
  274. appState: {
  275. ...initialData.appState,
  276. exportWithDarkMode,
  277. },
  278. files: excalidrawRef.current.getFiles(),
  279. });
  280. const ctx = canvas.getContext("2d");
  281. ctx.font = "30px Virgil";
  282. ctx.strokeText("My custom text", 50, 60);
  283. setCanvasUrl(canvas.toDataURL());
  284. }}
  285. >
  286. Export to Canvas
  287. </button>
  288. <div className="export export-canvas">
  289. <img src={canvasUrl} alt="" />
  290. </div>
  291. </div>
  292. </Sidebar>
  293. </div>
  294. );
  295. }