Răsfoiți Sursa

add extractCodeFromMxfile method

Yuki Takei 3 ani în urmă
părinte
comite
2770dead07

+ 18 - 5
packages/app/src/components/PageEditor/DrawioCommunicationHelper.ts

@@ -1,3 +1,5 @@
+import { extractCodeFromMxfile } from '@growi/remark-drawio-plugin';
+
 import loggerFactory from '~/utils/logger';
 
 
@@ -41,11 +43,7 @@ export class DrawioCommunicationHelper {
       }
     }
 
-    if (event.data === 'ready') {
-      event.source?.postMessage(drawioMxFile, { targetOrigin: '*' });
-      return;
-    }
-
+    // configure
     if (event.data === '{"event":"configure"}') {
       if (event.source == null) {
         return;
@@ -63,6 +61,21 @@ export class DrawioCommunicationHelper {
       return;
     }
 
+    // restore diagram data
+    if (event.data === 'ready') {
+      let code = drawioMxFile;
+      try {
+        code = extractCodeFromMxfile(drawioMxFile);
+      }
+      // catch error if drawioMxFile is not XML
+      catch (err) {
+        // do nothing because drawioMxFile might be base64 code
+      }
+
+      event.source?.postMessage(code, { targetOrigin: '*' });
+      return;
+    }
+
     if (typeof event.data === 'string' && event.data.match(/mxfile/)) {
       if (event.data.length > 0) {
         const parser = new DOMParser();

+ 3 - 4
packages/app/src/components/ReactMarkdownComponents/DrawioViewerWithEditButton.tsx

@@ -22,8 +22,8 @@ export const DrawioViewerWithEditButton = React.memo((props: DrawioViewerProps):
   const [mxfile, setMxfile] = useState('');
 
   const editButtonClickHandler = useCallback(() => {
-    // openDrawioModal(mxfile);
-  }, []);
+    openDrawioModal(mxfile);
+  }, [mxfile, openDrawioModal]);
 
   const renderingStartHandler = useCallback(() => {
     setMounted(false);
@@ -33,8 +33,7 @@ export const DrawioViewerWithEditButton = React.memo((props: DrawioViewerProps):
     setMounted(viewer != null);
 
     if (viewer != null) {
-      // console.log(viewer);
-      // setMxfile(viewer.xml);
+      setMxfile(viewer.xml);
     }
   }, []);
 

+ 6 - 3
packages/remark-drawio-plugin/src/utils/embed.ts

@@ -2,13 +2,16 @@
 import pako from 'pako';
 import xmldoc from 'xmldoc';
 
+export const extractCodeFromMxfile = (input: string): string => {
+  const doc = new xmldoc.XmlDocument(input);
+  return doc.valueWithPath('diagram');
+};
+
 const validateInputData = (input: string): boolean => {
   let data = input;
 
   try {
-    const doc = new xmldoc.XmlDocument(data);
-    const diagram = doc.valueWithPath('diagram');
-    data = diagram;
+    data = extractCodeFromMxfile(data);
   }
   catch (e) {
     // ignore