aduh95 / viz.js

A hack to put Graphviz on the web.
http://aduh95.github.io/viz.js-playground/
MIT License
39 stars 8 forks source link

Migrating from mdaines/viz.js #31

Closed Neriderc closed 10 months ago

Neriderc commented 1 year ago

I have a pretty basic setup of viz.js, using the mdaines/viz.js release, which literally has a file called "viz.js". The setup is pretty simple. I load the script:

<script src="javascript/viz.js"></script>

Create a worker:

    const workerURL = "javascript/full.renderer.js");
    let viz = new Viz({
        workerURL: workerURL
    });

And then render the SVG:

const images = [...lastDotStr.matchAll(/<IMG[^>]+SRC="([^"]*)/gmi)].map(function (matches) {
    return {
        path: matches[1],
        width: '150px',
        height: '150px'
    };
});
return viz.renderSVGElement(lastDotStr, {
    images: images

I'm not familiar with NPM and so am having quite some trouble working out how this forked and updated version can be used to replace the quite outdated version I currently have.

Any tips on where to start would be appreciated!

aduh95 commented 1 year ago

Did you read https://github.com/aduh95/viz.js#using-a-cdn?

Neriderc commented 1 year ago

Thanks, I've given this a try. I got errors such as "import declarations may only appear at top level of a module" in Firefox and "Cannot use import statement outside a module" in Chromium.

I read the bit about importing, so replaced that line with the provided code. Ended up with this, a complete copy paste of your example code:

// worker.js
    /**
     * Lazy-loads Viz.js message handler
     * @returns {(event: MessageEvent) => Promise<any>}
     */
    function getVizMesssageHandler() {
        if (this._messageHandler === undefined) {
            const vizDistFolder = "https://unpkg.com/@aduh95/viz.js/dist";
            const Module = {
                // locateFile is used by render module to locate WASM file.
                locateFile: (fileName) => `${vizDistFolder}/${fileName}`,
            };
            this._messageHandler = import(Module.locateFile("render.browser.js")).then(
                ({ default: init, onmessage }) => {
                    // to avoid conflicts, disable viz.js message handler
                    self.removeEventListener("message", onmessage);

                    return init(Module).then(() => onmessage);
                }
            );
        }
        return this._messageHandler;
    }

    self.addEventListener("message", (event) => {
        if (event.data.id) {
            // handling event sent by viz.js
            getVizMessageHandler()
                .then((onmessage) => onmessage(event))
                .catch((error) => {
                    // handle dynamic import error here
                    console.error(error);

                    // Note: If an error is emitted by Viz.js internals (dot syntax error,
                    // WASM file initialization error, etc.), the error is catch and sent
                    // directly through postMessage.
                    // If you think this behavior is not ideal, please open an issue.
                });
        } else {
            // handle other messages
        }
    });

    const locateFile = (fileName) =>
        "https://unpkg.com/@aduh95/viz.js/dist/" + fileName;
    const onmessage = async function (event) {
        if (this.messageHandler === undefined) {
            // Lazy loading actual handler
            const { default: init, onmessage } = await import(
                Module.locateFile("render.browser.js")
                );
            // Removing default MessageEvent handler
            removeEventListener("message", onmessage);
            await init(Module);
            this.messageHandler = onmessage;
        }
        return this.messageHandler(event);
    };
    const vizOptions = {
        workerURL: URL.createObjectURL(
            new Blob(
                [
                    "const Module = { locateFile:",
                    locateFile.toString(),
                    "};",
                    "onmessage=",
                    onmessage.toString(),
                ],
                { type: "application/javascript" }
            )
        ),
    };

    async function dot2svg(dot, options) {
        const viz = new Viz(vizOptions);

        return viz.renderString(dot, options);
    }

Then I tried running it: dot2svg(dotStr, {});

But I get the error: "Error: Dynamic module import is disabled or not supported in this context"

I only get this error in Firefox. In Chromium, I get no javascript errors but the output is a sort of half-compiled diagram: image

This is based on the following DOT:

digraph WT_Graph {
ranksep="0.15 equally"
nodesep="0.15"
dpi="72"
mclimit="1"
rankdir="LR"
pagedir="LT"
bgcolor="#eeeeee"
edge [ style=solid, arrowhead=normal arrowtail=none];
node [ shape=plaintext fontsize="10" fontname="Arial, Sans, Arial, Sans"];
X1 [ label=<<TABLE COLOR="#606060" BORDER="1" CELLBORDER="0" CELLPADDING="2" CELLSPACING="0" BGCOLOR="#fefefe" TARGET="_blank" HREF="http://192.168.1.100:8089/tree/gvetest/individual/X1/Joseph-Joe-BLOGGS"><TR><TD COLSPAN="2" CELLPADDING="2" BGCOLOR="#add8e6" PORT="nam" ></TD></TR><TR><TD ROWSPAN="2" CELLPADDING="1" PORT="pic" WIDTH="40" HEIGHT="40" FIXEDSIZE="true" ALIGN="CENTER"><IMG SCALE="true" SRC="/var/www/webtrees/app/../data/media/boy5.png" /></TD><TD ALIGN="LEFT" BALIGN="LEFT"  TARGET="_BLANK" CELLPADDING="4" PORT="dat"><FONT COLOR="#333333" POINT-SIZE="12">Joseph "Joe" BLOGGS</FONT><BR /><FONT COLOR="#555555" POINT-SIZE="10">* 4 May 1944 </FONT><BR /><FONT COLOR="#555555" POINT-SIZE="10">+ 7 March 2004 </FONT></TD></TR></TABLE>>];
X80 [ label=<<TABLE COLOR="#606060" BORDER="1" CELLBORDER="0" CELLPADDING="2" CELLSPACING="0" BGCOLOR="#fefefe" TARGET="_blank" HREF="http://192.168.1.100:8089/tree/gvetest/individual/X80/Steven-BLOGGS"><TR><TD COLSPAN="2" CELLPADDING="2" BGCOLOR="#add8e6" PORT="nam" ></TD></TR><TR><TD ROWSPAN="2" CELLPADDING="1" PORT="pic" WIDTH="0" HEIGHT="40" FIXEDSIZE="true"></TD><TD ALIGN="LEFT" BALIGN="LEFT"  TARGET="_BLANK" CELLPADDING="4" PORT="dat"><FONT COLOR="#333333" POINT-SIZE="12">Steven BLOGGS</FONT><BR /><FONT COLOR="#555555" POINT-SIZE="10">* &gt; March 1920 &lt; December 1926 </FONT><BR /><FONT COLOR="#555555" POINT-SIZE="10">+ interpreted 1985 </FONT></TD></TR></TABLE>>];
X82 [ label=<<TABLE COLOR="#606060" BORDER="1" CELLBORDER="0" CELLPADDING="2" CELLSPACING="0" BGCOLOR="#fefefe" TARGET="_blank" HREF="http://192.168.1.100:8089/tree/gvetest/individual/X82/Eden-Wilson"><TR><TD COLSPAN="2" CELLPADDING="2" BGCOLOR="#ffb6c1" PORT="nam" ></TD></TR><TR><TD ROWSPAN="2" CELLPADDING="1" PORT="pic" WIDTH="0" HEIGHT="40" FIXEDSIZE="true"></TD><TD ALIGN="LEFT" BALIGN="LEFT"  TARGET="_BLANK" CELLPADDING="4" PORT="dat"><FONT COLOR="#333333" POINT-SIZE="12">Eden Wilson</FONT><BR /><FONT COLOR="#555555" POINT-SIZE="10">* ~ 1 March 1922 </FONT> </TD></TR></TABLE>>];
X81 [ color="#606060",fillcolor="#ffffee", target="_blank" href="http://192.168.1.100:8089/tree/gvetest/family/X81/Steven-BLOGGS-Eden-Wilson", target="_blank",  shape=ellipse, style=filled, label=<<TABLE border="0" CELLPADDING="0" CELLSPACING="0"><TR><TD><FONT COLOR="#555555" POINT-SIZE="10">&gt; 30 December 1941<BR /></FONT></TD></TR></TABLE>>];
X80 -> X81 [color="#555555", arrowsize=0.3]
X82 -> X81 [color="#555555", arrowsize=0.3]
X81 -> X1 [color="#555555", arrowsize=0.3]
}

Which if I paste into this online viewer, it looks like this: image

Which is roughly how it's supposed to look, ignoring the weird text issue that I don't get with the 2018 version of Viz.js

Neriderc commented 10 months ago

I'll close this, I'm pretty sure I have it working fine it's just this bug: https://github.com/aduh95/viz.js/issues/21

aduh95 commented 10 months ago

Worth nothing that mdaines/vix.js is active once again, while this repo is much less. You might get better results switching back.

Neriderc commented 10 months ago

Yes, thanks, I just noticed that! However, images are not yet supported in the new version, so I'll just bide my time.