Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

8.2 KB
Raw Blame
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>CAD SVG Editor</title>
  <base href="/vendor/svgedit/" />
  <link rel="stylesheet" href="/vendor/svgedit/svgedit.css" />
  <style>
    /*
     * Lighter work area and rulers to sit with the rest of the app. The toolbars
     * stay mid-grey: svgedit's tool icons are drawn in white.
     */
    :root {
      --main-bg-color: #868e92;
      --icon-bg-color: #868e92;
      --canvas-bg-color: #e9edf0;
      --ruler-color: #dfe4e8;
      --input-color: #f4f6f8;
    }
    html, body {
      margin: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      background: #e9edf0;
    }
    #svgedit-container {
      width: 100vw;
      height: 100vh;
    }
  </style>
</head>
<body>
  <div id="svgedit-container"></div>

  <script type="module">
    import Editor from "/vendor/svgedit/Editor.js";

    const container = document.getElementById("svgedit-container");
    const editor = new Editor(container);
    const EMPTY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1000" viewBox="0 0 1600 1000"></svg>`;
    let editorReady = false;
    let pendingSvgLoad = "";

    editor.setConfig({
      allowInitialUserOverride: true,
      extensions: [],
      noDefaultExtensions: false,
      userExtensions: [],
      no_save_warning: true,
      noStorageOnLoad: true,
      imgPath: "/vendor/svgedit/images",
      extPath: "/vendor/svgedit/extensions"
    });

    // svgedit's storage extension asks (in English) whether to keep preferences
    // and content locally the first time it opens. CanvasAnvil keeps the plan
    // itself, so answer "preferences only" up front instead of interrupting.
    if (!/(?:^|;\s*)svgeditstore=/.test(document.cookie)) {
      document.cookie = "svgeditstore=prefsOnly; path=/; max-age=31536000";
    }

    editor.init();

    const origin = window.location.origin;

    const post = (payload) => {
      if (!window.parent || window.parent === window) return;
      window.parent.postMessage(payload, origin);
    };

    const normalizeIncomingSvg = (value) => {
      const decodeBasicHtmlEntities = (text) =>
        String(text || "")
          .replace(/&lt;/gi, "<")
          .replace(/&gt;/gi, ">")
          .replace(/&quot;/gi, '"')
          .replace(/&#39;|&apos;/gi, "'")
          .replace(/&amp;/gi, "&");

      const original = String(value || "").trim();
      const raw = !/<svg[\s/>]/i.test(original) && /&lt;\s*svg[\s\S]*&gt;/i.test(original)
        ? decodeBasicHtmlEntities(original).trim()
        : original;
      if (!raw) return "";
      const start = raw.search(/<svg[\s/>]/i);
      if (start < 0) return "";

      let text = raw.slice(start).trim();
      const lower = text.toLowerCase();
      const end = lower.lastIndexOf("</svg>");
      if (end >= 0) {
        text = text.slice(0, end + "</svg>".length).trim();
      }

      try {
        const parser = new DOMParser();
        const doc = parser.parseFromString(text, "image/svg+xml");
        if (doc.querySelector("parsererror")) return text;

        const svgEl = doc.documentElement?.nodeName?.toLowerCase() === "svg"
          ? doc.documentElement
          : doc.querySelector("svg");
        if (!svgEl) return text;

        if (!svgEl.getAttribute("xmlns")) {
          svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg");
        }
        if (!svgEl.getAttribute("xmlns:xlink")) {
          svgEl.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
        }

        const width = svgEl.getAttribute("width");
        const height = svgEl.getAttribute("height");
        const viewBox = svgEl.getAttribute("viewBox");
        if (!width || !height) {
          const parts = String(viewBox || "")
            .trim()
            .split(/[\s,]+/)
            .map((n) => Number(n));
          if (parts.length === 4 && Number.isFinite(parts[2]) && Number.isFinite(parts[3]) && parts[2] > 0 && parts[3] > 0) {
            if (!width) svgEl.setAttribute("width", String(parts[2]));
            if (!height) svgEl.setAttribute("height", String(parts[3]));
          } else {
            if (!width) svgEl.setAttribute("width", "1600");
            if (!height) svgEl.setAttribute("height", "1000");
          }
        }

        if (!viewBox) {
          const w = Number(svgEl.getAttribute("width"));
          const h = Number(svgEl.getAttribute("height"));
          if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {
            svgEl.setAttribute("viewBox", `0 0 ${w} ${h}`);
          }
        }

        const xml = new XMLSerializer().serializeToString(svgEl);
        return String(xml || "").trim() || text;
      } catch {
        return text;
      }
    };

    const getCurrentSvg = () => {
      const raw = String(editor?.svgCanvas?.getSvgString?.() || "").trim();
      return /^<svg[\s/>]/i.test(raw) ? raw : "";
    };

    // Loading straight into the canvas skips the editor's own resize, so the
    // drawing would sit at 100% in a corner; resize the work area and zoom the
    // whole sheet into view instead.
    const fitToView = () => {
      try {
        editor.updateCanvas?.(true);
        editor.zoomChanged?.(window, "canvas");
      } catch {
        // An editor that cannot zoom still shows the drawing, just not framed.
      }
    };

    const loadSvg = async (svg) => {
      const text = normalizeIncomingSvg(svg);
      if (!text) return false;

      try {
        const ok = editor?.svgCanvas?.setSvgString?.(text);
        if (ok !== false) {
          fitToView();
          return true;
        }
      } catch {
      }

      try {
        const ok = editor?.svgCanvas?.importSvgString?.(text);
        if (ok !== false) {
          fitToView();
          return true;
        }
      } catch {
      }

      try {
        await editor.loadFromString(text, { noAlert: true });
        fitToView();
        return true;
      } catch (e) {
        console.error("Failed to load SVG", e);
        return false;
      }
    };

    const clearSvg = async () => {
      const ok = await loadSvg(EMPTY_SVG);
      if (ok) return;
      try {
        if (typeof editor?.svgCanvas?.clear === "function") {
          editor.svgCanvas.clear();
        }
      } catch (e) {
        console.error("Failed to clear SVG canvas directly", e);
      }
    };

    const applyPendingLoad = async () => {
      if (!editorReady) return;
      const next = String(pendingSvgLoad || "").trim();
      if (!next) return;
      pendingSvgLoad = "";
      await loadSvg(next);
    };

    editor.ready(async () => {
      editorReady = true;
      // Always start from a known blank canvas; prevents stale local restore content.
      await clearSvg();
      await applyPendingLoad();
      post({ type: "cad_svg_editor_ready" });
    });

    window.addEventListener("message", async (event) => {
      if (event.origin !== origin) return;
      const data = event.data;
      if (!data || typeof data !== "object") return;
      const type = String(data.type || "");

      if (type === "cad_svg_editor_load") {
        const normalized = normalizeIncomingSvg(data.svg);
        if (!normalized) {
          post({
            type: "cad_svg_editor_load_result",
            ok: false,
            reason: "empty_or_invalid_svg"
          });
          return;
        }
        if (!editorReady) {
          pendingSvgLoad = normalized;
          post({
            type: "cad_svg_editor_load_result",
            ok: true,
            queued: true
          });
          return;
        }
        const ok = await loadSvg(normalized);
        post({
          type: "cad_svg_editor_load_result",
          ok: !!ok,
          reason: ok ? "" : "editor_rejected_svg"
        });
        return;
      }

      if (type === "cad_svg_editor_clear") {
        if (!editorReady) {
          pendingSvgLoad = EMPTY_SVG;
          return;
        }
        await clearSvg();
        return;
      }

      if (type === "cad_svg_editor_export_request") {
        const requestId = String(data.requestId || "");
        post({
          type: "cad_svg_editor_export_response",
          requestId,
          svg: getCurrentSvg(),
        });
      }
    });
  </script>
</body>
</html>