forked from nytimes/svg-crowbar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svg-crowbar.js
481 lines (411 loc) · 18.3 KB
/
svg-crowbar.js
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**
* Javascript module pattern: tp wrap a set of variables and functions together in a single scope.
* used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.
* expose certain properties and function s as public and can also restrict the scope of some within the object itself, making them private.
*
* NodeList: collections of nodes, usually returned by properties such as Node.childNodes and methods such as document.querySelectorAll().
*
* Node: is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similary and often interchangeably.
* as an abstract class, there is no such thing as a plain Node object.
* all objects that implement Node functionality are based on one of its subclasses.
* most notable are Document, Element, and DocumentFragment.
*/
/**
* @link https://albeertito7.github.io
* @since 1.0.0
* @module crowbar
* @author albert <[email protected]>
* @author_uri https://albeertito7.github.io
* @license MIT
* @description SVG Crowbar
*/
// Js module dependencies
const crowbar_deps = {
_window: window,
_document: document
};
const crowbar = (function (_deps) {
// static properties
const _doctype = '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
_prefix = {
svg: 'http://www.w3.org/2000/svg',
xlink: 'http://www.w3.org/1999/xlink',
xmlns: 'http://www.w3.org/2000/xmlns/'
};
window.URL = (window.URL || window.webkitURL);
/**
* To get the base SVG Empty Styles from the page browser.
*/
function _getEmtpySvgStyle () {
// create element specifying a namespace URI
// namespaceURI => a string to associate with the element
const empty_svg = window.document.createElementNS(_prefix.svg, 'svg');
// retrieve the Svg Style
return window.getComputedStyle(empty_svg);
}
// Document: represents any web page loaded in the browser and serves as an entry point into the web page's content, which is the DOM tree.
// describes the common properties and methods for any kind of document.
// depending on the document's type (e.g. HTML, XML, SVG, ...)
/**
* The JS module bootstrap method.
*/
function _initialize () {
const documents = [window.document];
const iframes = document.querySelectorAll('iframe'); // getting all iframes
const objects = document.querySelectorAll('object'); // getting all objects
const emptySvgDeclarationComputed = _getEmtpySvgStyle(); // retrieve the Svg base Style
// get documents
// get sources from documents
let SVGSources = getSources(window.document, emptySvgDeclarationComputed);
// retrieving the required documents
SVGSources = [...iframes, ...objects].reduce(function (filtered, element) {
if (element.contentDocument) {
const newSources = getSources(element.contentDocument, emptySvgDeclarationComputed);
filtered = filtered.concat(newSources);
}
return filtered;
}, SVGSources);
// halting case
if (!SVGSources.length) {
window.alert('The SVG Crowbar couldn’t find any SVG nodes.');
return;
}
console.log(SVGSources);
_createPopover(SVGSources);
}
function _createShowDiv () {
}
/**
*
*/
function _createPopover (sources) {
_cleanup();
sources.forEach(function (s1) {
sources.forEach(function (s2) {
if (s1 !== s2) {
if ((Math.abs(s1.top - s2.top) < 38) && (Math.abs(s1.left - s2.left) < 38)) {
s2.top += 38;
s2.left += 38;
}
}
});
});
const buttonsContainer = document.createElement('div'); // <div> <!-- main container -->
buttonsContainer.setAttribute('class', 'svg-crowbar');
document.body.appendChild(buttonsContainer);
// positioning
buttonsContainer.classList.add('crowbar-container');
buttonsContainer.style['z-index'] = 999999;// 1e7;
buttonsContainer.style.position = 'absolute';
buttonsContainer.style.top = 0;
buttonsContainer.style.left = 0;
const background = document.createElement('div'); // <div> <!-- opacity background -->
background.setAttribute('class', 'svg-crowbar');
document.body.appendChild(background);
background.classList.add('crowbar-background');
background.style.background = 'rgba(255, 255, 255, 0.7)';
background.style['z-index'] = 999998;
background.style.position = 'fixed';
background.style.left = 0;
background.style.top = 0;
background.style.width = '100%';
background.style.height = '100%';
const showDiv = document.createElement('div'); // <div> <!-- main container -->
showDiv.setAttribute('class', 'svg-crowbar');
showDiv.setAttribute('id', 'showDiv');
document.body.appendChild(showDiv);
const showDivHeader = document.createElement('div'); // <div> <!-- header -->
showDivHeader.setAttribute('class', 'showDiv-header');
showDiv.appendChild(showDivHeader);
showDivHeader.style.background = 'black';
showDivHeader.style.color = 'white';
showDivHeader.style['font-size'] = '14px';
showDivHeader.style['text-align'] = 'center';
const showText = document.createTextNode('SVG Visualizer'); // <div> <!-- SVG Visualizer container -->
const showCrossBtn = document.createElement('button');
showCrossBtn.setAttribute('class', 'crowbar-show-cross');
showCrossBtn.style.color = 'white';
showCrossBtn.style.background = 'transparent';
showCrossBtn.style['font-weight'] = 'bold';
showCrossBtn.style.border = 'none';
showCrossBtn.style.outline = 'none';
showCrossBtn.style.float = 'right';
showCrossBtn.style.margin = '0px';
showCrossBtn.style.cursor = 'pointer';
showCrossBtn.style['text-align'] = 'center';
showCrossBtn.innerHTML = '✖'; // X
showDivHeader.appendChild(showText);
showDivHeader.appendChild(showCrossBtn);
showCrossBtn.onclick = function (e) {
e.target.parentElement.parentElement.style.display = 'none';
};
const showDivBody = document.createElement('div'); // <div> <!-- Visualizer body container -->
showDivBody.setAttribute('class', 'showDiv-body');
showDivBody.style.padding = '5px';
showDiv.appendChild(showDivBody);
// positioning
showDiv.classList.add('crowbar-show-div');
showDiv.style['z-index'] = 9999999;// 1e7;
showDiv.style.position = 'absolute';
showDiv.style.width = '300px';
showDiv.style['min-width'] = '300px';
showDiv.style['min-height'] = '300px';
showDiv.style.cursor = 'move';
showDiv.style.border = '4px solid black';
// showDiv.style["background"] = "white";
showDiv.style.setProperty('background', 'rgba(255, 255, 255, 0.9)', 'important');
showDiv.style.top = 0;
showDiv.style.left = 0;
showDiv.style.display = 'none';
_dragElement(showDiv);
sources.forEach(function (d, i) {
const buttonWrapper = document.createElement('div'); // <div> <!-- action buttons wrapper -->
buttonWrapper.setAttribute('class', 'svg-crowbar');
buttonsContainer.appendChild(buttonWrapper);
buttonWrapper.classList.add('crowbar-btn-wrapper');
buttonWrapper.style.position = 'absolute';
buttonWrapper.style.top = (d.top) + 'px';
buttonWrapper.style.left = (d.left) + 'px';
buttonWrapper.style.padding = '4px';
buttonWrapper.style['border-radius'] = '3px';
buttonWrapper.style.setProperty('color', 'white', 'important');
buttonWrapper.style.setProperty('text-align', 'center', 'important');
buttonWrapper.style['font-family'] = '\'Helvetica Neue\'';
buttonWrapper.style.setProperty('background', 'rgba(0, 0, 0, 0.8)', 'important');
buttonWrapper.style['box-shadow'] = '0px 4px 18px rgba(0, 0, 0, 0.4)';
buttonWrapper.style.cursor = 'move';
// buttonWrapper.textContent = "SVG #" + i + ": " + (d.id ? "#" + d.id : "") + (d.class ? "." + d.class : "");
const buttonHeader = document.createElement('div'); // <div> <!-- button container header -->
buttonHeader.setAttribute('class', 'showDiv-header');
buttonWrapper.appendChild(buttonHeader);
buttonHeader.style.color = 'white';
buttonHeader.style['font-size'] = '14px';
buttonHeader.style['text-align'] = 'left';
const buttonHeaderText = document.createTextNode('SVG #' + i + ': ' + (d.id ? '#' + d.id : '') + (d.class ? '.' + d.class : '')); // <div> <!-- Header text -->
const buttonCrossBtn = document.createElement('button');
buttonCrossBtn.setAttribute('class', 'crowbar-show-cross');
buttonCrossBtn.style.color = 'white';
buttonCrossBtn.style.background = 'transparent';
buttonCrossBtn.style['font-weight'] = 'bold';
buttonCrossBtn.style.border = 'none';
buttonCrossBtn.style.outline = 'none';
buttonCrossBtn.style.float = 'right';
buttonCrossBtn.style.margin = '0px';
buttonCrossBtn.style.cursor = 'pointer';
buttonCrossBtn.style['text-align'] = 'center';
buttonCrossBtn.innerHTML = '✖'; // X
buttonHeader.appendChild(buttonHeaderText);
buttonHeader.appendChild(buttonCrossBtn);
const button = document.createElement('button'); // <button>
button.setAttribute('class', 'crowbar-download');
buttonWrapper.appendChild(button);
button.setAttribute('data-source-id', i);
button.style.width = '130px';
button.style['font-size'] = '12px';
button.style['line-height'] = '1.4em';
button.style.margin = '5px 0 0 0';
button.style.setProperty('color', 'black', 'important');
button.style.cursor = 'pointer';
button.style.setProperty('background', 'rgba(255, 255, 255, 0.9)', 'important');
button.textContent = 'Download';
const cross = document.createElement('button'); // <button>
cross.setAttribute('class', 'crowbar-cross');
buttonWrapper.appendChild(cross);
// cross.style["width"] = "20px";
cross.style['font-size'] = '14px';
cross.style.margin = '5px 0 0 0';
cross.style.setProperty('color', 'black', 'important');
cross.style.cursor = 'pointer';
cross.style.padding = '5px';
cross.style.setProperty('background', 'rgba(255, 255, 255, 0.9)', 'important');
cross.innerHTML = '✖'; // X
const show = document.createElement('button'); // <button>
show.setAttribute('class', 'crowbar-show');
buttonWrapper.appendChild(show);
show.style.width = '40px';
show.style['font-size'] = '12px';
show.style['line-height'] = '1.4em';
show.style.margin = '5px 0 0 0';
show.style.setProperty('color', 'black', 'important');
show.style.cursor = 'pointer';
show.style.setProperty('background', 'rgba(255, 255, 255, 0.9)', 'important');
show.textContent = 'Show';
_dragElement(buttonWrapper);
button.onclick = function () {
_download(d);
};
cross.onclick = function (e) {
e.target.parentElement.remove();
};
show.onclick = function () {
const showDiv = document.querySelector('#showDiv');
const showDivBody = document.querySelector('#showDiv > .showDiv-body');
showDivBody.innerHTML = '';
showDivBody.appendChild(d.element);
showDiv.style.display = 'block';
// console.log(d.element);
};
});
}
/**
* Removes the DOM .svg-crowbar already created elements, so that
* a new set can be raised.
*/
function _cleanup () {
const crowbarElements = document.querySelectorAll('.svg-crowbar');
[...crowbarElements].forEach((element) => {
element.remove();
});
}
/**
*
*/
function getSources (document, emptySvgDeclarationComputed) {
const svgInfo = [];
const svgs = document.querySelectorAll('svg'); // returns a static NodeList representing a list of the document's elements that match the specified group of selectors
[...svgs].forEach((svg) => {
svg.setAttribute('version', '1.1');
// removing attributes so they aren't doubled up
svg.removeAttribute('xmlns');
svg.removeAttribute('xlink');
// these are needed for the svg
if (!svg.hasAttributeNS(_prefix.xmlns, 'xmlns')) {
svg.setAttributeNS(_prefix.xmlns, 'xmlns', _prefix.svg);
}
if (!svg.hasAttributeNS(_prefix.xmlns, 'xmlns:xlink')) {
svg.setAttributeNS(_prefix.xmlns, 'xmlns:xlink', _prefix.xlink);
}
setInlineStyles(svg, emptySvgDeclarationComputed);
const source = (new XMLSerializer()).serializeToString(svg);
rect = svg.getBoundingClientRect(); // returns a DOMRect object providing information about the size of an element and its position relative to the viewport
svgInfo.push({
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
id: svg.getAttribute('id'),
class: svg.getAttribute('class'),
name: svg.getAttribute('name'),
childElementCount: svg.childElementCount,
source: [_doctype + source],
element: svg.cloneNode(true)
});
});
return svgInfo;
}
/**
* Downloads a specific svg source file.
*/
function _download (source) {
let filename = 'untitled';
if (source.name) {
filename = source.name;
} else if (source.id) {
filename = source.id;
} else if (source.class) {
filename = source.class;
} else if (window.document.title) {
filename = window.document.title.replace(/[^a-z0-9]/gi, '-').toLowerCase();
}
const url = window.URL.createObjectURL(new Blob(source.source, { type: 'text\/xml' }));
const a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('class', 'svg-crowbar');
a.setAttribute('download', filename + '.svg');
a.setAttribute('href', url);
a.style.display = 'none';
a.click();
setTimeout(function () {
window.URL.revokeObjectURL(url);
}, 10);
}
/**
*
*/
function setInlineStyles (svg, emptySvgDeclarationComputed) {
/**
*
*/
function explicitlySetStyle (element) {
const cSSStyleDeclarationComputed = getComputedStyle(element);
let i, len, key, value;
let computedStyleStr = '';
for (i = 0, len = cSSStyleDeclarationComputed.length; i < len; i++) {
key = cSSStyleDeclarationComputed[i];
value = cSSStyleDeclarationComputed.getPropertyValue(key);
if (value !== emptySvgDeclarationComputed.getPropertyValue(key)) {
computedStyleStr += key + ':' + value + ';';
}
}
element.setAttribute('style', computedStyleStr);
}
/**
*
*/
function traverse (obj) {
const tree = [];
tree.push(obj);
visit(obj);
function visit (node) {
if (node && node.hasChildNodes()) {
let child = node.firstChild;
while (child) {
if (child.nodeType === 1 && child.nodeName != 'SCRIPT') {
tree.push(child);
visit(child);
}
child = child.nextSibling;
}
}
}
return tree;
}
// hardcode computed css styles inside svg
const allElements = traverse(svg);
let i = allElements.length;
while (i--) {
explicitlySetStyle(allElements[i]);
}
}
/**
* Enables dragging for the element specified.
*/
function _dragElement (element) {
let pos1 = 0; let pos2 = 0; let pos3 = 0; let pos4 = 0;
// move the DIV from anywhere inside it
element.onmousedown = dragMouseDown;
function dragMouseDown (e) {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup
pos3 = e.clientX;
pos4 = e.clientY;
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves
document.onmousemove = elementDrag;
}
function elementDrag (e) {
e = e || window.event;
e.preventDefault();
// calculate the new cursor position
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
// set the element's new position
element.style.top = (element.offsetTop - pos2) + 'px';
element.style.left = (element.offsetLeft - pos1) + 'px';
}
function closeDragElement () {
// stop moving when mouse button is released
document.onmouseup = null;
document.onmousemove = null;
}
}
// public domain
return {
initialize: _initialize
};
}(crowbar_deps));
// see you later, baby
crowbar.initialize();