All files / src/lib/tinymce/plugins/graph2d tinymceGraph2dOpenUrlPlugin.js

94.04% Statements 79/84
84.5% Branches 60/71
100% Functions 11/11
95.12% Lines 78/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230                                            51x       3x 3x               3x           51x 51x 51x     10x 10x 10x                 31x 31x 31x 9x       7x 7x             7x                 7x     51x 51x 51x 51x 51x   51x     31x 1x 1x   1x 1x           30x       51x 51x                                 51x       32x 1x 1x   31x 1x   31x 31x 32x 32x 8x 8x       31x 31x                         18x 18x   18x 3x 3x       3x     15x 11x 11x 11x 9x 4x 4x 4x 4x 2x 2x 2x 2x 1x   1x         1x 1x     2x   1x     1x     5x     11x 11x     4x 2x             51x                    
/**
 * Fork of graph2d-react `tinymce/graph2d-plugin.js` (keep in sync on package upgrades).
 * Adds handling for { mceAction: 'close' } so GraphEditorStandalone "Close" dismisses the URL dialog.
 *
 * TinyMCE 6 plugin: Insert / edit Graph 2D drawings via a URL dialog.
 *
 * Setup:
 * 1. Install: npm install tinymce
 * 2. Load this script after TinyMCE (e.g. as a plugin script or import).
 * 3. Add to editor init: plugins: '... graph2d', toolbar: '... graph2d'
 * 4. Set graph editor URL: graph2d_url: 'https://yoursite.com/graph-editor'
 *    Optional: graph2d_size_percent (e.g. 90 = 90% of viewport), or graph2d_width, graph2d_height (dialog size in px).
 *
 * The page at graph2d_url must:
 * - Post { mceAction: 'graph2d-ready' } when loaded (so we can send initial data).
 * - Accept postMessage { type: 'graph2d-init', data: encodedString } to import existing graph.
 * - Post { mceAction: 'graph2d-insert', data: encodedString } when user clicks Insert, then { mceAction: 'close' }.
 *
 * Using in another project: You must host the graph editor page in your app and set graph2d_url
 * to its full URL (e.g. window.location.origin + '/graph-editor'). Otherwise the dialog will open blank.
 * See docs/TINYMCE_GRAPH2D_PLUGIN.md §9.
 */
(function () {
  'use strict';
 
  function graph2dPluginDebug() {
    try {
      return typeof window !== 'undefined' &&
        (window.__GRAPH2D_DEBUG__ === true ||
          (window.localStorage && window.localStorage.getItem('graph2dDebug') === '1'));
    } catch (e) {
      return false;
    }
  }
  function graph2dPluginLog() {
    Iif (graph2dPluginDebug()) {
      var a = ['[graph2d plugin]'].concat(Array.prototype.slice.call(arguments));
      console.log.apply(console, a);
    }
  }
 
  var PLACEHOLDER_CLASS = 'graph2d-embed';
  var DATA_ATTR = 'data-graph2d';
  var PLACEHOLDER_LABEL = '[2D Graph]';
 
  function escapeHtml(s) {
    Iif (s == null) return '';
    var str = String(s);
    return str
      .replace(/&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }
 
  function getSelectedGraphData(editor) {
    var node = editor.selection.getNode();
    var el = editor.dom.getParent(node, '[' + DATA_ATTR + ']');
    if (!el) return null;
    return editor.dom.getAttrib(el, DATA_ATTR) || null;
  }
 
  function insertPlaceholder(editor, encodedData, imageUrl) {
    var escaped = escapeHtml(encodedData);
    var inner = imageUrl
      ? '<img src="' + escapeHtml(imageUrl) + '" alt="2D Graph" style="max-width:100%;height:auto;display:inline-block;vertical-align:middle;" />'
      : PLACEHOLDER_LABEL;
    // Wrap the non-editable span in a paragraph so TinyMCE's built-in
    // alignment formats (which operate on block elements like <p>) can
    // align the whole graph block left/center/right/justify.
    var html =
      '<p><span class="' +
      PLACEHOLDER_CLASS +
      '" contenteditable="false" ' +
      DATA_ATTR +
      '="' +
      escaped +
      '">' +
      inner +
      '</span></p>';
    editor.insertContent(html);
  }
 
  tinymce.PluginManager.add('graph2d', function (editor, url) {
    var graphEditorUrl = editor.getParam('graph2d_url', '');
    var sizePercent = editor.getParam('graph2d_size_percent', 0);
    var fallbackWidth = editor.getParam('graph2d_width', 980);
    var fallbackHeight = editor.getParam('graph2d_height', 580);
 
    var editBookmark = null;
 
    function getDialogSize() {
      if (sizePercent > 0 && sizePercent <= 100) {
        var win = editor.getDoc().defaultView || (typeof window !== 'undefined' ? window : null);
        Eif (win) {
          // Use top window so 90% is of the full viewport, not the editor iframe
          var viewport = win.top && win.top.innerWidth ? win.top : win;
          return {
            width: Math.round((sizePercent / 100) * viewport.innerWidth),
            height: Math.round((sizePercent / 100) * viewport.innerHeight),
          };
        }
      }
      return { width: fallbackWidth, height: fallbackHeight };
    }
 
    // Toolbar icon (SVG Repo mixer; viewBox preserved, rendered at 24×24).
    Eif (editor.ui.registry.addIcon) {
      editor.ui.registry.addIcon(
        'graph2d',
        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 511.999 511.999" width="24" height="24" xml:space="preserve">' +
          '<path style="fill:#2C3E50;" d="M420.448,374.704H91.552c-12.273,0-22.223-9.95-22.223-22.223s9.95-22.223,22.223-22.223h328.896c12.273,0,22.223,9.95,22.223,22.223S432.722,374.704,420.448,374.704z"/>' +
          '<path style="fill:#22313F;" d="M420.448,330.259H256v44.445h164.448c12.273,0,22.223-9.95,22.223-22.223S432.722,330.259,420.448,330.259z"/>' +
          '<path style="fill:#2C3E50;" d="M392.151,497.29L284.805,201.45c-10.014-27.599,31.749-42.799,41.78-15.159l107.346,295.842C443.949,509.745,402.206,525.003,392.151,497.29z"/>' +
          '<path style="fill:#FFDA79;" d="M279.148,120.645c-13.836-9.48-32.447-9.479-46.315,0.009c-14.723,10.074-34.771-0.498-34.771-18.341V57.942C198.064,25.993,224.055,0,256.004,0c31.943,0,57.929,25.993,57.929,57.942v44.371C313.933,120.278,293.777,130.666,279.148,120.645z"/>' +
          '<path style="fill:#FFD155;" d="M256.004,0c-0.001,0-0.003,0-0.004,0v113.537c8.117-0.001,16.23,2.367,23.149,7.108c14.68,10.057,34.784-0.41,34.784-18.332V57.942C313.933,25.993,287.947,0,256.004,0z"/>' +
          '<path style="fill:#36495E;" d="M78.07,482.131L185.416,186.29c10.017-27.602,51.807-12.476,41.78,15.159L119.85,497.29C109.779,525.043,68.012,509.85,78.07,482.131z"/>' +
          '<path style="fill:#FFDA79;" d="M256,417.173c-12.273,0-22.223-9.95-22.223-22.223v-84.94c0-12.273,9.95-22.223,22.223-22.223s22.223,9.95,22.223,22.223v84.94C278.222,407.225,268.274,417.173,256,417.173z"/>' +
          '<path style="fill:#65C6BB;" d="M256.004,240.168c-84.211,0-117.351-108.955-48.262-156.199c28.878-19.76,67.672-19.757,96.526,0.01C373.522,131.337,340.016,240.168,256.004,240.168z"/>' +
          '<path style="fill:#FFD155;" d="M256,287.788v129.385c12.273,0,22.223-9.95,22.223-22.223v-84.94C278.222,297.738,268.274,287.788,256,287.788z"/>' +
          '<path style="fill:#20B8AE;" d="M304.269,83.981C289.837,74.093,272.92,69.151,256,69.153v171.015c0.001,0,0.003,0,0.004,0C339.907,240.168,373.617,131.403,304.269,83.981z"/>' +
          '</svg>'
      );
    }
 
    editor.ui.registry.addButton('graph2d', {
      icon: 'graph2d',
      tooltip: 'Insert 2D graph',
      onAction: function () {
        if (!graphEditorUrl) {
          editor.windowManager.alert('Graph 2D: Please set graph2d_url in the editor config.');
          return;
        }
        if (graphEditorUrl.indexOf('http://') !== 0 && graphEditorUrl.indexOf('https://') !== 0 && graphEditorUrl.indexOf('/') !== 0) {
          console.warn('Graph 2D: graph2d_url should be a full URL (http/https) or path starting with /. Otherwise the dialog may open blank. See docs/TINYMCE_GRAPH2D_PLUGIN.md §9.');
        }
        var initialData = getSelectedGraphData(editor);
        var isEdit = initialData != null && initialData !== '';
        editBookmark = null;
        if (isEdit) {
          try {
            editBookmark = editor.selection.getBookmark(2, true);
          } catch (e) { }
        }
 
        var size = getDialogSize();
        editor.windowManager.openUrl({
          title: isEdit ? 'Edit 2D graph' : 'Insert 2D graph',
          url: graphEditorUrl,
          width: size.width,
          height: size.height,
          buttons: [
            {
              type: 'cancel',
              text: 'Cancel',
              name: 'cancel',
            },
          ],
          onMessage: function (api, details) {
            var msg = details && details.mceAction != null ? details : (details || {});
            var action = msg.mceAction;
 
            if (action === 'graph2d-ready') {
              graph2dPluginLog('iframe graph2d-ready → sending graph2d-init', initialData ? { edit: true, len: String(initialData).length } : { edit: false });
              api.sendMessage({
                type: 'graph2d-init',
                data: initialData || null,
              });
              return;
            }
 
            if (action === 'graph2d-insert') {
              var data = msg.data;
              var imageUrl = msg.image;
              if (data != null && data !== '') {
                if (editBookmark) {
                  try {
                    editor.selection.moveToBookmark(editBookmark);
                    var el = editor.dom.getParent(editor.selection.getNode(), '[' + DATA_ATTR + ']');
                    if (el) {
                      editor.dom.setAttrib(el, DATA_ATTR, data);
                      Eif (imageUrl) {
                        var img = el.querySelector('img');
                        if (img) {
                          img.setAttribute('src', imageUrl);
                        } else {
                          var newImg = editor.dom.create('img', {
                            src: imageUrl,
                            alt: '2D Graph',
                            style: 'max-width:100%;height:auto;display:inline-block;vertical-align:middle;'
                          });
                          el.innerHTML = '';
                          el.appendChild(newImg);
                        }
                      }
                      editBookmark = null;
                    } else {
                      insertPlaceholder(editor, data, imageUrl);
                    }
                  } catch (e) {
                    insertPlaceholder(editor, data, imageUrl);
                  }
                } else {
                  insertPlaceholder(editor, data, imageUrl);
                }
              }
              api.close();
              return;
            }
 
            if (action === 'close') {
              api.close();
            }
          },
        });
      },
    });
 
    return {
      getMetadata: function () {
        return {
          name: 'Graph 2D',
          url: 'https://github.com/your-org/graph2d-react',
        };
      },
    };
  });
})();