xyc
2025-02-21 664db98c9e8595ce4dd636a27f480e3a08b81ff5
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/* globals jQuery */
/**
 * ext-polygon.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 *
 */
export default {
  name: 'polygon',
  async init (S) {
    const svgEditor = this;
    const $ = jQuery;
    const svgCanvas = svgEditor.canvas;
    const {importLocale} = S, // {svgcontent}
      // addElem = svgCanvas.addSVGElementFromJson,
      editingitex = false;
    const strings = await importLocale();
    let selElems,
      // svgdoc = S.svgroot.parentNode.ownerDocument,
      // newFOG, newFOGParent, newDef, newImageName, newMaskID, modeChangeG,
      // edg = 0,
      // undoCommand = 'Not image';
      started, newFO;
 
    // const ccZoom;
    // const wEl, hEl;
    // const wOffset, hOffset;
    // const ccRBG;
    // const ccOpacity;
    // const brushW, brushH;
 
    // const ccDebug = document.getElementById('debugpanel');
 
    /* const properlySourceSizeTextArea = function(){
     // TODO: remove magic numbers here and get values from CSS
     const height = $('#svg_source_container').height() - 80;
     $('#svg_source_textarea').css('height', height);
     }; */
    function showPanel (on) {
      let fcRules = $('#fc_rules');
      if (!fcRules.length) {
        fcRules = $('<style id="fc_rules"></style>').appendTo('head');
      }
      fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
      $('#polygon_panel').toggle(on);
    }
 
    /*
    function toggleSourceButtons(on){
      $('#tool_source_save, #tool_source_cancel').toggle(!on);
      $('#polygon_save, #polygon_cancel').toggle(on);
    }
    */
 
    function setAttr (attr, val) {
      svgCanvas.changeSelectedAttribute(attr, val);
      svgCanvas.call('changed', selElems);
    }
 
    function cot (n) {
      return 1 / Math.tan(n);
    }
 
    function sec (n) {
      return 1 / Math.cos(n);
    }
 
    /**
    * Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
    * This function sets the content of of the currently-selected foreignObject element,
    *   based on the itex contained in string.
    * @param {string} tex The itex text.
    * @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
    */
    /*
    function setItexString(tex) {
      const mathns = 'http://www.w3.org/1998/Math/MathML',
        xmlnsns = 'http://www.w3.org/2000/xmlns/',
        ajaxEndpoint = '../../itex';
      const elt = selElems[0];
      try {
        const math = svgdoc.createElementNS(mathns, 'math');
        math.setAttributeNS(xmlnsns, 'xmlns', mathns);
        math.setAttribute('display', 'inline');
        const semantics = document.createElementNS(mathns, 'semantics');
        const annotation = document.createElementNS(mathns, 'annotation');
        annotation.setAttribute('encoding', 'application/x-tex');
        annotation.textContent = tex;
        const mrow = document.createElementNS(mathns, 'mrow');
        semantics.append(mrow, annotation);
        math.append(semantics);
        // make an AJAX request to the server, to get the MathML
        $.post(ajaxEndpoint, {tex, display: 'inline'}, function(data){
          const children = data.documentElement.childNodes;
          while (children.length > 0) {
             mrow.append(svgdoc.adoptNode(children[0], true));
          }
          svgCanvas.sanitizeSvg(math);
          svgCanvas.call('changed', [elt]);
        });
        elt.firstChild.replaceWith(math);
        svgCanvas.call('changed', [elt]);
        svgCanvas.clearSelection();
      } catch(e) {
        console.log(e);
        return false;
      }
 
      return true;
    }
    */
    const buttons = [{
      id: 'tool_polygon',
      icon: svgEditor.curConfig.extIconsPath + 'polygon.png',
      type: 'mode',
      position: 11,
      events: {
        click () {
          svgCanvas.setMode('polygon');
          showPanel(true);
        }
      }
    }];
    const contextTools = [{
      type: 'input',
      panel: 'polygon_panel',
      id: 'polySides',
      size: 3,
      defval: 5,
      events: {
        change () {
          setAttr('sides', this.value);
        }
      }
    }];
    return {
      name: strings.name,
      svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg',
      buttons: strings.buttons.map((button, i) => {
        return Object.assign(buttons[i], button);
      }),
      context_tools: strings.contextTools.map((contextTool, i) => {
        return Object.assign(contextTools[i], contextTool);
      }),
 
      callback () {
        $('#polygon_panel').hide();
 
        const endChanges = function () {
        };
 
        // TODO: Needs to be done after orig icon loads
        setTimeout(function () {
          // Create source save/cancel buttons
          /* const save = */ $('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
            if (!editingitex) {
              return;
            }
            // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
            /*
            if (!setItexString($('#svg_source_textarea').val())) {
              $.confirm('Errors found. Revert to original?', function (ok) {
                if (!ok) {
                  return false;
                }
                endChanges();
              });
            } else { */
            endChanges();
            // }
            // setSelectMode();
          });
 
          /* const cancel = */ $('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
            endChanges();
          });
        }, 3000);
      },
      mouseDown (opts) {
        // const e = opts.event;
        const rgb = svgCanvas.getColor('fill');
        // const ccRgbEl = rgb.substring(1, rgb.length);
        const sRgb = svgCanvas.getColor('stroke');
        // ccSRgbEl = sRgb.substring(1, rgb.length);
        const sWidth = svgCanvas.getStrokeWidth();
 
        if (svgCanvas.getMode() === 'polygon') {
          started = true;
 
          newFO = svgCanvas.addSVGElementFromJson({
            element: 'polygon',
            attr: {
              cx: opts.start_x,
              cy: opts.start_y,
              id: svgCanvas.getNextId(),
              shape: 'regularPoly',
              sides: document.getElementById('polySides').value,
              orient: 'x',
              edge: 0,
              fill: rgb,
              strokecolor: sRgb,
              strokeWidth: sWidth
            }
          });
 
          return {
            started: true
          };
        }
      },
      mouseMove (opts) {
        if (!started) {
          return;
        }
        if (svgCanvas.getMode() === 'polygon') {
          // const e = opts.event;
          const c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);
          let x = opts.mouse_x;
          let y = opts.mouse_y;
          const {cx, cy, fill, strokecolor, strokeWidth, sides} = c, // {orient} = c,
            edg = (Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy))) / 1.5;
          newFO.setAttribute('edge', edg);
 
          const inradius = (edg / 2) * cot(Math.PI / sides);
          const circumradius = inradius * sec(Math.PI / sides);
          let points = '';
          for (let s = 0; sides >= s; s++) {
            const angle = 2.0 * Math.PI * s / sides;
            x = (circumradius * Math.cos(angle)) + cx;
            y = (circumradius * Math.sin(angle)) + cy;
 
            points += x + ',' + y + ' ';
          }
 
          // const poly = newFO.createElementNS(NS.SVG, 'polygon');
          newFO.setAttribute('points', points);
          newFO.setAttribute('fill', fill);
          newFO.setAttribute('stroke', strokecolor);
          newFO.setAttribute('stroke-width', strokeWidth);
          // newFO.setAttribute('transform', 'rotate(-90)');
          // const shape = newFO.getAttribute('shape');
          // newFO.append(poly);
          // DrawPoly(cx, cy, sides, edg, orient);
          return {
            started: true
          };
        }
      },
 
      mouseUp (opts) {
        if (svgCanvas.getMode() === 'polygon') {
          const attrs = $(newFO).attr('edge');
          const keep = (attrs.edge !== '0');
          // svgCanvas.addToSelection([newFO], true);
          return {
            keep,
            element: newFO
          };
        }
      },
      selectedChanged (opts) {
        // Use this to update the current selected elements
        selElems = opts.elems;
 
        let i = selElems.length;
        while (i--) {
          const elem = selElems[i];
          if (elem && elem.getAttribute('shape') === 'regularPoly') {
            if (opts.selectedElement && !opts.multiselected) {
              $('#polySides').val(elem.getAttribute('sides'));
 
              showPanel(true);
            } else {
              showPanel(false);
            }
          } else {
            showPanel(false);
          }
        }
      },
      elementChanged (opts) {
        // const elem = opts.elems[0];
      }
    };
  }
};