- Linting: ESLint (or ignore) JavaScript files; unfinished: editor/jgraduate and editor/extensions folders, editor/ (root), test/ (root) HTML

- Fix: An apparent bug in jquery.svgicons.js whereby a variable `holder` was declared in too nested of a scope
- Fix: `addBezierCurve` in canvg.js had undeclared `i`
- Fix: Undeclared variable in opera widget
- Fix: Screencast `showNotes`
This commit is contained in:
Brett Zamir
2018-05-13 18:47:00 +08:00
parent 820964334c
commit 5894398c36
16 changed files with 6846 additions and 6996 deletions

View File

@@ -1,3 +1,13 @@
node_modules node_modules
editor/jspdf/jspdf.min.js editor/jspdf/jspdf.min.js
editor/jspdf/underscore-min.js editor/jspdf/underscore-min.js
jgraduate/jpicker.min.js
jgraduate/jquery.jgraduate.js
jquery-ui
jquerybbq
js-hotkeys
spinbtn/JQuerySpinBtn.min.js
test/qunit
test/sinon
wave/json2.js

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,25 @@
/*jslint vars: true*/ /* eslint-disable no-var */
/** /**
* A class to parse color values * A class to parse color values
* @author Stoyan Stefanov <sstoo@gmail.com> * @author Stoyan Stefanov <sstoo@gmail.com>
* @link http://www.phpied.com/rgb-color-parser-in-javascript/ * @link http://www.phpied.com/rgb-color-parser-in-javascript/
* @license Use it if you like it * @license Use it if you like it
*/ */
function RGBColor(color_string) { 'use strict'; function RGBColor (colorString) { // eslint-disable-line no-unused-vars
'use strict';
this.ok = false; this.ok = false;
// strip any leading # // strip any leading #
if (color_string.charAt(0) === '#') { // remove # if any if (colorString.charAt(0) === '#') { // remove # if any
color_string = color_string.substr(1,6); colorString = colorString.substr(1, 6);
} }
color_string = color_string.replace(/ /g,''); colorString = colorString.replace(/ /g, '');
color_string = color_string.toLowerCase(); colorString = colorString.toLowerCase();
// before getting into regexps, try simple matches // before getting into regexps, try simple matches
// and overwrite the input // and overwrite the input
var simple_colors = { var simpleColors = {
aliceblue: 'f0f8ff', aliceblue: 'f0f8ff',
antiquewhite: 'faebd7', antiquewhite: 'faebd7',
aqua: '00ffff', aqua: '00ffff',
@@ -75,8 +76,8 @@ function RGBColor(color_string) { 'use strict';
greenyellow: 'adff2f', greenyellow: 'adff2f',
honeydew: 'f0fff0', honeydew: 'f0fff0',
hotpink: 'ff69b4', hotpink: 'ff69b4',
indianred : 'cd5c5c', indianred: 'cd5c5c',
indigo : '4b0082', indigo: '4b0082',
ivory: 'fffff0', ivory: 'fffff0',
khaki: 'f0e68c', khaki: 'f0e68c',
lavender: 'e6e6fa', lavender: 'e6e6fa',
@@ -164,21 +165,21 @@ function RGBColor(color_string) { 'use strict';
yellowgreen: '9acd32' yellowgreen: '9acd32'
}; };
var key; var key;
for (key in simple_colors) { for (key in simpleColors) {
if (simple_colors.hasOwnProperty(key)) { if (simpleColors.hasOwnProperty(key)) {
if (color_string == key) { if (colorString === key) {
color_string = simple_colors[key]; colorString = simpleColors[key];
} }
} }
} }
// emd of simple type-in colors // emd of simple type-in colors
// array of color definition objects // array of color definition objects
var color_defs = [ var colorDefs = [
{ {
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function (bits){ process: function (bits) {
return [ return [
parseInt(bits[1], 10), parseInt(bits[1], 10),
parseInt(bits[2], 10), parseInt(bits[2], 10),
@@ -189,7 +190,7 @@ function RGBColor(color_string) { 'use strict';
{ {
re: /^(\w{2})(\w{2})(\w{2})$/, re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'], example: ['#00ff00', '336699'],
process: function (bits){ process: function (bits) {
return [ return [
parseInt(bits[1], 16), parseInt(bits[1], 16),
parseInt(bits[2], 16), parseInt(bits[2], 16),
@@ -200,7 +201,7 @@ function RGBColor(color_string) { 'use strict';
{ {
re: /^(\w{1})(\w{1})(\w{1})$/, re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'], example: ['#fb0', 'f0f'],
process: function (bits){ process: function (bits) {
return [ return [
parseInt(bits[1] + bits[1], 16), parseInt(bits[1] + bits[1], 16),
parseInt(bits[2] + bits[2], 16), parseInt(bits[2] + bits[2], 16),
@@ -212,10 +213,10 @@ function RGBColor(color_string) { 'use strict';
var i; var i;
// search through the definitions to find a match // search through the definitions to find a match
for (i = 0; i < color_defs.length; i++) { for (i = 0; i < colorDefs.length; i++) {
var re = color_defs[i].re; var re = colorDefs[i].re;
var processor = color_defs[i].process; var processor = colorDefs[i].process;
var bits = re.exec(color_string); var bits = re.exec(colorString);
if (bits) { if (bits) {
var channels = processor(bits); var channels = processor(bits);
this.r = channels[0]; this.r = channels[0];
@@ -223,7 +224,6 @@ function RGBColor(color_string) { 'use strict';
this.b = channels[2]; this.b = channels[2];
this.ok = true; this.ok = true;
} }
} }
// validate/cleanup values // validate/cleanup values
@@ -239,9 +239,9 @@ function RGBColor(color_string) { 'use strict';
var r = this.r.toString(16); var r = this.r.toString(16);
var g = this.g.toString(16); var g = this.g.toString(16);
var b = this.b.toString(16); var b = this.b.toString(16);
if (r.length === 1) {r = '0' + r;} if (r.length === 1) { r = '0' + r; }
if (g.length === 1) {g = '0' + g;} if (g.length === 1) { g = '0' + g; }
if (b.length === 1) {b = '0' + b;} if (b.length === 1) { b = '0' + b; }
return '#' + r + g + b; return '#' + r + g + b;
}; };
@@ -250,16 +250,16 @@ function RGBColor(color_string) { 'use strict';
var i, j; var i, j;
var examples = []; var examples = [];
// add regexps // add regexps
for (i = 0; i < color_defs.length; i++) { for (i = 0; i < colorDefs.length; i++) {
var example = color_defs[i].example; var example = colorDefs[i].example;
for (j = 0; j < example.length; j++) { for (j = 0; j < example.length; j++) {
examples[examples.length] = example[j]; examples[examples.length] = example[j];
} }
} }
// add type-in colors // add type-in colors
var sc; var sc;
for (sc in simple_colors) { for (sc in simpleColors) {
if (simple_colors.hasOwnProperty(sc)) { if (simpleColors.hasOwnProperty(sc)) {
examples[examples.length] = sc; examples[examples.length] = sc;
} }
} }
@@ -268,27 +268,24 @@ function RGBColor(color_string) { 'use strict';
xml.setAttribute('id', 'rgbcolor-examples'); xml.setAttribute('id', 'rgbcolor-examples');
for (i = 0; i < examples.length; i++) { for (i = 0; i < examples.length; i++) {
try { try {
var list_item = document.createElement('li'); var listItem = document.createElement('li');
var list_color = new RGBColor(examples[i]); var listColor = new RGBColor(examples[i]);
var example_div = document.createElement('div'); var exampleDiv = document.createElement('div');
example_div.style.cssText = exampleDiv.style.cssText =
'margin: 3px; ' 'margin: 3px; ' +
+ 'border: 1px solid black; ' 'border: 1px solid black; ' +
+ 'background:' + list_color.toHex() + '; ' 'background:' + listColor.toHex() + '; ' +
+ 'color:' + list_color.toHex() 'color:' + listColor.toHex()
; ;
example_div.appendChild(document.createTextNode('test')); exampleDiv.appendChild(document.createTextNode('test'));
var list_item_value = document.createTextNode( var listItemValue = document.createTextNode(
' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex() ' ' + examples[i] + ' -> ' + listColor.toRGB() + ' -> ' + listColor.toHex()
); );
list_item.appendChild(example_div); listItem.appendChild(exampleDiv);
list_item.appendChild(list_item_value); listItem.appendChild(listItemValue);
xml.appendChild(list_item); xml.appendChild(listItem);
} catch (e) {}
} catch(e){}
} }
return xml; return xml;
}; };
} }

View File

@@ -1,3 +1,5 @@
/* eslint-disable no-var */
/* globals jQuery, $, svgedit */
// jQuery Context Menu Plugin // jQuery Context Menu Plugin
// //
// Version 1.01 // Version 1.01
@@ -13,22 +15,23 @@
// This plugin is dual-licensed under the GNU General Public License // This plugin is dual-licensed under the GNU General Public License
// and the MIT License and is copyright A Beautiful Site, LLC. // and the MIT License and is copyright A Beautiful Site, LLC.
// //
if(jQuery)( function() { if (jQuery) {
(function () {
var win = $(window); var win = $(window);
var doc = $(document); var doc = $(document);
$.extend($.fn, { $.extend($.fn, {
contextMenu: function(o, callback) { contextMenu: function (o, callback) {
// Defaults // Defaults
if( o.menu == undefined ) return false; if (o.menu === undefined) return false;
if( o.inSpeed == undefined ) o.inSpeed = 150; if (o.inSpeed === undefined) o.inSpeed = 150;
if( o.outSpeed == undefined ) o.outSpeed = 75; if (o.outSpeed === undefined) o.outSpeed = 75;
// 0 needs to be -1 for expected results (no fade) // 0 needs to be -1 for expected results (no fade)
if( o.inSpeed == 0 ) o.inSpeed = -1; if (o.inSpeed === 0) o.inSpeed = -1;
if( o.outSpeed == 0 ) o.outSpeed = -1; if (o.outSpeed === 0) o.outSpeed = -1;
// Loop each context menu // Loop each context menu
$(this).each( function() { $(this).each(function () {
var el = $(this); var el = $(this);
var offset = $(el).offset(); var offset = $(el).offset();
@@ -37,56 +40,57 @@ if(jQuery)( function() {
// Add contextMenu class // Add contextMenu class
menu.addClass('contextMenu'); menu.addClass('contextMenu');
// Simulate a true right click // Simulate a true right click
$(this).bind( "mousedown", function(e) { $(this).bind('mousedown', function (e) {
var evt = e; var evt = e;
$(this).mouseup( function(e) { $(this).mouseup(function (e) {
var srcElement = $(this); var srcElement = $(this);
srcElement.unbind('mouseup'); srcElement.unbind('mouseup');
if( evt.button === 2 || o.allowLeft || (evt.ctrlKey && svgedit.browser.isMac()) ) { if (evt.button === 2 || o.allowLeft ||
(evt.ctrlKey && svgedit.browser.isMac())) {
e.stopPropagation(); e.stopPropagation();
// Hide context menus that may be showing // Hide context menus that may be showing
$(".contextMenu").hide(); $('.contextMenu').hide();
// Get this context menu // Get this context menu
if( el.hasClass('disabled') ) return false; if (el.hasClass('disabled')) return false;
// Detect mouse position // Detect mouse position
var d = {}, x = e.pageX, y = e.pageY; var x = e.pageX, y = e.pageY;
var x_off = win.width() - menu.width(), var xOff = win.width() - menu.width(),
y_off = win.height() - menu.height(); yOff = win.height() - menu.height();
if(x > x_off - 15) x = x_off-15; if (x > xOff - 15) x = xOff - 15;
if(y > y_off - 30) y = y_off-30; // 30 is needed to prevent scrollbars in FF if (y > yOff - 30) y = yOff - 30; // 30 is needed to prevent scrollbars in FF
// Show the menu // Show the menu
doc.unbind('click'); doc.unbind('click');
menu.css({ top: y, left: x }).fadeIn(o.inSpeed); menu.css({ top: y, left: x }).fadeIn(o.inSpeed);
// Hover events // Hover events
menu.find('A').mouseover( function() { menu.find('A').mouseover(function () {
menu.find('LI.hover').removeClass('hover'); menu.find('LI.hover').removeClass('hover');
$(this).parent().addClass('hover'); $(this).parent().addClass('hover');
}).mouseout( function() { }).mouseout(function () {
menu.find('LI.hover').removeClass('hover'); menu.find('LI.hover').removeClass('hover');
}); });
// Keyboard // Keyboard
doc.keypress( function(e) { doc.keypress(function (e) {
switch( e.keyCode ) { switch (e.keyCode) {
case 38: // up case 38: // up
if( !menu.find('LI.hover').length ) { if (!menu.find('LI.hover').length) {
menu.find('LI:last').addClass('hover'); menu.find('LI:last').addClass('hover');
} else { } else {
menu.find('LI.hover').removeClass('hover').prevAll('LI:not(.disabled)').eq(0).addClass('hover'); menu.find('LI.hover').removeClass('hover').prevAll('LI:not(.disabled)').eq(0).addClass('hover');
if( !menu.find('LI.hover').length ) menu.find('LI:last').addClass('hover'); if (!menu.find('LI.hover').length) menu.find('LI:last').addClass('hover');
} }
break; break;
case 40: // down case 40: // down
if( menu.find('LI.hover').length == 0 ) { if (menu.find('LI.hover').length === 0) {
menu.find('LI:first').addClass('hover'); menu.find('LI:first').addClass('hover');
} else { } else {
menu.find('LI.hover').removeClass('hover').nextAll('LI:not(.disabled)').eq(0).addClass('hover'); menu.find('LI.hover').removeClass('hover').nextAll('LI:not(.disabled)').eq(0).addClass('hover');
if( !menu.find('LI.hover').length ) menu.find('LI:first').addClass('hover'); if (!menu.find('LI.hover').length) menu.find('LI:first').addClass('hover');
} }
break; break;
case 13: // enter case 13: // enter
@@ -94,23 +98,23 @@ if(jQuery)( function() {
break; break;
case 27: // esc case 27: // esc
doc.trigger('click'); doc.trigger('click');
break break;
} }
}); });
// When items are selected // When items are selected
menu.find('A').unbind('mouseup'); menu.find('A').unbind('mouseup');
menu.find('LI:not(.disabled) A').mouseup( function() { menu.find('LI:not(.disabled) A').mouseup(function () {
doc.unbind('click').unbind('keypress'); doc.unbind('click').unbind('keypress');
$(".contextMenu").hide(); $('.contextMenu').hide();
// Callback // Callback
if( callback ) callback( $(this).attr('href').substr(1), $(srcElement), {x: x - offset.left, y: y - offset.top, docX: x, docY: y} ); if (callback) callback($(this).attr('href').substr(1), $(srcElement), {x: x - offset.left, y: y - offset.top, docX: x, docY: y});
return false; return false;
}); });
// Hide bindings // Hide bindings
setTimeout( function() { // Delay for Mozilla setTimeout(function () { // Delay for Mozilla
doc.click( function() { doc.click(function () {
doc.unbind('click').unbind('keypress'); doc.unbind('click').unbind('keypress');
menu.fadeOut(o.outSpeed); menu.fadeOut(o.outSpeed);
return false; return false;
@@ -121,83 +125,81 @@ if(jQuery)( function() {
}); });
// Disable text selection // Disable text selection
if( $.browser.mozilla ) { if ($.browser.mozilla) {
$('#' + o.menu).each( function() { $(this).css({ 'MozUserSelect' : 'none' }); }); $('#' + o.menu).each(function () { $(this).css({'MozUserSelect': 'none'}); });
} else if( $.browser.msie ) { } else if ($.browser.msie) {
$('#' + o.menu).each( function() { $(this).bind('selectstart.disableTextSelect', function() { return false; }); }); $('#' + o.menu).each(function () { $(this).bind('selectstart.disableTextSelect', function () { return false; }); });
} else { } else {
$('#' + o.menu).each(function() { $(this).bind('mousedown.disableTextSelect', function() { return false; }); }); $('#' + o.menu).each(function () { $(this).bind('mousedown.disableTextSelect', function () { return false; }); });
} }
// Disable browser context menu (requires both selectors to work in IE/Safari + FF/Chrome) // Disable browser context menu (requires both selectors to work in IE/Safari + FF/Chrome)
$(el).add($('UL.contextMenu')).bind('contextmenu', function() { return false; }); $(el).add($('UL.contextMenu')).bind('contextmenu', function () { return false; });
}); });
return $(this); return $(this);
}, },
// Disable context menu items on the fly // Disable context menu items on the fly
disableContextMenuItems: function(o) { disableContextMenuItems: function (o) {
if( o == undefined ) { if (o === undefined) {
// Disable all // Disable all
$(this).find('LI').addClass('disabled'); $(this).find('LI').addClass('disabled');
return( $(this) ); return $(this);
} }
$(this).each( function() { $(this).each(function () {
if( o != undefined ) { if (o !== undefined) {
var d = o.split(','); var d = o.split(',');
for( var i = 0; i < d.length; i++ ) { for (var i = 0; i < d.length; i++) {
$(this).find('A[href="' + d[i] + '"]').parent().addClass('disabled'); $(this).find('A[href="' + d[i] + '"]').parent().addClass('disabled');
} }
} }
}); });
return( $(this) ); return $(this);
}, },
// Enable context menu items on the fly // Enable context menu items on the fly
enableContextMenuItems: function(o) { enableContextMenuItems: function (o) {
if( o == undefined ) { if (o === undefined) {
// Enable all // Enable all
$(this).find('LI.disabled').removeClass('disabled'); $(this).find('LI.disabled').removeClass('disabled');
return( $(this) ); return $(this);
} }
$(this).each( function() { $(this).each(function () {
if( o != undefined ) { if (o !== undefined) {
var d = o.split(','); var d = o.split(',');
for( var i = 0; i < d.length; i++ ) { for (var i = 0; i < d.length; i++) {
$(this).find('A[href="' + d[i] + '"]').parent().removeClass('disabled'); $(this).find('A[href="' + d[i] + '"]').parent().removeClass('disabled');
} }
} }
}); });
return( $(this) ); return $(this);
}, },
// Disable context menu(s) // Disable context menu(s)
disableContextMenu: function() { disableContextMenu: function () {
$(this).each( function() { $(this).each(function () {
$(this).addClass('disabled'); $(this).addClass('disabled');
}); });
return( $(this) ); return $(this);
}, },
// Enable context menu(s) // Enable context menu(s)
enableContextMenu: function() { enableContextMenu: function () {
$(this).each( function() { $(this).each(function () {
$(this).removeClass('disabled'); $(this).removeClass('disabled');
}); });
return( $(this) ); return $(this);
}, },
// Destroy context menu(s) // Destroy context menu(s)
destroyContextMenu: function() { destroyContextMenu: function () {
// Destroy specified context menus // Destroy specified context menus
$(this).each( function() { $(this).each(function () {
// Disable action // Disable action
$(this).unbind('mousedown').unbind('mouseup'); $(this).unbind('mousedown').unbind('mouseup');
}); });
return( $(this) ); return $(this);
} }
}); });
})(jQuery); })(jQuery);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
/*globals $, svgEditor*/ /* eslint-disable no-var */
/*jslint vars: true, eqeq: true*/ /* globals $, svgEditor */
/* SpinButton control /* SpinButton control
* *
* Adds bells and whistles to any ordinary textbox to * Adds bells and whistles to any ordinary textbox to
@@ -65,11 +65,12 @@
}); });
*/ */
$.fn.SpinButton = function(cfg) { 'use strict'; $.fn.SpinButton = function (cfg) {
function coord(el,prop) { 'use strict';
function coord (el, prop) {
var c = el[prop], b = document.body; var c = el[prop], b = document.body;
while ((el = el.offsetParent) && (el != b)) { while ((el = el.offsetParent) && (el !== b)) {
if (!$.browser.msie || (el.currentStyle.position !== 'relative')) { if (!$.browser.msie || (el.currentStyle.position !== 'relative')) {
c += el[prop]; c += el[prop];
} }
@@ -78,15 +79,14 @@ $.fn.SpinButton = function(cfg) { 'use strict';
return c; return c;
} }
return this.each(function(){ return this.each(function () {
this.repeating = false; this.repeating = false;
// Apply specified options or defaults: // Apply specified options or defaults:
// (Ought to refactor this some day to use $.extend() instead) // (Ought to refactor this some day to use $.extend() instead)
this.spinCfg = { this.spinCfg = {
//min: cfg && cfg.min ? Number(cfg.min) : null, // min: cfg && cfg.min ? Number(cfg.min) : null,
//max: cfg && cfg.max ? Number(cfg.max) : null, // max: cfg && cfg.max ? Number(cfg.max) : null,
min: cfg && !isNaN(parseFloat(cfg.min)) ? Number(cfg.min) : null, // Fixes bug with min:0 min: cfg && !isNaN(parseFloat(cfg.min)) ? Number(cfg.min) : null, // Fixes bug with min:0
max: cfg && !isNaN(parseFloat(cfg.max)) ? Number(cfg.max) : null, max: cfg && !isNaN(parseFloat(cfg.max)) ? Number(cfg.max) : null,
step: cfg && cfg.step ? Number(cfg.step) : 1, step: cfg && cfg.step ? Number(cfg.step) : 1,
@@ -105,42 +105,43 @@ $.fn.SpinButton = function(cfg) { 'use strict';
}; };
// if a smallStep isn't supplied, use half the regular step // if a smallStep isn't supplied, use half the regular step
this.spinCfg.smallStep = cfg && cfg.smallStep ? cfg.smallStep : this.spinCfg.step/2; this.spinCfg.smallStep = cfg && cfg.smallStep ? cfg.smallStep : this.spinCfg.step / 2;
this.adjustValue = function(i){ this.adjustValue = function (i) {
var v; var v;
if(isNaN(this.value)) { if (isNaN(this.value)) {
v = this.spinCfg.reset; v = this.spinCfg.reset;
} else if($.isFunction(this.spinCfg.stepfunc)) { } else if ($.isFunction(this.spinCfg.stepfunc)) {
v = this.spinCfg.stepfunc(this, i); v = this.spinCfg.stepfunc(this, i);
} else { } else {
// weirdest javascript bug ever: 5.1 + 0.1 = 5.199999999 // weirdest javascript bug ever: 5.1 + 0.1 = 5.199999999
v = Number((Number(this.value) + Number(i)).toFixed(5)); v = Number((Number(this.value) + Number(i)).toFixed(5));
} }
if (this.spinCfg.min !== null) {v = Math.max(v, this.spinCfg.min);} if (this.spinCfg.min !== null) { v = Math.max(v, this.spinCfg.min); }
if (this.spinCfg.max !== null) {v = Math.min(v, this.spinCfg.max);} if (this.spinCfg.max !== null) { v = Math.min(v, this.spinCfg.max); }
this.value = v; this.value = v;
if ($.isFunction(this.spinCfg.callback)) {this.spinCfg.callback(this);} if ($.isFunction(this.spinCfg.callback)) { this.spinCfg.callback(this); }
}; };
$(this) $(this)
.addClass(cfg && cfg.spinClass ? cfg.spinClass : 'spin-button') .addClass(cfg && cfg.spinClass ? cfg.spinClass : 'spin-button')
.mousemove(function(e){ .mousemove(function (e) {
// Determine which button mouse is over, or not (spin direction): // Determine which button mouse is over, or not (spin direction):
var x = e.pageX || e.x; var x = e.pageX || e.x;
var y = e.pageY || e.y; var y = e.pageY || e.y;
var el = e.target || e.srcElement; var el = e.target || e.srcElement;
var scale = svgEditor.tool_scale || 1; var scale = svgEditor.tool_scale || 1;
var height = $(el).height()/2; var height = $(el).height() / 2;
var direction = var direction =
(x > coord(el,'offsetLeft') + el.offsetWidth*scale - this.spinCfg._btn_width) (x > coord(el, 'offsetLeft') +
? ((y < coord(el,'offsetTop') + height*scale) ? 1 : -1) : 0; el.offsetWidth * scale - this.spinCfg._btn_width)
? ((y < coord(el, 'offsetTop') + height * scale) ? 1 : -1) : 0;
if (direction !== this.spinCfg._direction) { if (direction !== this.spinCfg._direction) {
// Style up/down buttons: // Style up/down buttons:
switch(direction){ switch (direction) {
case 1: // Up arrow: case 1: // Up arrow:
$(this).removeClass(this.spinCfg.downClass).addClass(this.spinCfg.upClass); $(this).removeClass(this.spinCfg.downClass).addClass(this.spinCfg.upClass);
break; break;
@@ -156,7 +157,7 @@ $.fn.SpinButton = function(cfg) { 'use strict';
} }
}) })
.mouseout(function(){ .mouseout(function () {
// Reset up/down buttons to their normal appearance when mouse moves away: // Reset up/down buttons to their normal appearance when mouse moves away:
$(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass); $(this).removeClass(this.spinCfg.upClass).removeClass(this.spinCfg.downClass);
this.spinCfg._direction = null; this.spinCfg._direction = null;
@@ -164,20 +165,20 @@ $.fn.SpinButton = function(cfg) { 'use strict';
window.clearTimeout(this.spinCfg._delay); window.clearTimeout(this.spinCfg._delay);
}) })
.mousedown(function(e){ .mousedown(function (e) {
if (e.button === 0 && this.spinCfg._direction != 0) { if (e.button === 0 && this.spinCfg._direction !== 0) {
// Respond to click on one of the buttons: // Respond to click on one of the buttons:
var self = this; var self = this;
var stepSize = e.shiftKey ? self.spinCfg.smallStep : self.spinCfg.step; var stepSize = e.shiftKey ? self.spinCfg.smallStep : self.spinCfg.step;
var adjust = function() { var adjust = function () {
self.adjustValue(self.spinCfg._direction * stepSize); self.adjustValue(self.spinCfg._direction * stepSize);
}; };
adjust(); adjust();
// Initial delay before repeating adjustment // Initial delay before repeating adjustment
self.spinCfg._delay = window.setTimeout(function() { self.spinCfg._delay = window.setTimeout(function () {
adjust(); adjust();
// Repeat adjust at regular intervals // Repeat adjust at regular intervals
self.spinCfg._repeat = window.setInterval(adjust, self.spinCfg.interval); self.spinCfg._repeat = window.setInterval(adjust, self.spinCfg.interval);
@@ -185,21 +186,21 @@ $.fn.SpinButton = function(cfg) { 'use strict';
} }
}) })
.mouseup(function(e){ .mouseup(function (e) {
// Cancel repeating adjustment // Cancel repeating adjustment
window.clearInterval(this.spinCfg._repeat); window.clearInterval(this.spinCfg._repeat);
window.clearTimeout(this.spinCfg._delay); window.clearTimeout(this.spinCfg._delay);
}) })
.dblclick(function(e) { .dblclick(function (e) {
if ($.browser.msie) { if ($.browser.msie) {
this.adjustValue(this.spinCfg._direction * this.spinCfg.step); this.adjustValue(this.spinCfg._direction * this.spinCfg.step);
} }
}) })
.keydown(function(e){ .keydown(function (e) {
// Respond to up/down arrow keys. // Respond to up/down arrow keys.
switch(e.keyCode){ switch (e.keyCode) {
case 38: this.adjustValue(this.spinCfg.step); break; // Up case 38: this.adjustValue(this.spinCfg.step); break; // Up
case 40: this.adjustValue(-this.spinCfg.step); break; // Down case 40: this.adjustValue(-this.spinCfg.step); break; // Down
case 33: this.adjustValue(this.spinCfg.page); break; // PageUp case 33: this.adjustValue(this.spinCfg.page); break; // PageUp
@@ -213,26 +214,25 @@ $.fn.SpinButton = function(cfg) { 'use strict';
- Safari 3.1 changed their model so that keydown is reliably repeated going forward - Safari 3.1 changed their model so that keydown is reliably repeated going forward
- Firefox and Opera still only repeat the keypress event, not the keydown - Firefox and Opera still only repeat the keypress event, not the keydown
*/ */
.keypress(function(e){ .keypress(function (e) {
if (this.repeating) { if (this.repeating) {
// Respond to up/down arrow keys. // Respond to up/down arrow keys.
switch(e.keyCode){ switch (e.keyCode) {
case 38: this.adjustValue(this.spinCfg.step); break; // Up case 38: this.adjustValue(this.spinCfg.step); break; // Up
case 40: this.adjustValue(-this.spinCfg.step); break; // Down case 40: this.adjustValue(-this.spinCfg.step); break; // Down
case 33: this.adjustValue(this.spinCfg.page); break; // PageUp case 33: this.adjustValue(this.spinCfg.page); break; // PageUp
case 34: this.adjustValue(-this.spinCfg.page); break; // PageDown case 34: this.adjustValue(-this.spinCfg.page); break; // PageDown
} }
}
// we always ignore the first keypress event (use the keydown instead) // we always ignore the first keypress event (use the keydown instead)
else { } else {
this.repeating = true; this.repeating = true;
} }
}) })
// clear the 'repeating' flag // clear the 'repeating' flag
.keyup(function(e) { .keyup(function (e) {
this.repeating = false; this.repeating = false;
switch(e.keyCode){ switch (e.keyCode) {
case 38: // Up case 38: // Up
case 40: // Down case 40: // Down
case 33: // PageUp case 33: // PageUp
@@ -241,29 +241,27 @@ $.fn.SpinButton = function(cfg) { 'use strict';
} }
}) })
.bind("mousewheel", function(e){ .bind('mousewheel', function (e) {
// Respond to mouse wheel in IE. (It returns up/dn motion in multiples of 120) // Respond to mouse wheel in IE. (It returns up/dn motion in multiples of 120)
if (e.wheelDelta >= 120) { if (e.wheelDelta >= 120) {
this.adjustValue(this.spinCfg.step); this.adjustValue(this.spinCfg.step);
} } else if (e.wheelDelta <= -120) {
else if (e.wheelDelta <= -120) {
this.adjustValue(-this.spinCfg.step); this.adjustValue(-this.spinCfg.step);
} }
e.preventDefault(); e.preventDefault();
}) })
.change(function(e){ .change(function (e) {
this.adjustValue(0); this.adjustValue(0);
}); });
if (this.addEventListener) { if (this.addEventListener) {
// Respond to mouse wheel in Firefox // Respond to mouse wheel in Firefox
this.addEventListener('DOMMouseScroll', function(e) { this.addEventListener('DOMMouseScroll', function (e) {
if (e.detail > 0) { if (e.detail > 0) {
this.adjustValue(-this.spinCfg.step); this.adjustValue(-this.spinCfg.step);
} } else if (e.detail < 0) {
else if (e.detail < 0) {
this.adjustValue(this.spinCfg.step); this.adjustValue(this.spinCfg.step);
} }

View File

@@ -1,4 +1,6 @@
/* /* eslint-disable no-var */
/* globals jQuery */
/*
* SVG Icon Loader 2.0 * SVG Icon Loader 2.0
* *
* jQuery Plugin for loading SVG icons from a single file * jQuery Plugin for loading SVG icons from a single file
@@ -72,7 +74,6 @@ This will return the icon (as jQuery object) with a given ID.
6. To resize icons at a later point without using the callback, use this: 6. To resize icons at a later point without using the callback, use this:
$.resizeSvgIcons(resizeOptions) (use the same way as the "resize" parameter) $.resizeSvgIcons(resizeOptions) (use the same way as the "resize" parameter)
Example usage #1: Example usage #1:
$(function() { $(function() {
@@ -123,30 +124,30 @@ $(function() {
}) })
}); });
*/ */
(function ($) {
var svgIcons = {}, fixIDs;
(function($) { $.svgIcons = function (file, opts) {
var svg_icons = {}, fixIDs; var svgns = 'http://www.w3.org/2000/svg',
xlinkns = 'http://www.w3.org/1999/xlink',
$.svgIcons = function(file, opts) { iconW = opts.w || 24,
var svgns = "http://www.w3.org/2000/svg", iconH = opts.h || 24,
xlinkns = "http://www.w3.org/1999/xlink",
icon_w = opts.w?opts.w : 24,
icon_h = opts.h?opts.h : 24,
elems, svgdoc, testImg, elems, svgdoc, testImg,
icons_made = false, data_loaded = false, load_attempts = 0, iconsMade = false, dataLoaded = false, loadAttempts = 0,
ua = navigator.userAgent, isOpera = !!window.opera, isSafari = (ua.indexOf('Safari/') > -1 && ua.indexOf('Chrome/')==-1), // ua = navigator.userAgent,
data_pre = 'data:image/svg+xml;charset=utf-8;base64,'; isOpera = !!window.opera,
// isSafari = (ua.indexOf('Safari/') > -1 && ua.indexOf('Chrome/') === -1),
dataPre = 'data:image/svg+xml;charset=utf-8;base64,';
if(opts.svgz) { if (opts.svgz) {
var data_el = $('<object data="' + file + '" type=image/svg+xml>').appendTo('body').hide(); var dataEl = $('<object data="' + file + '" type=image/svg+xml>').appendTo('body').hide();
try { try {
svgdoc = data_el[0].contentDocument; svgdoc = dataEl[0].contentDocument;
data_el.load(getIcons); dataEl.load(getIcons);
getIcons(0, true); // Opera will not run "load" event if file is already cached getIcons(0, true); // Opera will not run "load" event if file is already cached
} catch(err1) { } catch (err1) {
useFallback(); useFallback();
} }
} else { } else {
@@ -154,30 +155,30 @@ $(function() {
$.ajax({ $.ajax({
url: file, url: file,
dataType: 'string', dataType: 'string',
success: function(data) { success: function (data) {
if(!data) { if (!data) {
$(useFallback); $(useFallback);
return; return;
} }
svgdoc = parser.parseFromString(data, "text/xml"); svgdoc = parser.parseFromString(data, 'text/xml');
$(function() { $(function () {
getIcons('ajax'); getIcons('ajax');
}); });
}, },
error: function(err) { error: function (err) {
// TODO: Fix Opera widget icon bug // TODO: Fix Opera widget icon bug
if(window.opera) { if (window.opera) {
$(function() { $(function () {
useFallback(); useFallback();
}); });
} else { } else {
if(err.responseText) { if (err.responseText) {
svgdoc = parser.parseFromString(err.responseText, "text/xml"); svgdoc = parser.parseFromString(err.responseText, 'text/xml');
if(!svgdoc.childNodes.length) { if (!svgdoc.childNodes.length) {
$(useFallback); $(useFallback);
} }
$(function() { $(function () {
getIcons('ajax'); getIcons('ajax');
}); });
} else { } else {
@@ -188,31 +189,31 @@ $(function() {
}); });
} }
function getIcons(evt, no_wait) { function getIcons (evt, noWait) {
if(evt !== 'ajax') { if (evt !== 'ajax') {
if(data_loaded) return; if (dataLoaded) return;
// Webkit sometimes says svgdoc is undefined, other times // Webkit sometimes says svgdoc is undefined, other times
// it fails to load all nodes. Thus we must make sure the "eof" // it fails to load all nodes. Thus we must make sure the "eof"
// element is loaded. // element is loaded.
svgdoc = data_el[0].contentDocument; // Needed again for Webkit svgdoc = dataEl[0].contentDocument; // Needed again for Webkit
var isReady = (svgdoc && svgdoc.getElementById('svg_eof')); var isReady = (svgdoc && svgdoc.getElementById('svg_eof'));
if(!isReady && !(no_wait && isReady)) { if (!isReady && !(noWait && isReady)) {
load_attempts++; loadAttempts++;
if(load_attempts < 50) { if (loadAttempts < 50) {
setTimeout(getIcons, 20); setTimeout(getIcons, 20);
} else { } else {
useFallback(); useFallback();
data_loaded = true; dataLoaded = true;
} }
return; return;
} }
data_loaded = true; dataLoaded = true;
} }
elems = $(svgdoc.firstChild).children(); //.getElementsByTagName('foreignContent'); elems = $(svgdoc.firstChild).children(); // .getElementsByTagName('foreignContent');
if(!opts.no_img) { if (!opts.no_img) {
var testSrc = data_pre + 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D'; var testSrc = dataPre + 'PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNzUiIGhlaWdodD0iMjc1Ij48L3N2Zz4%3D';
testImg = $(new Image()).attr({ testImg = $(new Image()).attr({
src: testSrc, src: testSrc,
@@ -226,56 +227,56 @@ $(function() {
makeIcons(); makeIcons();
}); });
} else { } else {
setTimeout(function() { setTimeout(function () {
if(!icons_made) makeIcons(); if (!iconsMade) makeIcons();
},500); }, 500);
} }
} }
var setIcon = function(target, icon, id, setID) { var setIcon = function (target, icon, id, setID) {
if(isOpera) icon.css('visibility','hidden'); if (isOpera) icon.css('visibility', 'hidden');
if(opts.replace) { if (opts.replace) {
if(setID) icon.attr('id',id); if (setID) icon.attr('id', id);
var cl = target.attr('class'); var cl = target.attr('class');
if(cl) icon.attr('class','svg_icon '+cl); if (cl) icon.attr('class', 'svg_icon ' + cl);
target.replaceWith(icon); target.replaceWith(icon);
} else { } else {
target.append(icon); target.append(icon);
} }
if(isOpera) { if (isOpera) {
setTimeout(function() { setTimeout(function () {
icon.removeAttr('style'); icon.removeAttr('style');
},1); }, 1);
} }
}; };
var addIcon = function(icon, id) { var holder;
if(opts.id_match === undefined || opts.id_match !== false) { var addIcon = function (icon, id) {
if (opts.id_match === undefined || opts.id_match !== false) {
setIcon(holder, icon, id, true); setIcon(holder, icon, id, true);
} }
svg_icons[id] = icon; svgIcons[id] = icon;
}; };
function makeIcons(toImage, fallback) { function makeIcons (toImage, fallback) {
if(icons_made) return; if (iconsMade) return;
if(opts.no_img) toImage = false; if (opts.no_img) toImage = false;
var holder, temp_holder; var tempHolder;
if(toImage) { if (toImage) {
temp_holder = $(document.createElement('div')); tempHolder = $(document.createElement('div'));
temp_holder.hide().appendTo('body'); tempHolder.hide().appendTo('body');
} }
if(fallback) { if (fallback) {
var path = opts.fallback_path?opts.fallback_path:''; var path = opts.fallback_path || '';
$.each(fallback, function(id, imgsrc) { $.each(fallback, function (id, imgsrc) {
holder = $('#' + id); holder = $('#' + id);
var icon = $(new Image()) var icon = $(new Image())
.attr({ .attr({
'class':'svg_icon', 'class': 'svg_icon',
src: path + imgsrc, src: path + imgsrc,
'width': icon_w, 'width': iconW,
'height': icon_h, 'height': iconH,
'alt': 'icon' 'alt': 'icon'
}); });
@@ -283,16 +284,16 @@ $(function() {
}); });
} else { } else {
var len = elems.length; var len = elems.length;
for(var i = 0; i < len; i++) { for (var i = 0; i < len; i++) {
var elem = elems[i]; var elem = elems[i];
var id = elem.id; var id = elem.id;
if(id === 'svg_eof') break; if (id === 'svg_eof') break;
holder = $('#' + id); holder = $('#' + id);
var svg = elem.getElementsByTagNameNS(svgns, 'svg')[0]; var svg = elem.getElementsByTagNameNS(svgns, 'svg')[0];
var svgroot = document.createElementNS(svgns, "svg"); var svgroot = document.createElementNS(svgns, 'svg');
// Per http://www.w3.org/TR/xml-names11/#defaulting, the namespace for // Per http://www.w3.org/TR/xml-names11/#defaulting, the namespace for
// attributes should have no value. // attributes should have no value.
svgroot.setAttributeNS(null, 'viewBox', [0,0,icon_w,icon_h].join(' ')); svgroot.setAttributeNS(null, 'viewBox', [0, 0, iconW, iconH].join(' '));
// Make flexible by converting width/height to viewBox // Make flexible by converting width/height to viewBox
var w = svg.getAttribute('width'); var w = svg.getAttribute('width');
@@ -301,128 +302,129 @@ $(function() {
svg.removeAttribute('height'); svg.removeAttribute('height');
var vb = svg.getAttribute('viewBox'); var vb = svg.getAttribute('viewBox');
if(!vb) { if (!vb) {
svg.setAttribute('viewBox', [0,0,w,h].join(' ')); svg.setAttribute('viewBox', [0, 0, w, h].join(' '));
} }
// Not using jQuery to be a bit faster // Not using jQuery to be a bit faster
svgroot.setAttribute('xmlns', svgns); svgroot.setAttribute('xmlns', svgns);
svgroot.setAttribute('width', icon_w); svgroot.setAttribute('width', iconW);
svgroot.setAttribute('height', icon_h); svgroot.setAttribute('height', iconH);
svgroot.setAttribute("xmlns:xlink", xlinkns); svgroot.setAttribute('xmlns:xlink', xlinkns);
svgroot.setAttribute("class", 'svg_icon'); svgroot.setAttribute('class', 'svg_icon');
// Without cloning, Firefox will make another GET request. // Without cloning, Firefox will make another GET request.
// With cloning, causes issue in Opera/Win/Non-EN // With cloning, causes issue in Opera/Win/Non-EN
if(!isOpera) svg = svg.cloneNode(true); if (!isOpera) svg = svg.cloneNode(true);
svgroot.appendChild(svg); svgroot.appendChild(svg);
var icon; var icon;
if(toImage) { if (toImage) {
temp_holder.empty().append(svgroot); tempHolder.empty().append(svgroot);
var str = data_pre + encode64(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgroot)))); var str = dataPre + encode64(unescape(encodeURIComponent(new XMLSerializer().serializeToString(svgroot))));
icon = $(new Image()) icon = $(new Image())
.attr({'class':'svg_icon', src:str}); .attr({'class': 'svg_icon', src: str});
} else { } else {
icon = fixIDs($(svgroot), i); icon = fixIDs($(svgroot), i);
} }
addIcon(icon, id); addIcon(icon, id);
} }
} }
if(opts.placement) { if (opts.placement) {
$.each(opts.placement, function(sel, id) { $.each(opts.placement, function (sel, id) {
if(!svg_icons[id]) return; if (!svgIcons[id]) return;
$(sel).each(function(i) { $(sel).each(function (i) {
var copy = svg_icons[id].clone(); var copy = svgIcons[id].clone();
if(i > 0 && !toImage) copy = fixIDs(copy, i, true); if (i > 0 && !toImage) copy = fixIDs(copy, i, true);
setIcon($(this), copy, id); setIcon($(this), copy, id);
}); });
}); });
} }
if(!fallback) { if (!fallback) {
if(toImage) temp_holder.remove(); if (toImage) tempHolder.remove();
if(data_el) data_el.remove(); if (dataEl) dataEl.remove();
if(testImg) testImg.remove(); if (testImg) testImg.remove();
} }
if(opts.resize) $.resizeSvgIcons(opts.resize); if (opts.resize) $.resizeSvgIcons(opts.resize);
icons_made = true; iconsMade = true;
if(opts.callback) opts.callback(svg_icons); if (opts.callback) opts.callback(svgIcons);
} }
fixIDs = function(svg_el, svg_num, force) { fixIDs = function (svgEl, svgNum, force) {
var defs = svg_el.find('defs'); var defs = svgEl.find('defs');
if(!defs.length) return svg_el; if (!defs.length) return svgEl;
var id_elems; var idElems;
if(isOpera) { if (isOpera) {
id_elems = defs.find('*').filter(function() { idElems = defs.find('*').filter(function () {
return !!this.id; return !!this.id;
}); });
} else { } else {
id_elems = defs.find('[id]'); idElems = defs.find('[id]');
} }
var all_elems = svg_el[0].getElementsByTagName('*'), len = all_elems.length; var allElems = svgEl[0].getElementsByTagName('*'), len = allElems.length;
id_elems.each(function(i) { idElems.each(function (i) {
var id = this.id; var id = this.id;
var no_dupes = ($(svgdoc).find('#' + id).length <= 1); /*
if(isOpera) no_dupes = false; // Opera didn't clone svg_el, so not reliable var noDupes = ($(svgdoc).find('#' + id).length <= 1);
// if(!force && no_dupes) return; if (isOpera) noDupes = false; // Opera didn't clone svgEl, so not reliable
var new_id = 'x' + id + svg_num + i; if(!force && noDupes) return;
this.id = new_id; */
var newId = 'x' + id + svgNum + i;
this.id = newId;
var old_val = 'url(#' + id + ')'; var oldVal = 'url(#' + id + ')';
var new_val = 'url(#' + new_id + ')'; var newVal = 'url(#' + newId + ')';
// Selector method, possibly faster but fails in Opera / jQuery 1.4.3 // Selector method, possibly faster but fails in Opera / jQuery 1.4.3
// svg_el.find('[fill="url(#' + id + ')"]').each(function() { // svgEl.find('[fill="url(#' + id + ')"]').each(function() {
// this.setAttribute('fill', 'url(#' + new_id + ')'); // this.setAttribute('fill', 'url(#' + newId + ')');
// }).end().find('[stroke="url(#' + id + ')"]').each(function() { // }).end().find('[stroke="url(#' + id + ')"]').each(function() {
// this.setAttribute('stroke', 'url(#' + new_id + ')'); // this.setAttribute('stroke', 'url(#' + newId + ')');
// }).end().find('use').each(function() { // }).end().find('use').each(function() {
// if(this.getAttribute('xlink:href') == '#' + id) { // if(this.getAttribute('xlink:href') == '#' + id) {
// this.setAttributeNS(xlinkns,'href','#' + new_id); // this.setAttributeNS(xlinkns,'href','#' + newId);
// } // }
// }).end().find('[filter="url(#' + id + ')"]').each(function() { // }).end().find('[filter="url(#' + id + ')"]').each(function() {
// this.setAttribute('filter', 'url(#' + new_id + ')'); // this.setAttribute('filter', 'url(#' + newId + ')');
// }); // });
for(i = 0; i < len; i++) { for (i = 0; i < len; i++) {
var elem = all_elems[i]; var elem = allElems[i];
if(elem.getAttribute('fill') === old_val) { if (elem.getAttribute('fill') === oldVal) {
elem.setAttribute('fill', new_val); elem.setAttribute('fill', newVal);
} }
if(elem.getAttribute('stroke') === old_val) { if (elem.getAttribute('stroke') === oldVal) {
elem.setAttribute('stroke', new_val); elem.setAttribute('stroke', newVal);
} }
if(elem.getAttribute('filter') === old_val) { if (elem.getAttribute('filter') === oldVal) {
elem.setAttribute('filter', new_val); elem.setAttribute('filter', newVal);
} }
} }
}); });
return svg_el; return svgEl;
}; };
function useFallback() { function useFallback () {
if(file.indexOf('.svgz') != -1) { if (file.indexOf('.svgz') > -1) {
var reg_file = file.replace('.svgz','.svg'); var regFile = file.replace('.svgz', '.svg');
if(window.console) { if (window.console) {
console.log('.svgz failed, trying with .svg'); console.log('.svgz failed, trying with .svg');
} }
$.svgIcons(reg_file, opts); $.svgIcons(regFile, opts);
} else if(opts.fallback) { } else if (opts.fallback) {
makeIcons(false, opts.fallback); makeIcons(false, opts.fallback);
} }
} }
function encode64(input) { function encode64 (input) {
// base64 strings are 4/3 larger than the original string // base64 strings are 4/3 larger than the original string
if(window.btoa) return window.btoa(input); if (window.btoa) return window.btoa(input);
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var output = new Array( Math.floor( (input.length + 2) / 3 ) * 4 ); var output = new Array(Math.floor((input.length + 2) / 3) * 4);
var chr1, chr2, chr3; var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4; var enc1, enc2, enc3, enc4;
var i = 0, p = 0; var i = 0, p = 0;
@@ -451,35 +453,34 @@ $(function() {
return output.join(''); return output.join('');
} }
}; };
$.getSvgIcon = function(id, uniqueClone) { $.getSvgIcon = function (id, uniqueClone) {
var icon = svg_icons[id]; var icon = svgIcons[id];
if(uniqueClone && icon) { if (uniqueClone && icon) {
icon = fixIDs(icon, 0, true).clone(true); icon = fixIDs(icon, 0, true).clone(true);
} }
return icon; return icon;
}; };
$.resizeSvgIcons = function(obj) { $.resizeSvgIcons = function (obj) {
// FF2 and older don't detect .svg_icon, so we change it detect svg elems instead // FF2 and older don't detect .svg_icon, so we change it detect svg elems instead
var change_sel = !$('.svg_icon:first').length; var changeSel = !$('.svg_icon:first').length;
$.each(obj, function(sel, size) { $.each(obj, function (sel, size) {
var arr = $.isArray(size); var arr = $.isArray(size);
var w = arr?size[0]:size, var w = arr ? size[0] : size,
h = arr?size[1]:size; h = arr ? size[1] : size;
if(change_sel) { if (changeSel) {
sel = sel.replace(/\.svg_icon/g,'svg'); sel = sel.replace(/\.svg_icon/g, 'svg');
} }
$(sel).each(function() { $(sel).each(function () {
this.setAttribute('width', w); this.setAttribute('width', w);
this.setAttribute('height', h); this.setAttribute('height', h);
if(window.opera && window.widget) { if (window.opera && window.widget) {
this.parentNode.style.width = w + 'px'; this.parentNode.style.width = w + 'px';
this.parentNode.style.height = h + 'px'; this.parentNode.style.height = h + 'px';
} }
}); });
}); });
}; };
})(jQuery); })(jQuery);

View File

@@ -1,4 +1,5 @@
function start_svg_edit() { /* eslint-disable no-var */
var url = "chrome://svg-edit/content/editor/svg-editor.html"; function startSvgEdit () { // eslint-disable-line no-unused-vars
window.openDialog(url, "SVG Editor", "width=1024,height=700,menubar=no,toolbar=no"); var url = 'chrome://svg-edit/content/editor/svg-editor.html';
window.openDialog(url, 'SVG Editor', 'width=1024,height=700,menubar=no,toolbar=no');
} }

View File

@@ -11,14 +11,14 @@
<menupopup id="menu_ToolsPopup"> <menupopup id="menu_ToolsPopup">
<menuitem insertafter="devToolsSeparator" label="SVG Editor" <menuitem insertafter="devToolsSeparator" label="SVG Editor"
oncommand="start_svg_edit();" /> oncommand="startSvgEdit();" />
</menupopup> </menupopup>
<!-- Firefox --> <!-- Firefox -->
<statusbar id="status-bar"> <statusbar id="status-bar">
<statusbarpanel id="svg-edit-statusbar-button" <statusbarpanel id="svg-edit-statusbar-button"
class="statusbarpanel-menu-iconic" class="statusbarpanel-menu-iconic"
onclick="return start_svg_edit()" onclick="return startSvgEdit()"
tooltip="SvgEdit"> tooltip="SvgEdit">
</statusbarpanel> </statusbarpanel>
</statusbar> </statusbar>

View File

@@ -1,53 +1,54 @@
/* eslint-disable no-var */
/* global $, Components, svgCanvas, netscape */
// Note: This JavaScript file must be included as the last script on the main HTML editor page to override the open/save handlers // Note: This JavaScript file must be included as the last script on the main HTML editor page to override the open/save handlers
$(function() { $(function () {
if(!window.Components) return; if (!window.Components) return;
function moz_file_picker(readflag) { function mozFilePicker (readflag) {
var fp = window.Components.classes["@mozilla.org/filepicker;1"]. var fp = window.Components.classes['@mozilla.org/filepicker;1']
createInstance(Components.interfaces.nsIFilePicker); .createInstance(Components.interfaces.nsIFilePicker);
if(readflag) if (readflag) fp.init(window, 'Pick a SVG file', fp.modeOpen);
fp.init(window, "Pick a SVG file", fp.modeOpen); else fp.init(window, 'Pick a SVG file', fp.modeSave);
else fp.defaultExtension = '*.svg';
fp.init(window, "Pick a SVG file", fp.modeSave);
fp.defaultExtension = "*.svg";
fp.show(); fp.show();
return fp.file; return fp.file;
} }
svgCanvas.setCustomHandlers({ svgCanvas.setCustomHandlers({
'open':function() { open: function () {
try { try {
netscape.security.PrivilegeManager. netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
enablePrivilege("UniversalXPConnect"); var file = mozFilePicker(true);
var file = moz_file_picker(true); if (!file) {
if(!file) return null;
return(null); }
var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); var inputStream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
inputStream.init(file, 0x01, 00004, null); inputStream.init(file, 0x01, parseInt('00004', 8), null);
var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); var sInputStream = Components.classes['@mozilla.org/scriptableinputstream;1'].createInstance(Components.interfaces.nsIScriptableInputStream);
sInputStream.init(inputStream); sInputStream.init(inputStream);
svgCanvas.setSvgString(sInputStream. svgCanvas.setSvgString(sInputStream.read(sInputStream.available()));
read(sInputStream.available())); } catch (e) {
} catch(e) { console.log('Exception while attempting to load' + e);
console.log("Exception while attempting to load" + e);
} }
}, },
'save':function(svg, str) { save: function (svg, str) {
try { try {
var file = moz_file_picker(false); var file = mozFilePicker(false);
if(!file) if (!file) {
return; return;
}
if (!file.exists()) if (!file.exists()) {
file.create(0, 0664); file.create(0, parseInt('0664', 8));
}
var out = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance(Components.interfaces.nsIFileOutputStream); var out = Components.classes['@mozilla.org/network/file-output-stream;1'].createInstance(Components.interfaces.nsIFileOutputStream);
out.init(file, 0x20 | 0x02, 00004,null); out.init(file, 0x20 | 0x02, parseInt('00004', 8), null);
out.write(str, str.length); out.write(str, str.length);
out.flush(); out.flush();
out.close(); out.close();
} catch(e) { } catch (e) {
alert(e); alert(e);
} }
} }

View File

@@ -1,60 +1,57 @@
/* eslint-disable no-var */
/* globals $, svgCanvas */
// Note: This JavaScript file must be included as the last script on the main HTML editor page to override the open/save handlers // Note: This JavaScript file must be included as the last script on the main HTML editor page to override the open/save handlers
$(function() { $(function () {
if(window.opera && window.opera.io && window.opera.io.filesystem) { if (window.opera && window.opera.io && window.opera.io.filesystem) {
svgCanvas.setCustomHandlers({ svgCanvas.setCustomHandlers({
'open':function() { open: function () {
try { try {
window.opera.io.filesystem.browseForFile( window.opera.io.filesystem.browseForFile(
new Date().getTime(), /* mountpoint name */ new Date().getTime(), /* mountpoint name */
"", /* default location */ '', /* default location */
function(file) { function (file) {
try { try {
if (file) { if (file) {
fstream = file.open(file, "r"); var fstream = file.open(file, 'r');
var output = ""; var output = '';
while (!fstream.eof) { while (!fstream.eof) {
output += fstream.readLine(); output += fstream.readLine();
} }
svgCanvas.setSvgString(output); /* 'this' is bound to the filestream object here */ svgCanvas.setSvgString(output); /* 'this' is bound to the filestream object here */
} }
} } catch (e) {
catch(e) { console.log('Reading file failed.');
console.log("Reading file failed.");
} }
}, },
false, /* not persistent */ false, /* not persistent */
false, /* no multiple selections */ false, /* no multiple selections */
"*.svg" /* file extension filter */ '*.svg' /* file extension filter */
); );
} catch (e) {
console.log('Open file failed.');
} }
catch(e) {
console.log("Open file failed.");
}
}, },
'save':function(window, svg) { save: function (window, svg) {
try { try {
window.opera.io.filesystem.browseForSave( window.opera.io.filesystem.browseForSave(
new Date().getTime(), /* mountpoint name */ new Date().getTime(), /* mountpoint name */
"", /* default location */ '', /* default location */
function(file) { function (file) {
try { try {
if (file) { if (file) {
var fstream = file.open(file, "w"); var fstream = file.open(file, 'w');
fstream.write(svg, "UTF-8"); fstream.write(svg, 'UTF-8');
fstream.close(); fstream.close();
} }
} } catch (e) {
catch(e) { console.log('Write to file failed.');
console.log("Write to file failed.");
} }
}, },
false /* not persistent */ false /* not persistent */
); );
} } catch (e) {
catch(e) { console.log('Save file failed.');
console.log("Save file failed.");
} }
} }
}); });

View File

@@ -6,14 +6,12 @@
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<script> <script>
/** this method adds the script that overrides the default open/save handlers */ /** this method adds the script that overrides the default open/save handlers */
function addHandlers() function addHandlers () {
{ var cdoc = document.getElementById('container').contentDocument;
var cdoc = document.getElementById("container").contentDocument; if (cdoc) {
if(cdoc) var scriptelm = cdoc.createElement('script');
{ scriptelm.src = '../handlers.js';
var scriptelm = cdoc.createElement("script"); cdoc.getElementsByTagName('head')[0].appendChild(scriptelm);
scriptelm.src = "../handlers.js";
cdoc.getElementsByTagName("head")[0].appendChild(scriptelm);
} }
} }
</script> </script>

View File

@@ -206,10 +206,10 @@
<h2>Plugin Architecture</h2> <h2>Plugin Architecture</h2>
</header> </header>
<pre> <pre>
svgEditor.addExtension("Hello World", function() { svgEditor.addExtension("Hello World", function () {
return { return {
svgicons: "extensions/helloworld-icon.xml", svgicons: 'extensions/helloworld-icon.xml',
buttons: [{...}], buttons: [{...}],
mouseDown: function() { mouseDown: function() {
... ...

View File

@@ -1,29 +1,30 @@
(function() { /* eslint-disable no-var */
var doc = document; (function () {
var disableBuilds = true; var doc = document;
var disableBuilds = true;
var ctr = 0; var ctr = 0;
var spaces = /\s+/, a1 = ['']; var spaces = /\s+/, a1 = [''];
var toArray = function(list) { var toArray = function (list) {
return Array.prototype.slice.call(list || [], 0); return Array.prototype.slice.call(list || [], 0);
}; };
var byId = function(id) { var byId = function (id) {
if (typeof id == 'string') { return doc.getElementById(id); } if (typeof id === 'string') { return doc.getElementById(id); }
return id; return id;
}; };
var query = function(query, root) { var query = function (query, root) {
if (!query) { return []; } if (!query) { return []; }
if (typeof query != 'string') { return toArray(query); } if (typeof query !== 'string') { return toArray(query); }
if (typeof root == 'string') { if (typeof root === 'string') {
root = byId(root); root = byId(root);
if(!root){ return []; } if (!root) { return []; }
} }
root = root || document; root = root || document;
var rootIsDoc = (root.nodeType == 9); var rootIsDoc = (root.nodeType === 9);
var doc = rootIsDoc ? root : (root.ownerDocument || document); var doc = rootIsDoc ? root : (root.ownerDocument || document);
// rewrite the query to be ID rooted // rewrite the query to be ID rooted
@@ -35,21 +36,20 @@
if ('>~+'.indexOf(query.slice(-1)) >= 0) { query += ' *'; } if ('>~+'.indexOf(query.slice(-1)) >= 0) { query += ' *'; }
return toArray(doc.querySelectorAll(query)); return toArray(doc.querySelectorAll(query));
}; };
var strToArray = function(s) { var strToArray = function (s) {
if (typeof s == 'string' || s instanceof String) { if (typeof s === 'string' || s instanceof String) {
if (s.indexOf(' ') < 0) { if (s.indexOf(' ') < 0) {
a1[0] = s; a1[0] = s;
return a1; return a1;
} else { }
return s.split(spaces); return s.split(spaces);
} }
}
return s; return s;
}; };
var addClass = function(node, classStr) { var addClass = function (node, classStr) {
classStr = strToArray(classStr); classStr = strToArray(classStr);
var cls = ' ' + node.className + ' '; var cls = ' ' + node.className + ' ';
for (var i = 0, len = classStr.length, c; i < len; ++i) { for (var i = 0, len = classStr.length, c; i < len; ++i) {
@@ -59,9 +59,9 @@
} }
} }
node.className = cls.trim(); node.className = cls.trim();
}; };
var removeClass = function(node, classStr) { var removeClass = function (node, classStr) {
var cls; var cls;
if (classStr !== undefined) { if (classStr !== undefined) {
classStr = strToArray(classStr); classStr = strToArray(classStr);
@@ -73,37 +73,37 @@
} else { } else {
cls = ''; cls = '';
} }
if (node.className != cls) { if (node.className !== cls) {
node.className = cls; node.className = cls;
} }
}; };
var toggleClass = function(node, classStr) { var toggleClass = function (node, classStr) {
var cls = ' ' + node.className + ' '; var cls = ' ' + node.className + ' ';
if (cls.indexOf(' ' + classStr.trim() + ' ') >= 0) { if (cls.indexOf(' ' + classStr.trim() + ' ') >= 0) {
removeClass(node, classStr); removeClass(node, classStr);
} else { } else {
addClass(node, classStr); addClass(node, classStr);
} }
}; };
var ua = navigator.userAgent; var ua = navigator.userAgent;
var isFF = parseFloat(ua.split('Firefox/')[1]) || undefined; var isFF = parseFloat(ua.split('Firefox/')[1]) || undefined;
var isWK = parseFloat(ua.split('WebKit/')[1]) || undefined; var isWK = parseFloat(ua.split('WebKit/')[1]) || undefined;
var isOpera = parseFloat(ua.split('Opera/')[1]) || undefined; var isOpera = parseFloat(ua.split('Opera/')[1]) || undefined;
var canTransition = (function() { var canTransition = (function () {
var ver = parseFloat(ua.split('Version/')[1]) || undefined; var ver = parseFloat(ua.split('Version/')[1]) || undefined;
// test to determine if this browser can handle CSS transitions. // test to determine if this browser can handle CSS transitions.
var cachedCanTransition = var cachedCanTransition =
(isWK || (isFF && isFF > 3.6 ) || (isOpera && ver >= 10.5)); (isWK || (isFF && isFF > 3.6) || (isOpera && ver >= 10.5));
return function() { return cachedCanTransition; } return function () { return cachedCanTransition; };
})(); })();
// //
// Slide class // Slide class
// //
var Slide = function(node, idx) { var Slide = function (node, idx) {
this._node = node; this._node = node;
if (idx >= 0) { if (idx >= 0) {
this._count = idx + 1; this._count = idx + 1;
@@ -113,9 +113,9 @@
} }
this._makeCounter(); this._makeCounter();
this._makeBuildList(); this._makeBuildList();
}; };
Slide.prototype = { Slide.prototype = {
_node: null, _node: null,
_count: 0, _count: 0,
_buildList: [], _buildList: [],
@@ -124,11 +124,11 @@
_states: [ 'distant-slide', 'far-past', _states: [ 'distant-slide', 'far-past',
'past', 'current', 'future', 'past', 'current', 'future',
'far-future', 'distant-slide' ], 'far-future', 'distant-slide' ],
setState: function(state) { setState: function (state) {
if (typeof state != 'string') { if (typeof state !== 'string') {
state = this._states[state]; state = this._states[state];
} }
if (state == 'current' && !this._visited) { if (state === 'current' && !this._visited) {
this._visited = true; this._visited = true;
this._makeBuildList(); this._makeBuildList();
} }
@@ -141,32 +141,32 @@
this._runAutos(); this._runAutos();
*/ */
var _t = this; var _t = this;
setTimeout(function(){ _t._runAutos(); } , 400); setTimeout(function () { _t._runAutos(); }, 400);
}, },
_makeCounter: function() { _makeCounter: function () {
if(!this._count || !this._node) { return; } if (!this._count || !this._node) { return; }
var c = doc.createElement('span'); var c = doc.createElement('span');
c.innerHTML = this._count; c.innerHTML = this._count;
c.className = 'counter'; c.className = 'counter';
this._node.appendChild(c); this._node.appendChild(c);
}, },
_makeBuildList: function() { _makeBuildList: function () {
this._buildList = []; this._buildList = [];
if (disableBuilds) { return; } if (disableBuilds) { return; }
if (this._node) { if (this._node) {
this._buildList = query('[data-build] > *', this._node); this._buildList = query('[data-build] > *', this._node);
} }
this._buildList.forEach(function(el) { this._buildList.forEach(function (el) {
addClass(el, 'to-build'); addClass(el, 'to-build');
}); });
}, },
_runAutos: function() { _runAutos: function () {
if (this._currentState != 'current') { if (this._currentState !== 'current') {
return; return;
} }
// find the next auto, slice it out of the list, and run it // find the next auto, slice it out of the list, and run it
var idx = -1; var idx = -1;
this._buildList.some(function(n, i) { this._buildList.some(function (n, i) {
if (n.hasAttribute('data-auto')) { if (n.hasAttribute('data-auto')) {
idx = i; idx = i;
return true; return true;
@@ -178,61 +178,61 @@
var transitionEnd = isWK ? 'webkitTransitionEnd' : (isFF ? 'mozTransitionEnd' : 'oTransitionEnd'); var transitionEnd = isWK ? 'webkitTransitionEnd' : (isFF ? 'mozTransitionEnd' : 'oTransitionEnd');
var _t = this; var _t = this;
if (canTransition()) { if (canTransition()) {
var l = function(evt) { var l = function (evt) {
elem.parentNode.removeEventListener(transitionEnd, l, false); elem.parentNode.removeEventListener(transitionEnd, l, false);
_t._runAutos(); _t._runAutos();
}; };
elem.parentNode.addEventListener(transitionEnd, l, false); elem.parentNode.addEventListener(transitionEnd, l, false);
removeClass(elem, 'to-build'); removeClass(elem, 'to-build');
} else { } else {
setTimeout(function() { setTimeout(function () {
removeClass(elem, 'to-build'); removeClass(elem, 'to-build');
_t._runAutos(); _t._runAutos();
}, 400); }, 400);
} }
} }
}, },
buildNext: function() { buildNext: function () {
if (!this._buildList.length) { if (!this._buildList.length) {
return false; return false;
} }
removeClass(this._buildList.shift(), 'to-build'); removeClass(this._buildList.shift(), 'to-build');
return true; return true;
}, }
}; };
// //
// SlideShow class // SlideShow class
// //
var SlideShow = function(slides) { var SlideShow = function (slides) {
this._slides = (slides || []).map(function(el, idx) { this._slides = (slides || []).map(function (el, idx) {
return new Slide(el, idx); return new Slide(el, idx);
}); });
var h = window.location.hash; var h = window.location.hash;
try { try {
this.current = parseInt(h.split('#slide')[1], 10); this.current = parseInt(h.split('#slide')[1], 10);
}catch (e) { /* squeltch */ } } catch (e) { /* squeltch */ }
this.current = isNaN(this.current) ? 1 : this.current; this.current = isNaN(this.current) ? 1 : this.current;
var _t = this; var _t = this;
doc.addEventListener('keydown', doc.addEventListener('keydown',
function(e) { _t.handleKeys(e); }, false); function (e) { _t.handleKeys(e); }, false);
doc.addEventListener('mousewheel', doc.addEventListener('mousewheel',
function(e) { _t.handleWheel(e); }, false); function (e) { _t.handleWheel(e); }, false);
doc.addEventListener('DOMMouseScroll', doc.addEventListener('DOMMouseScroll',
function(e) { _t.handleWheel(e); }, false); function (e) { _t.handleWheel(e); }, false);
doc.addEventListener('touchstart', doc.addEventListener('touchstart',
function(e) { _t.handleTouchStart(e); }, false); function (e) { _t.handleTouchStart(e); }, false);
doc.addEventListener('touchend', doc.addEventListener('touchend',
function(e) { _t.handleTouchEnd(e); }, false); function (e) { _t.handleTouchEnd(e); }, false);
window.addEventListener('popstate', window.addEventListener('popstate',
function(e) { _t.go(e.state); }, false); function (e) { _t.go(e.state); }, false);
this._update(); this._update();
}; };
SlideShow.prototype = { SlideShow.prototype = {
_slides: [], _slides: [],
_update: function(dontPush) { _update: function (dontPush) {
document.querySelector('#presentation-counter').innerText = this.current; document.querySelector('#presentation-counter').innerText = this.current;
if (history.pushState) { if (history.pushState) {
if (!dontPush) { if (!dontPush) {
@@ -241,26 +241,26 @@
} else { } else {
window.location.hash = 'slide' + this.current; window.location.hash = 'slide' + this.current;
} }
for (var x = this.current-1; x < this.current + 7; x++) { for (var x = this.current - 1; x < this.current + 7; x++) {
if (this._slides[x-4]) { if (this._slides[x - 4]) {
this._slides[x-4].setState(Math.max(0, x-this.current)); this._slides[x - 4].setState(Math.max(0, x - this.current));
} }
} }
}, },
current: 0, current: 0,
next: function() { next: function () {
if (!this._slides[this.current-1].buildNext()) { if (!this._slides[this.current - 1].buildNext()) {
this.current = Math.min(this.current + 1, this._slides.length); this.current = Math.min(this.current + 1, this._slides.length);
this._update(); this._update();
} }
}, },
prev: function() { prev: function () {
this.current = Math.max(this.current-1, 1); this.current = Math.max(this.current - 1, 1);
this._update(); this._update();
}, },
go: function(num) { go: function (num) {
if (history.pushState && this.current != num) { if (history.pushState && this.current !== num) {
history.replaceState(this.current, 'Slide ' + this.current, '#slide' + this.current); history.replaceState(this.current, 'Slide ' + this.current, '#slide' + this.current);
} }
this.current = num; this.current = num;
@@ -268,37 +268,35 @@
}, },
_notesOn: false, _notesOn: false,
showNotes: function() { showNotes: function () {
var isOn = this._notesOn = !this._notesOn; var notesOn = this._notesOn = !this._notesOn;
query('.notes').forEach(function(el) { query('.notes').forEach(function (el) {
el.style.display = (notesOn) ? 'block' : 'none'; el.style.display = (notesOn) ? 'block' : 'none';
}); });
}, },
switch3D: function() { switch3D: function () {
toggleClass(document.body, 'three-d'); toggleClass(document.body, 'three-d');
}, },
handleWheel: function(e) { handleWheel: function (e) {
var delta = 0; var delta = 0;
if (e.wheelDelta) { if (e.wheelDelta) {
delta = e.wheelDelta/120; delta = e.wheelDelta / 120;
if (isOpera) { if (isOpera) {
delta = -delta; delta = -delta;
} }
} else if (e.detail) { } else if (e.detail) {
delta = -e.detail/3; delta = -e.detail / 3;
} }
if (delta > 0 ) { if (delta > 0) {
this.prev(); this.prev();
return; return;
} }
if (delta < 0 ) { if (delta < 0) {
this.next(); this.next();
return;
} }
}, },
handleKeys: function(e) { handleKeys: function (e) {
if (/^(input|textarea)$/i.test(e.target.nodeName)) return; if (/^(input|textarea)$/i.test(e.target.nodeName)) return;
switch (e.keyCode) { switch (e.keyCode) {
@@ -314,77 +312,64 @@
} }
}, },
_touchStartX: 0, _touchStartX: 0,
handleTouchStart: function(e) { handleTouchStart: function (e) {
this._touchStartX = e.touches[0].pageX; this._touchStartX = e.touches[0].pageX;
}, },
handleTouchEnd: function(e) { handleTouchEnd: function (e) {
var delta = this._touchStartX - e.changedTouches[0].pageX; var delta = this._touchStartX - e.changedTouches[0].pageX;
var SWIPE_SIZE = 150; var SWIPE_SIZE = 150;
if (delta > SWIPE_SIZE) { if (delta > SWIPE_SIZE) {
this.next(); this.next();
} else if (delta< -SWIPE_SIZE) { } else if (delta < -SWIPE_SIZE) {
this.prev(); this.prev();
} }
}, }
}; };
// Initialize // Initialize
var slideshow = new SlideShow(query('.slide')); var slideshow = new SlideShow(query('.slide')); // eslint-disable-line no-unused-vars
document.querySelector('#toggle-counter').addEventListener('click', toggleCounter, false);
document.querySelector('#toggle-size').addEventListener('click', toggleSize, false);
document.querySelector('#toggle-transitions').addEventListener('click', toggleTransitions, false);
document.querySelector('#toggle-gradients').addEventListener('click', toggleGradients, false);
var counters = document.querySelectorAll('.counter');
var slides = document.querySelectorAll('.slide');
function toggleCounter () {
toArray(counters).forEach(function (el) {
document.querySelector('#toggle-counter').addEventListener('click', toggleCounter, false);
document.querySelector('#toggle-size').addEventListener('click', toggleSize, false);
document.querySelector('#toggle-transitions').addEventListener('click', toggleTransitions, false);
document.querySelector('#toggle-gradients').addEventListener('click', toggleGradients, false);
var counters = document.querySelectorAll('.counter');
var slides = document.querySelectorAll('.slide');
function toggleCounter() {
toArray(counters).forEach(function(el) {
el.style.display = (el.offsetHeight) ? 'none' : 'block'; el.style.display = (el.offsetHeight) ? 'none' : 'block';
}); });
} }
function toggleSize() { function toggleSize () {
toArray(slides).forEach(function(el) { toArray(slides).forEach(function (el) {
if (!/reduced/.test(el.className)) { if (!/reduced/.test(el.className)) {
addClass(el, 'reduced'); addClass(el, 'reduced');
} } else {
else {
removeClass(el, 'reduced'); removeClass(el, 'reduced');
} }
}); });
} }
function toggleTransitions() { function toggleTransitions () {
toArray(slides).forEach(function(el) { toArray(slides).forEach(function (el) {
if (!/no-transitions/.test(el.className)) { if (!/no-transitions/.test(el.className)) {
addClass(el, 'no-transitions'); addClass(el, 'no-transitions');
} } else {
else {
removeClass(el, 'no-transitions'); removeClass(el, 'no-transitions');
} }
}); });
} }
function toggleGradients() { function toggleGradients () {
toArray(slides).forEach(function(el) { toArray(slides).forEach(function (el) {
if (!/no-gradients/.test(el.className)) { if (!/no-gradients/.test(el.className)) {
addClass(el, 'no-gradients'); addClass(el, 'no-gradients');
} } else {
else {
removeClass(el, 'no-gradients'); removeClass(el, 'no-gradients');
} }
}); });
} }
})();
})();

View File

@@ -1,31 +1,30 @@
/* eslint-disable no-var */
/* globals wave, $, svgCanvas */
var shapetime = {}; var shapetime = {};
var nodelete = false; var nodelete = false;
function stateUpdated() { function stateUpdated () {
// 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements // 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements
// 'keys' is an array of all the keys in the state // 'keys' is an array of all the keys in the state
var state = wave.getState(); var state = wave.getState();
var keys = state.getKeys(); var keys = state.getKeys();
svgCanvas.each(function(e) { svgCanvas.each(function (e) {
// 'this' is the SVG DOM element node (ellipse, rect, etc) // 'this' is the SVG DOM element node (ellipse, rect, etc)
// 'e' is an integer describing the position within the document // 'e' is an integer describing the position within the document
var k = this.id; var k = this.id;
var v = state.get(k); var v = state.get(k);
if(k == "selectorParentGroup" || k == "svgcontent"){ if (k === 'selectorParentGroup' || k === 'svgcontent') {
//meh // meh
}else if (v) { } else if (v) {
var ob = JSON.parse(v); var ob = JSON.parse(v);
if (ob) { if (ob) {
// do nothing // do nothing
} else { } else {
//var node = document.getElementById(k); // var node = document.getElementById(k);
//if (node) node.parentNode.removeChild(node); // if (node) node.parentNode.removeChild(node);
} }
//keys.remove(k); // keys.remove(k);
} else if (!nodelete) {
} else if(!nodelete){
this.parentNode.removeChild(this); this.parentNode.removeChild(this);
} }
}); });
@@ -34,114 +33,106 @@ function stateUpdated() {
for (var k in keys) { for (var k in keys) {
var v = state.get(keys[k]); var v = state.get(keys[k]);
var ob = JSON.parse(v); var ob = JSON.parse(v);
if (ob){ if (ob) {
if(!shapetime[k] || ob.time > shapetime[k]){ if (!shapetime[k] || ob.time > shapetime[k]) {
var a; var a = document.getElementById(k);
if(a = document.getElementById(k)){ if (a) {
var attrs = get_attrs(a); var attrs = getAttrs(a);
if(JSON.stringify(attrs) != JSON.stringify(ob.attr)){ if (JSON.stringify(attrs) !== JSON.stringify(ob.attr)) {
shapetime[k] = ob.time shapetime[k] = ob.time;
svgCanvas.updateElementFromJson(ob) svgCanvas.updateElementFromJson(ob);
} }
}else{ } else {
shapetime[k] = ob.time shapetime[k] = ob.time;
svgCanvas.updateElementFromJson(ob) svgCanvas.updateElementFromJson(ob);
} }
} }
} }
} }
} }
function getId (canvas, objnum) {
function getId(canvas, objnum) { var id = wave.getViewer().getId().split('@')[0];
var id = wave.getViewer().getId().split("@")[0]; var extra = SHA256(wave.getViewer().getId()); // in case the next step kills all the characters
var extra = SHA256(wave.getViewer().getId()); //in case the next step kills all the characters for (var i = 0, l = id.length, n = ''; i < l; i++) {
for(var i = 0, l = id.length, n = ""; i < l; i++){ if ('abcdefghijklmnopqrstuvwxyz0123456789'.indexOf(id[i]) > -1) {
if("abcdefghijklmnopqrstuvwxyz0123456789".indexOf(id[i]) != -1){ n += id[i];
n+=id[i];
} }
} }
return "svg_"+n+"_"+extra.substr(0,5)+"_"+objnum; return 'svg_' + n + '_' + extra.substr(0, 5) + '_' + objnum;
} }
function get_attrs(a){ function getAttrs (a) {
var attrs = {}; var attrs = {};
for(var i = a.length; i--;){ for (var i = a.length; i--;) {
var attr = a.item(i).nodeName; var attr = a.item(i).nodeName;
if(",style,".indexOf(","+attr+",") == -1){ if (',style,'.indexOf(',' + attr + ',') === -1) {
attrs[attr] = a.item(i).nodeValue; attrs[attr] = a.item(i).nodeValue;
} }
} }
return attrs return attrs;
} }
function main() { function main () {
$(document).ready(function(){ $(document).ready(function () {
if (wave && wave.isInWaveContainer()) { if (wave && wave.isInWaveContainer()) {
wave.setStateCallback(function(){setTimeout(stateUpdated,10)}); wave.setStateCallback(function () {
setTimeout(stateUpdated, 10);
});
} }
var oldchanged = svgCanvas.bind("changed", function(canvas, elem){ var oldchanged = svgCanvas.bind('changed', function (canvas, elem) {
if(oldchanged)oldchanged.apply(this, [canvas,elem]); if (oldchanged) oldchanged.apply(this, [canvas, elem]);
var delta = {} var delta = {};
$.each(elem, function(){ $.each(elem, function () {
var attrs = {};
var a = this.attributes; var a = this.attributes;
if(a){ if (a) {
var attrs = get_attrs(a) var attrs = getAttrs(a);
var ob = {element: this.nodeName, attr: attrs}; var ob = {element: this.nodeName, attr: attrs};
ob.time = shapetime[this.id] = (new Date).getTime() ob.time = shapetime[this.id] = new Date().getTime();
delta[this.id] = JSON.stringify(ob); delta[this.id] = JSON.stringify(ob);
} }
})
wave.getState().submitDelta(delta)
//sendDelta(canvas, elem)
}); });
//*
var oldselected = svgCanvas.bind("selected", function(canvas, elem){ wave.getState().submitDelta(delta);
// sendDelta(canvas, elem)
});
// *
var oldselected = svgCanvas.bind('selected', function (canvas, elem) {
if (oldselected) oldselected.apply(this, [canvas, elem]);
if(oldselected)oldselected.apply(this, [canvas,elem]); var delta = {};
var delta = {}
var deletions = 0; var deletions = 0;
$.each(elem, function(){ $.each(elem, function () {
if(!this.parentNode && this != window){ if (!this.parentNode && this !== window) {
delta[this.id] = null; delta[this.id] = null;
deletions ++ deletions++;
} }
}); });
if(deletions > 0){ if (deletions > 0) {
wave.getState().submitDelta(delta) wave.getState().submitDelta(delta);
} }
}); });
/// //
svgCanvas.bind("cleared", function(){ svgCanvas.bind('cleared', function () {
//alert("cleared") // alert("cleared")
var state = {}, keys = wave.getState().getKeys() var state = {}, keys = wave.getState().getKeys();
for(var i = 0; i < keys.length; i++){ for (var i = 0; i < keys.length; i++) {
state[keys[i]] = null; state[keys[i]] = null;
} }
wave.getState().submitDelta(state) wave.getState().submitDelta(state);
});
// */
svgCanvas.bind('getid', getId);
}); });
//*/
svgCanvas.bind("getid", getId);
})
} }
if (window.gadgets) window.gadgets.util.registerOnLoadHandler(main);
// $(main)
if(window.gadgets) gadgets.util.registerOnLoadHandler(main); /* eslint-disable */
// and why not use my stuff?
//$(main)
//and why not use my stuff?
function SHA256(b){function h(j,k){return(j>>e)+(k>>e)+((p=(j&o)+(k&o))>>e)<<e|p&o}function f(j,k){return j>>>k|j<<32-k}var g=[],d,c=3,l=[2],p,i,q,a,m=[],n=[];i=b.length*8;for(var e=16,o=65535,r="";c<312;c++){for(d=l.length;d--&&c%l[d]!=0;);d<0&&l.push(c)}b+="\u0080";for(c=0;c<=i;c+=8)n[c>>5]|=(b.charCodeAt(c/8)&255)<<24-c%32;n[(i+64>>9<<4)+15]=i;for(c=8;c--;)m[c]=parseInt(Math.pow(l[c],0.5).toString(e).substr(2,8),e);for(c=0;c<n.length;c+=e){a=m.slice(0);for(b=0;b<64;b++){g[b]=b<e?n[b+c]:h(h(h(f(g[b-2],17)^f(g[b-2],19)^g[b-2]>>>10,g[b-7]),f(g[b-15],7)^f(g[b-15],18)^g[b-15]>>>3),g[b-e]);i=h(h(h(h(a[7],f(a[4],6)^f(a[4],11)^f(a[4],25)),a[4]&a[5]^~a[4]&a[6]),parseInt(Math.pow(l[b],1/3).toString(e).substr(2,8),e)),g[b]);q=(f(a[0],2)^f(a[0],13)^f(a[0],22))+(a[0]&a[1]^a[0]&a[2]^a[1]&a[2]);for(d=8;--d;)a[d]=d==4?h(a[3],i):a[d-1];a[0]=h(i,q)}for(d=8;d--;)m[d]+=a[d]}for(c=0;c<8;c++)for(b=8;b--;)r+=(m[c]>>>b*4&15).toString(e);return r} function SHA256(b){function h(j,k){return(j>>e)+(k>>e)+((p=(j&o)+(k&o))>>e)<<e|p&o}function f(j,k){return j>>>k|j<<32-k}var g=[],d,c=3,l=[2],p,i,q,a,m=[],n=[];i=b.length*8;for(var e=16,o=65535,r="";c<312;c++){for(d=l.length;d--&&c%l[d]!=0;);d<0&&l.push(c)}b+="\u0080";for(c=0;c<=i;c+=8)n[c>>5]|=(b.charCodeAt(c/8)&255)<<24-c%32;n[(i+64>>9<<4)+15]=i;for(c=8;c--;)m[c]=parseInt(Math.pow(l[c],0.5).toString(e).substr(2,8),e);for(c=0;c<n.length;c+=e){a=m.slice(0);for(b=0;b<64;b++){g[b]=b<e?n[b+c]:h(h(h(f(g[b-2],17)^f(g[b-2],19)^g[b-2]>>>10,g[b-7]),f(g[b-15],7)^f(g[b-15],18)^g[b-15]>>>3),g[b-e]);i=h(h(h(h(a[7],f(a[4],6)^f(a[4],11)^f(a[4],25)),a[4]&a[5]^~a[4]&a[6]),parseInt(Math.pow(l[b],1/3).toString(e).substr(2,8),e)),g[b]);q=(f(a[0],2)^f(a[0],13)^f(a[0],22))+(a[0]&a[1]^a[0]&a[2]^a[1]&a[2]);for(d=8;--d;)a[d]=d==4?h(a[3],i):a[d-1];a[0]=h(i,q)}for(d=8;d--;)m[d]+=a[d]}for(c=0;c<8;c++)for(b=8;b--;)r+=(m[c]>>>b*4&15).toString(e);return r}