source: other-projects/nz-flag-design/trunk/design-2d/Original editor.method.ac/method-draw/src/select.js@ 29468

Last change on this file since 29468 was 29468, checked in by sjs49, 9 years ago

Initial commit for editor.method.ac for flag design

  • Property svn:executable set to *
File size: 16.3 KB
Line 
1/**
2 * Package: svedit.select
3 *
4 * Licensed under the Apache License, Version 2
5 *
6 * Copyright(c) 2010 Alexis Deveria
7 * Copyright(c) 2010 Jeff Schiller
8 */
9
10// Dependencies:
11// 1) jQuery
12// 2) browser.js
13// 3) math.js
14// 4) svgutils.js
15
16var svgedit = svgedit || {};
17
18(function() {
19
20if (!svgedit.select) {
21 svgedit.select = {};
22}
23
24var svgFactory_;
25var config_;
26var selectorManager_; // A Singleton
27
28// Class: svgedit.select.Selector
29// Private class for DOM element selection boxes
30//
31// Parameters:
32// id - integer to internally indentify the selector
33// elem - DOM element associated with this selector
34svgedit.select.Selector = function(id, elem) {
35 // this is the selector's unique number
36 this.id = id;
37
38 // this holds a reference to the element for which this selector is being used
39 this.selectedElement = elem;
40
41 // this is a flag used internally to track whether the selector is being used or not
42 this.locked = true;
43
44 // this holds a reference to the <g> element that holds all visual elements of the selector
45 this.selectorGroup = svgFactory_.createSVGElement({
46 'element': 'g',
47 'attr': {'id': ('selectorGroup' + this.id)}
48 });
49
50 // this holds a reference to the path rect
51 this.selectorRect = this.selectorGroup.appendChild(
52 svgFactory_.createSVGElement({
53 'element': 'path',
54 'attr': {
55 'id': ('selectedBox' + this.id),
56 'fill': 'none',
57 'stroke': '#4F80FF',
58 'stroke-width': '1',
59 'shape-rendering': 'crispEdges',
60 'style': 'pointer-events:none'
61 }
62 })
63 );
64
65 if (svgedit.browser.isTouch()) {
66 this.selectorRect.setAttribute("stroke-opacity", 0.3);
67 }
68
69 // this holds a reference to the grip coordinates for this selector
70 this.gripCoords = {
71 'nw': null,
72 'n' : null,
73 'ne': null,
74 'e' : null,
75 'se': null,
76 's' : null,
77 'sw': null,
78 'w' : null
79 };
80
81 this.reset(this.selectedElement);
82};
83
84
85// Function: svgedit.select.Selector.reset
86// Used to reset the id and element that the selector is attached to
87//
88// Parameters:
89// e - DOM element associated with this selector
90svgedit.select.Selector.prototype.reset = function(e) {
91 this.locked = true;
92 this.selectedElement = e;
93 this.resize();
94 this.selectorGroup.setAttribute('display', 'inline');
95};
96
97// Function: svgedit.select.Selector.updateGripCursors
98// Updates cursors for corner grips on rotation so arrows point the right way
99//
100// Parameters:
101// angle - Float indicating current rotation angle in degrees
102svgedit.select.Selector.prototype.updateGripCursors = function(angle) {
103 var dir_arr = [];
104 var steps = Math.round(angle / 45);
105 if(steps < 0) steps += 8;
106 for (var dir in selectorManager_.selectorGrips) {
107 dir_arr.push(dir);
108 }
109 while(steps > 0) {
110 dir_arr.push(dir_arr.shift());
111 steps--;
112 }
113 var i = 0;
114 for (var dir in selectorManager_.selectorGrips) {
115 selectorManager_.selectorGrips[dir].setAttribute('style', ('cursor:' + dir_arr[i] + '-resize'));
116 i++;
117 };
118};
119
120// Function: svgedit.select.Selector.showGrips
121// Show the resize grips of this selector
122//
123// Parameters:
124// show - boolean indicating whether grips should be shown or not
125svgedit.select.Selector.prototype.showGrips = function(show) {
126 // TODO: use suspendRedraw() here
127 var bShow = show ? 'inline' : 'none';
128 selectorManager_.selectorGripsGroup.setAttribute('display', bShow);
129 var elem = this.selectedElement;
130 this.hasGrips = show;
131 if(elem && show) {
132 this.selectorGroup.appendChild(selectorManager_.selectorGripsGroup);
133 this.updateGripCursors(svgedit.utilities.getRotationAngle(elem));
134 }
135};
136
137// Function: svgedit.select.Selector.resize
138// Updates the selector to match the element's size
139svgedit.select.Selector.prototype.resize = function() {
140 var selectedBox = this.selectorRect,
141 mgr = selectorManager_,
142 selectedGrips = mgr.selectorGrips,
143 selected = this.selectedElement,
144 sw = selected.getAttribute('stroke-width'),
145 current_zoom = svgFactory_.currentZoom();
146 var offset = 1/current_zoom;
147 if (selected.getAttribute('stroke') !== 'none' && !isNaN(sw)) {
148 offset += (sw/2);
149 }
150
151 var tagName = selected.tagName;
152 if (tagName === 'text') {
153 offset += 2/current_zoom;
154 }
155
156 // loop and transform our bounding box until we reach our first rotation
157 var tlist = svgedit.transformlist.getTransformList(selected);
158 var m = svgedit.math.transformListToTransform(tlist).matrix;
159
160 // This should probably be handled somewhere else, but for now
161 // it keeps the selection box correctly positioned when zoomed
162 m.e *= current_zoom;
163 m.f *= current_zoom;
164
165 var bbox = svgedit.utilities.getBBox(selected);
166 if(tagName === 'g' && !$.data(selected, 'gsvg')) {
167 // The bbox for a group does not include stroke vals, so we
168 // get the bbox based on its children.
169 var stroked_bbox = svgFactory_.getStrokedBBox(selected.childNodes);
170 if(stroked_bbox) {
171 bbox = stroked_bbox;
172 }
173 }
174
175 // apply the transforms
176 var l=bbox.x, t=bbox.y, w=bbox.width, h=bbox.height,
177 bbox = {x:l, y:t, width:w, height:h};
178
179 // we need to handle temporary transforms too
180 // if skewed, get its transformed box, then find its axis-aligned bbox
181
182 //*
183 offset *= current_zoom;
184
185 var nbox = svgedit.math.transformBox(l*current_zoom, t*current_zoom, w*current_zoom, h*current_zoom, m),
186 aabox = nbox.aabox,
187 nbax = aabox.x - offset,
188 nbay = aabox.y - offset,
189 nbaw = aabox.width + (offset * 2),
190 nbah = aabox.height + (offset * 2);
191
192 // now if the shape is rotated, un-rotate it
193 var cx = nbax + nbaw/2,
194 cy = nbay + nbah/2;
195
196 var angle = svgedit.utilities.getRotationAngle(selected);
197 if (angle) {
198 var rot = svgFactory_.svgRoot().createSVGTransform();
199 rot.setRotate(-angle,cx,cy);
200 var rotm = rot.matrix;
201 nbox.tl = svgedit.math.transformPoint(nbox.tl.x,nbox.tl.y,rotm);
202 nbox.tr = svgedit.math.transformPoint(nbox.tr.x,nbox.tr.y,rotm);
203 nbox.bl = svgedit.math.transformPoint(nbox.bl.x,nbox.bl.y,rotm);
204 nbox.br = svgedit.math.transformPoint(nbox.br.x,nbox.br.y,rotm);
205
206 // calculate the axis-aligned bbox
207 var tl = nbox.tl;
208 var minx = tl.x,
209 miny = tl.y,
210 maxx = tl.x,
211 maxy = tl.y;
212
213 var Min = Math.min, Max = Math.max;
214
215 minx = Min(minx, Min(nbox.tr.x, Min(nbox.bl.x, nbox.br.x) ) ) - offset;
216 miny = Min(miny, Min(nbox.tr.y, Min(nbox.bl.y, nbox.br.y) ) ) - offset;
217 maxx = Max(maxx, Max(nbox.tr.x, Max(nbox.bl.x, nbox.br.x) ) ) + offset;
218 maxy = Max(maxy, Max(nbox.tr.y, Max(nbox.bl.y, nbox.br.y) ) ) + offset;
219
220 nbax = minx;
221 nbay = miny;
222 nbaw = (maxx-minx);
223 nbah = (maxy-miny);
224 }
225 var sr_handle = svgFactory_.svgRoot().suspendRedraw(100);
226
227 var dstr = 'M' + nbax + ',' + nbay
228 + ' L' + (nbax+nbaw) + ',' + nbay
229 + ' ' + (nbax+nbaw) + ',' + (nbay+nbah)
230 + ' ' + nbax + ',' + (nbay+nbah) + 'z';
231 selectedBox.setAttribute('d', dstr);
232
233 var xform = angle ? 'rotate(' + [angle,cx,cy].join(',') + ')' : '';
234 this.selectorGroup.setAttribute('transform', xform);
235
236 if(svgedit.browser.isTouch()) {
237 nbax -= 15.75;
238 nbay -= 15.75;
239 }
240 else {
241 nbax -= 4;
242 nbay -= 4;
243 }
244 this.gripCoords = {
245 'nw': [nbax, nbay].map(Math.round),
246 'ne': [nbax+nbaw, nbay].map(Math.round),
247 'sw': [nbax, nbay+nbah].map(Math.round),
248 'se': [nbax+nbaw, nbay+nbah].map(Math.round),
249 'n': [nbax + (nbaw)/2, nbay].map(Math.round),
250 'w': [nbax, nbay + (nbah)/2].map(Math.round),
251 'e': [nbax + nbaw, nbay + (nbah)/2].map(Math.round),
252 's': [nbax + (nbaw)/2, nbay + nbah].map(Math.round)
253 };
254
255 for(var dir in this.gripCoords) {
256 var coords = this.gripCoords[dir];
257 selectedGrips[dir].setAttribute('x', coords[0]);
258 selectedGrips[dir].setAttribute('y', coords[1]);
259 };
260
261 this.rotateCoords = {
262 'nw': [nbax, nbay],
263 'ne': [nbax+nbaw+8, nbay],
264 'sw': [nbax, nbay+nbah+8],
265 'se': [nbax+nbaw+8, nbay+nbah+8]
266 };
267
268 for(var dir in this.rotateCoords) {
269 var coords = this.rotateCoords[dir];
270 mgr.rotateGrips[dir].setAttribute('cx', coords[0]);
271 mgr.rotateGrips[dir].setAttribute('cy', coords[1]);
272 }
273
274 svgFactory_.svgRoot().unsuspendRedraw(sr_handle);
275};
276
277
278// Class: svgedit.select.SelectorManager
279svgedit.select.SelectorManager = function() {
280 // this will hold the <g> element that contains all selector rects/grips
281 this.selectorParentGroup = null;
282
283 // this is a special rect that is used for multi-select
284 this.rubberBandBox = null;
285
286 // this will hold objects of type svgedit.select.Selector (see above)
287 this.selectors = [];
288
289 // this holds a map of SVG elements to their Selector object
290 this.selectorMap = {};
291
292 // this holds a reference to the grip elements
293 this.selectorGrips = {
294 'nw': null,
295 'n' : null,
296 'ne': null,
297 'e' : null,
298 'se': null,
299 's' : null,
300 'sw': null,
301 'w' : null
302 };
303
304 this.selectorGripsGroup = null;
305 //this.rotateGripConnector = null;
306 this.rotateGrips = {
307 'nw': null,
308 'ne': null,
309 'se': null,
310 'sw': null
311 };
312
313 this.initGroup();
314};
315
316// Function: svgedit.select.SelectorManager.initGroup
317// Resets the parent selector group element
318svgedit.select.SelectorManager.prototype.initGroup = function() {
319 // remove old selector parent group if it existed
320 if (this.selectorParentGroup && this.selectorParentGroup.parentNode) {
321 this.selectorParentGroup.parentNode.removeChild(this.selectorParentGroup);
322 }
323
324 // create parent selector group and add it to svgroot
325 this.selectorParentGroup = svgFactory_.createSVGElement({
326 'element': 'g',
327 'attr': {'id': 'selectorParentGroup'}
328 });
329 this.selectorGripsGroup = svgFactory_.createSVGElement({
330 'element': 'g',
331 'attr': {'display': 'none'}
332 });
333 this.selectorParentGroup.appendChild(this.selectorGripsGroup);
334 svgFactory_.svgRoot().appendChild(this.selectorParentGroup);
335
336 this.selectorMap = {};
337 this.selectors = [];
338 this.rubberBandBox = null;
339
340 for (var dir in this.rotateGrips) {
341 var grip = svgFactory_.createSVGElement({
342 'element': 'circle',
343 'attr': {
344 'id': 'selectorGrip_rotate_' + dir,
345 'fill': '#000',
346 'r': 8,
347 'stroke': '#000',
348 "fill-opacity": 0,
349 "stroke-opacity": 0,
350 'stroke-width': 0,
351 'style': 'cursor:url(' + config_.imgPath + 'rotate.png) 12 12, auto;'
352 }
353 })
354 $.data(grip, 'dir', dir);
355 $.data(grip, 'type', 'rotate');
356 this.rotateGrips[dir] = this.selectorGripsGroup.appendChild(grip);
357 }
358
359 // add the corner grips
360 for (var dir in this.selectorGrips) {
361 var grip = svgFactory_.createSVGElement({
362 'element': 'rect',
363 'attr': {
364 'id': ('selectorGrip_resize_' + dir),
365 'width': 8,
366 'height': 8,
367 'fill': "#4F80FF",
368 'stroke': "rgba(0,0,0,0)",
369 'stroke-width': 1,
370 'style': ('cursor:' + dir + '-resize'),
371 'pointer-events': 'all'
372 }
373 });
374 if (svgedit.browser.isTouch()) {
375
376 grip.setAttribute("width", 30.5)
377 grip.setAttribute("height", 30.5)
378 grip.setAttribute("fill-opacity", 0.3)
379 }
380
381 $.data(grip, 'dir', dir);
382 $.data(grip, 'type', 'resize');
383 this.selectorGrips[dir] = this.selectorGripsGroup.appendChild(grip);
384 }
385
386 if($('#canvasBackground').length) return;
387
388 var dims = config_.dimensions;
389 var canvasbg = svgFactory_.createSVGElement({
390 'element': 'svg',
391 'attr': {
392 'id': 'canvasBackground',
393 'width': dims[0],
394 'height': dims[1],
395 'x': 0,
396 'y': 0,
397 'overflow': (svgedit.browser.isWebkit() ? 'none' : 'visible'), // Chrome 7 has a problem with this when zooming out
398 'style': 'pointer-events:none'
399 }
400 });
401
402 var defs = svgFactory_.createSVGElement({
403 'element': 'defs',
404 'attr': {
405 'id': 'placeholder_defs'
406 }
407 })
408
409 var pattern = svgFactory_.createSVGElement({
410 'element': 'pattern',
411 'attr': {
412 'id': 'checkerPattern',
413 'patternUnits': 'userSpaceOnUse',
414 'x': 0,
415 'y': 0,
416 'width': 20,
417 'height': 20,
418 'viewBox': '0 0 10 10'
419 }
420 })
421
422 var pattern_bg = svgFactory_.createSVGElement({
423 'element': 'rect',
424 'attr': {
425 'x': 0,
426 'y': 0,
427 'width': 10,
428 'height': 10,
429 'fill': "#fff"
430 }
431 })
432
433 var pattern_square1 = svgFactory_.createSVGElement({
434 'element': 'rect',
435 'attr': {
436 'x': 0,
437 'y': 0,
438 'width': 5,
439 'height': 5,
440 'fill': "#eee"
441 }
442 })
443
444 var pattern_square2 = svgFactory_.createSVGElement({
445 'element': 'rect',
446 'attr': {
447 'x': 5,
448 'y': 5,
449 'width': 5,
450 'height': 5,
451 'fill': "#eee"
452 }
453 })
454
455 var rect = svgFactory_.createSVGElement({
456 'element': 'rect',
457 'attr': {
458 'width': '100%',
459 'height': '100%',
460 'x': 0,
461 'y': 0,
462 'stroke-width': 1,
463 'stroke': '#000',
464 'fill': 'url(#checkerPattern)',
465 'style': 'pointer-events:none'
466 }
467 });
468
469 // Both Firefox and WebKit are too slow with this filter region (especially at higher
470 // zoom levels) and Opera has at least one bug
471// if (!svgedit.browser.isOpera()) rect.setAttribute('filter', 'url(#canvashadow)');
472 canvasbg.appendChild(defs);
473 defs.appendChild(pattern);
474 pattern.appendChild(pattern_bg);
475 pattern.appendChild(pattern_square1);
476 pattern.appendChild(pattern_square2);
477 canvasbg.appendChild(rect);
478
479 svgFactory_.svgRoot().insertBefore(canvasbg, svgFactory_.svgContent());
480};
481
482// Function: svgedit.select.SelectorManager.requestSelector
483// Returns the selector based on the given element
484//
485// Parameters:
486// elem - DOM element to get the selector for
487svgedit.select.SelectorManager.prototype.requestSelector = function(elem) {
488 if (elem == null) return null;
489 var N = this.selectors.length;
490 // If we've already acquired one for this element, return it.
491 if (typeof(this.selectorMap[elem.id]) == 'object') {
492 this.selectorMap[elem.id].locked = true;
493 return this.selectorMap[elem.id];
494 }
495 for (var i = 0; i < N; ++i) {
496 if (this.selectors[i] && !this.selectors[i].locked) {
497 this.selectors[i].locked = true;
498 this.selectors[i].reset(elem);
499 this.selectorMap[elem.id] = this.selectors[i];
500 return this.selectors[i];
501 }
502 }
503 // if we reached here, no available selectors were found, we create one
504 this.selectors[N] = new svgedit.select.Selector(N, elem);
505 this.selectorParentGroup.appendChild(this.selectors[N].selectorGroup);
506 this.selectorMap[elem.id] = this.selectors[N];
507 return this.selectors[N];
508};
509
510// Function: svgedit.select.SelectorManager.releaseSelector
511// Removes the selector of the given element (hides selection box)
512//
513// Parameters:
514// elem - DOM element to remove the selector for
515svgedit.select.SelectorManager.prototype.releaseSelector = function(elem) {
516 if (elem == null) return;
517 var N = this.selectors.length,
518 sel = this.selectorMap[elem.id];
519 for (var i = 0; i < N; ++i) {
520 if (this.selectors[i] && this.selectors[i] == sel) {
521 if (sel.locked == false) {
522 // TODO(codedread): Ensure this exists in this module.
523 console.log('WARNING! selector was released but was already unlocked');
524 }
525 delete this.selectorMap[elem.id];
526 sel.locked = false;
527 sel.selectedElement = null;
528 sel.showGrips(false);
529
530 // remove from DOM and store reference in JS but only if it exists in the DOM
531 try {
532 sel.selectorGroup.setAttribute('display', 'none');
533 } catch(e) { }
534
535 break;
536 }
537 }
538};
539
540// Function: svgedit.select.SelectorManager.getRubberBandBox
541// Returns the rubberBandBox DOM element. This is the rectangle drawn by the user for selecting/zooming
542svgedit.select.SelectorManager.prototype.getRubberBandBox = function() {
543 if (!this.rubberBandBox) {
544 this.rubberBandBox = this.selectorParentGroup.appendChild(
545 svgFactory_.createSVGElement({
546 'element': 'rect',
547 'attr': {
548 'id': 'selectorRubberBand',
549 'fill': 'none',
550 'stroke': '#666',
551 'stroke-width': 1,
552 'stroke-dasharray': '3,2',
553 'display': 'none',
554 'style': 'pointer-events:none'
555 }
556 })
557 );
558 }
559 return this.rubberBandBox;
560};
561
562
563/**
564 * Interface: svgedit.select.SVGFactory
565 * An object that creates SVG elements for the canvas.
566 *
567 * interface svgedit.select.SVGFactory {
568 * SVGElement createSVGElement(jsonMap);
569 * SVGSVGElement svgRoot();
570 * SVGSVGElement svgContent();
571 *
572 * Number currentZoom();
573 * Object getStrokedBBox(Element[]); // TODO(codedread): Remove when getStrokedBBox() has been put into svgutils.js
574 * }
575 */
576
577/**
578 * Function: svgedit.select.init()
579 * Initializes this module.
580 *
581 * Parameters:
582 * config - an object containing configurable parameters (imgPath)
583 * svgFactory - an object implementing the SVGFactory interface (see above).
584 */
585svgedit.select.init = function(config, svgFactory) {
586 config_ = config;
587 svgFactory_ = svgFactory;
588 selectorManager_ = new svgedit.select.SelectorManager();
589 //for hovering elements
590 svgFactory_.createSVGElement({
591 'element': 'g',
592 'attr': {
593 'id': 'hover_group'
594 }
595 })
596};
597
598/**
599 * Function: svgedit.select.getSelectorManager
600 *
601 * Returns:
602 * The SelectorManager instance.
603 */
604svgedit.select.getSelectorManager = function() {
605 return selectorManager_;
606};
607
608})();
Note: See TracBrowser for help on using the repository browser.