d)
- this.ctx.stroke()
-
- if (dashed) this.ctx.setLineDash([])
-
- // knob
-
- this.ctx.lineWidth = PXSCALE
-
- this.ctx.fillStyle = this.colors.raised
- this.ctx.beginPath()
- this.ctx.globalAlpha = 1
- this.ctx.arc(this.width / 2, this.height / 2, knobRadius, 0, Math.PI * 2)
- this.ctx.fill()
- this.ctx.strokeStyle = this.colors.bg
- this.ctx.stroke()
-
- this.ctx.beginPath()
- this.ctx.globalAlpha = 1
- this.ctx.arc(this.width / 2, this.height / 2, knobRadius - PXSCALE * 1.5, 0, Math.PI * 2)
- this.ctx.strokeStyle = this.colors.light
- this.ctx.stroke()
-
- var g = this.ctx.createLinearGradient(this.width / 2, this.height / 2 - knobRadius / 2,this.width / 2, this.height / 2 + knobRadius / 2);
- g.addColorStop(0.5, 'transparent');
- g.addColorStop(0, this.colors.light);
-
- this.ctx.strokeStyle = g
- this.ctx.stroke()
-
- // cursor
- this.ctx.globalAlpha = 1
-
- let r1 = knobRadius,
- r2 = knobRadius / 2,
- a = 2 * Math.PI - d
-
- this.ctx.beginPath()
- this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
- this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
-
- this.ctx.lineWidth = tiny ? PXSCALE : 2 * PXSCALE
- this.ctx.strokeStyle = this.colors.knob
- this.ctx.stroke()
-
-
-
- }
-
-}
diff --git a/src/browser/js/app/widgets/switchers/switcher.js b/src/browser/js/app/widgets/switchers/switcher.js
deleted file mode 100644
index 8cf31ae5..00000000
--- a/src/browser/js/app/widgets/switchers/switcher.js
+++ /dev/null
@@ -1,86 +0,0 @@
-var _switchers_base = require('./_switchers_base'),
- Switch = require('../buttons/switch')
-
-var switchDefaults = Switch.defaults()
-
-module.exports = class Switcher extends _switchers_base {
-
- static defaults() {
-
- return {
- type:'switcher',
- id:'auto',
- linkId:'',
-
- _geometry:'geometry',
-
- left:'auto',
- top:'auto',
- width:'auto',
- height:'auto',
-
- _style:'style',
-
- label:'auto',
- color:'auto',
- css:'',
-
- _switcher:'Switcher',
-
- horizontal:false,
- linkedWidgets:'',
- values:['A', 'B'],
- value:'A',
-
- _osc:'osc',
-
- address:'auto',
- preArgs:[],
- target:[]
- }
-
- }
-
- constructor(options) {
-
- super({...options, html: '
'})
-
- if (this.getProp('horizontal')) this.widget.addClass('horizontal')
-
- this.switch = new Switch({props:{
- ...switchDefaults,
- label:false,
- values:this.getProp('values'),
- value: this.getProp('value'),
- horizontal:this.getProp('horizontal')
- }})
-
- this.switch.sendValue = ()=>{}
-
- this.widget.append(this.switch.widget)
-
- this.switch.widget.on('change', (e)=>{
-
- e.stopPropagation()
-
- var {widget, options} = e
-
- options.fromSelf = true
-
- this.setValue(this.switch.getValue(), options)
-
- })
-
-
- }
-
- setValue(v, options={}) {
-
- super.setValue(...arguments)
-
- if (!options.fromSelf) this.switch.setValue(this.value._selected)
-
- }
-
-
-}
diff --git a/src/browser/js/app/widgets/utils.js b/src/browser/js/app/widgets/utils.js
deleted file mode 100644
index db755163..00000000
--- a/src/browser/js/app/widgets/utils.js
+++ /dev/null
@@ -1,79 +0,0 @@
-module.exports = {
-
- clip: function(value,range) {
- var value = parseFloat(value)
-
- if (isNaN(value)) value = range[0]
- return Math.max(Math.min(range[0],range[1]),Math.min(value,Math.max(range[0],range[1])))
-
- },
-
- // map a value from a scale to another input and output must be range arrays
- mapToScale: function(value,rangeIn,rangeOut,precision,log,revertlog) {
-
- var value = module.exports.clip(value,[rangeIn[0],rangeIn[1]])
-
- value = log?
- revertlog?
- (Math.pow(10,((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])))/9-1/9) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
- :Math.log10(((value-rangeIn[0])/(rangeIn[1]-rangeIn[0]))*9+1) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
- :((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
-
- value = Math.max(Math.min(rangeOut[0],rangeOut[1]),Math.min(value,Math.max(rangeOut[0],rangeOut[1])))
-
- if (precision!==false) value = parseFloat(value.toFixed(precision))
-
-
- return value
-
- },
-
- hsbToRgb: function (hsb) {
- var rgb = {}
- var h = hsb.h
- var s = hsb.s*255/100
- var v = hsb.b*255/100
- if(s == 0) {
- rgb.r = rgb.g = rgb.b = v
- } else {
- var t1 = v
- var t2 = (255-s)*v/255
- var t3 = (t1-t2)*(h%60)/60
- if(h==360) h = 0
- if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
- else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
- else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
- else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
- else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
- else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
- else {rgb.r=0; rgb.g=0; rgb.b=0}
- }
- return rgb
- },
-
- rgbToHsb: function (rgb) {
- var hsb = {h: 0, s: 0, b: 0}
- var min = Math.min(rgb.r, rgb.g, rgb.b)
- var max = Math.max(rgb.r, rgb.g, rgb.b)
- var delta = max - min
- hsb.b = max
- hsb.s = max != 0 ? 255 * delta / max : 0
- if (hsb.s != 0) {
- if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
- else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
- else hsb.h = 4 + (rgb.r - rgb.g) / delta
- } else hsb.h = 0
- hsb.h *= 60
- if (hsb.h < 0) hsb.h += 360
- hsb.s *= 100/255
- hsb.b *= 100/255
- return hsb
- },
-
- math: function(){
- var math = require('mathjs/dist/math.min.js')
- // set math's parser array index base to zero
- math.expression.transform = Object.create(math)
- return math
- }()
-}
diff --git a/src/browser/js/browser.js b/src/browser/js/browser.js
deleted file mode 100644
index efe3b8cb..00000000
--- a/src/browser/js/browser.js
+++ /dev/null
@@ -1,17 +0,0 @@
-require('./app/globals')
-require('./app/sourcemap')
-
-var ipc = require('./app/ipc/'),
- osc = require('./app/osc'),
- parser = require('./app/parser'),
- {loading} = require('./app/utils')
-
-ipc.init()
-osc.init()
-parser.init()
-
-$(document).ready(function(){
- LOADING = loading('Connecting server...')
- require('./app/ui')
- ipc.send('ready')
-})
diff --git a/src/browser/js/libs/jquery.drag.js b/src/browser/js/libs/jquery.drag.js
deleted file mode 100644
index f12660f4..00000000
--- a/src/browser/js/libs/jquery.drag.js
+++ /dev/null
@@ -1,395 +0,0 @@
-// jQuery drag event handler
-// note: triggerHandler() is used instead of trigger() when event bubblig is not
-// necessary, this increases performances a lot.
-;(function($){
- var events = {
- touch:{start:'touchstart',stop:'touchend touchcancel',move:'touchmove',touch:true},
- mouse:{start:'mousedown',stop:'mouseup',move:'mousemove',out:'mouseout',touch:false}
- },
-
-
- $document = $(document),
- getOffset = function(obj) {
- var offsetLeft = 0
- var offsetTop = 0
- if (obj) {
- do {
- if (!isNaN(obj.offsetLeft)) {
- offsetLeft += obj.offsetLeft - obj.scrollLeft
- }
- if (!isNaN(obj.offsetTop)) {
- offsetTop += obj.offsetTop - obj.scrollTop
- }
- } while(obj = obj.offsetParent )
- }
-
- return {left: offsetLeft, top: offsetTop}
- }
-
-
- $.event.special.draginit = $.event.special.drag = {
- setup:function(){
-
- var $this = $(this)
-
- if ($this.data('dragSetup') == 'true') return
- $this.data('dragSetup','true')
-
-
- // mouse single touch handler
- var previousEvent = null,
- target = null,
- traversing = false,
- mouseStartHandler = function(e){
-
- // ignore mouse event when fired by a simulated touch event
- if ((e.originalEvent.sourceCapabilities && e.originalEvent.sourceCapabilities.firesTouchEvents) || e.button == 2) return
-
- target = $this
- previousEvent = e
-
- e.speedX = 0
- e.speedY = 0
- e.deltaX = 0
- e.deltaY = 0
-
- target.triggerHandler('draginit',[e,e.originalEvent.traversing])
-
- $document.on(events.mouse.move,mouseMoveHandler)
- $document.on(events.mouse.stop,mouseStopHandler)
- $document.on(events.mouse.out,mouseOutHandler)
-
- },
- mouseMoveHandler = function(e){
- e.stopPropagation()
-
- e.speedX = e.pageX - previousEvent.pageX
- e.speedY = e.pageY - previousEvent.pageY
- e.deltaX = e.speedX + previousEvent.deltaX
- e.deltaY = e.speedY + previousEvent.deltaY
-
-
- if (e.originalEvent.traversing) {
- target = $(e.target)
- e.preventDefault()
- target.triggerHandler('draginit',[e,e.originalEvent.traversing])
- } else {
- target.triggerHandler('drag',[e,e.originalEvent.traversing])
- }
-
- previousEvent = e
- },
- mouseStopHandler = function(e){
- e.stopPropagation()
-
- // ignore mouse event when fired by a simulated touch event
- if (e.originalEvent.sourceCapabilities && e.originalEvent.sourceCapabilities.firesTouchEvents) return
-
- e.speedX = e.pageX - previousEvent.pageX
- e.speedY = e.pageY - previousEvent.pageY
- e.deltaX = e.deltaX + previousEvent.deltaX
- e.deltaY = e.deltaY + previousEvent.deltaY
-
-
- target.trigger('dragend',[e,e.originalEvent.traversing])
-
- $document.off(events.mouse.move,mouseMoveHandler)
- $document.off(events.mouse.stop,mouseStopHandler)
- $document.off(events.mouse.out,mouseOutHandler)
- },
- mouseOutHandler = function(e){
- if (e.originalEvent.traversing) {
- e.stopPropagation()
-
- e.speedX = e.pageX - previousEvent.pageX
- e.speedY = e.pageY - previousEvent.pageY
- e.deltaX = e.deltaX + previousEvent.deltaX
- e.deltaY = e.deltaY + previousEvent.deltaY
-
- target.trigger('dragend',[e,e.originalEvent.traversing])
-
- previousEvent = e
-
- }
- }
-
-
- $this.on(events.mouse.start + '.drag-osc',mouseStartHandler)
-
-
- // multi touch hanlder
- window.targets = window.targets || {}
- window.previousTouches = window.previousTouches || {}
- window.touchActive = window.touchActive || false
-
- var self = this,
- touchStartHandler = function(e){
- e.preventDefault()
-
- var oE = e.originalEvent
-
- for (let i in oE.changedTouches) {
- if (isNaN(i) || !oE.changedTouches[i]) continue
-
- var touch = oE.changedTouches[i],
- id = touch.identifier,
- emit = true
-
- for (let j in targets) {
- if (targets[j][0].isSameNode(touch.target)) {
- emit = false
- break
- }
- }
-
- targets[id] = $(touch.target)
- previousTouches[id] = {
- deltaX:touch.deltaX,
- deltaY:touch.deltaY,
- offsetX:touch.offsetX,
- offsetY:touch.offsetY,
- speedX:touch.speedX,
- speedY:touch.speedY,
- pageX:touch.pageX,
- pageY:touch.pageY,
- clientX:touch.clientX,
- clientY:touch.clientY
- }
-
- touch.speedX = 0
- touch.speedY = 0
-
- touch.deltaX = 0
- touch.deltaY = 0
-
- var off = getOffset(touch.target)
- touch.offsetX = touch.pageX-off.left
- touch.offsetY = touch.pageY-off.top
-
-
- if (emit) targets[id].triggerHandler('draginit',[touch,e.originalEvent.traversing])
-
- }
-
- if (!touchActive) {
- $document.on(events.touch.move,touchMoveHandler)
- $document.on(events.touch.stop,touchStopHandler)
- touchActive = true
- }
-
- },
- touchMoveHandler = function(e){
-
- var oE = e.originalEvent
-
- for (let i in oE.changedTouches) {
- if (isNaN(i) || !oE.changedTouches[i]) continue
-
- var nFingers = 0
- for (let j in oE.touches) {
- if (oE.touches[j].target && oE.touches[j].target.isSameNode(oE.changedTouches[i].target)) {
- nFingers += 1
- }
- }
-
- var touch = oE.changedTouches[i],
- id = touch.identifier,
- speedFactor = nFingers * nFingers
-
- if (e.originalEvent.traversing) {
- targets[id] = $(document.elementFromPoint(touch.clientX, touch.clientY))
- }
-
- if (!targets[id]) continue
-
- touch.speedX = (touch.pageX - previousTouches[id].pageX) / speedFactor
- touch.speedY = (touch.pageY - previousTouches[id].pageY) / speedFactor
-
- touch.deltaX = touch.speedX + previousTouches[id].deltaX
- touch.deltaY = touch.speedY + previousTouches[id].deltaY
-
- touch.offsetX = previousTouches[id].offsetX+touch.speedX
- touch.offsetY = previousTouches[id].offsetY+touch.speedY
-
- if (e.originalEvent.traversing) {
- touch.traversing = true
- var previousTarget = document.elementFromPoint(previousTouches[id].clientX, previousTouches[id].clientY)
- if (targets[id][0]!=previousTarget) {
- var off = getOffset(targets[id][0])
- touch.offsetX = touch.pageX-off.left
- touch.offsetY = touch.pageY-off.top
- $(previousTarget).trigger('dragend',[touch,e.originalEvent.traversing])
- }
- e.preventDefault()
- if (oE.traversingContainer.contains(targets[id][0])) targets[id].triggerHandler('draginit',[touch,e.originalEvent.traversing])
-
- } else {
-
- targets[id].triggerHandler('drag',[touch,e.originalEvent.traversing])
-
- }
-
- previousTouches[id] = {
- deltaX:touch.deltaX,
- deltaY:touch.deltaY,
- offsetX:touch.offsetX,
- offsetY:touch.offsetY,
- speedX:touch.speedX,
- speedY:touch.speedY,
- pageX:touch.pageX,
- pageY:touch.pageY,
- clientX:touch.clientX,
- clientY:touch.clientY
- }
-
- }
-
- },
- touchStopHandler = function(e){
-
- var oE = e.originalEvent
-
- for (let i in oE.changedTouches) {
-
- if (isNaN(i) || !oE.changedTouches[i]) continue
-
- var touch = oE.changedTouches[i],
- id = touch.identifier
-
- $(targets[id]).trigger('dragend',[touch,e.originalEvent.traversing])
-
- delete previousTouches[id]
- delete targets[id]
-
- }
-
- if (oE.touches.length==0) {
- $document.off(events.touch.move,touchMoveHandler)
- $document.off(events.touch.stop,touchStopHandler)
- touchActive = false
- }
-
- }
-
- $this.on(events.touch.start + '.drag-osc',touchStartHandler)
-
-
- },
- teardown: function(){
- var $this = $(this)
- $this.off(events.touch.start + '.drag-osc')
- $this.off(events.mouse.start + '.drag-osc')
- $this.data('dragSetup','false')
- }
-
- }
-
-
-
-
-
-
-
-
- var makeEventTraversing = function(e){
- e.traversing=true
- if (!e.traversingContainer) e.traversingContainer=this
- }
-
-
- $.fn.enableTraversingGestures = function() {
-
- var self = this[0]
-
- var down = function(e){
- makeEventTraversing(e)
- self.addEventListener("mousemove", makeEventTraversing, true)
- self.addEventListener("touchmove", makeEventTraversing, true)
- self.addEventListener("mouseout", makeEventTraversing, true)
- document.addEventListener("mouseup",up,true)
- document.addEventListener("touchend",up,true)
- },
- up = function(e){
- makeEventTraversing(e)
- self.removeEventListener("mousemove", makeEventTraversing, true)
- self.removeEventListener("touchmove", makeEventTraversing, true)
- self.removeEventListener("mouseout", makeEventTraversing, true)
- document.removeEventListener("mouseup",up,true)
- document.removeEventListener("touchend",up,true)
- }
-
- self.addEventListener("mousedown", down, true)
- self.addEventListener("touchstart", down, true)
-
- this.on('draginit.traversing',()=>{})
-
- this.on('disableTraversingGestures',()=>{
- this.off('draginit.traversing')
- self.removeEventListener("mousedown", down, true)
- self.removeEventListener("touchstart", down, true)
- })
-
-
- return this
-
- }
-
- $.fn.disableTraversingGestures = function() {
-
- this.trigger('disableTraversingGestures')
-
- }
-
-
- var longTapTimer = false,
- clearLongTapTimer = function() {
- clearTimeout(longTapTimer)
- longTapTimer = false
- }
-
- $document.on('mousedown',function(e){
-
- if (e.originalEvent.sourceCapabilities && e.originalEvent.sourceCapabilities.firesTouchEvents) return
-
-
- if (e.button==2) {
-
- e.preventDefault()
- $(e.target).trigger('fake-right-click', e)
-
- } else {
-
- $(e.target).trigger('fake-click', e)
-
- }
-
- })
-
- $document.on(events.touch.start,function(e){
- var touch = e.originalEvent.changedTouches[0]
-
- $(e.target).trigger('fake-click', touch)
-
- if (!longTapTimer&&e.originalEvent.touches.length==1) {
- longTapTimer = setTimeout(function(){
- if (longTapTimer) {
- var off = getOffset(touch.target)
-
- touch.offsetX = touch.pageX-off.left
- touch.offsetY = touch.pageY-off.top
- $(e.originalEvent.changedTouches[0].target).trigger('fake-right-click',touch)
- }
- longTapTimer = false
- },600)
- } else {
- clearLongTapTimer()
- }
- })
-
- $document.on(events.touch.stop + ' ' + events.touch.move,function(e){
- clearLongTapTimer()
- })
-
- $document.on('contextmenu',function(){return false})
-
-})($)
diff --git a/src/browser/js/libs/jquery.resize.js b/src/browser/js/libs/jquery.resize.js
deleted file mode 100644
index d1b14fcc..00000000
--- a/src/browser/js/libs/jquery.resize.js
+++ /dev/null
@@ -1,84 +0,0 @@
-/* jquery.resize
- * based on jQuery resize event (@ "Cowboy" Ben Alman http://benalman.com/projects/jquery-resize-plugin/)
- * just lighter and faster
-*/
-(function($){
-
- var elems = []
-
- $.event.special.resize = {
- setup: function(data, namespaces, handler) {
-
- if (this===window) return false
-
- // Add this element to the list of internal elements to monitor.
- elems.push(this)
-
- },
- teardown: function() {
-
- if (this===window) return false
-
- // Remove this element from the list of internal elements to monitor.
- for (var i = elems.length - 1; i >= 0; i--) {
- if(elems[i] == this){
- elems.splice(i, 1)
- break
- }
- }
-
- },
- add: function(handleObj) {
- if (this===window) return false
-
- if (this.resizeHandler) {
-
- var handler = this.resizeHandler
-
- this.resizeHandler = function(){
- handler(...arguments)
- handleObj.handler(...arguments)
- }
-
- } else {
-
- this.resizeHandler = function(){
- handleObj.handler(...arguments)
- }
-
- }
- }
-
- }
-
- function checkResizes(){
- // Iterate over all elements to which the 'resize' event is bound.
- var resizedElems = []
- for (var i = elems.length - 1; i >= 0; i--) {
- var elem = elems[i]
-
- if (!document.contains(elem)) continue
-
- var style = window.getComputedStyle(elem),
- width = parseInt(style['width']) - parseInt(style['padding-left']) - parseInt(style['padding-right']),
- height = parseInt(style['height']) - parseInt(style['padding-top']) - parseInt(style['padding-bottom'])
-
- if (!width) continue
-
- // If element size has changed since the last time, update the element
- // data store and trigger the 'resize' event.
- if ( width != elem.resizedataw || height != elem.resizedatah ) {
- elem.resizedataw = width
- elem.resizedatah = height
- resizedElems.push(elem)
- }
- }
- for (var i = resizedElems.length - 1; i >= 0; i--) {
- resizedElems[i].resizeHandler(undefined, resizedElems[i].resizedataw, resizedElems[i].resizedatah)
- }
-
- }
-
- $(window).resize(checkResizes)
-
-})($)
diff --git a/src/browser/js/libs/source-map.min.js b/src/browser/js/libs/source-map.min.js
deleted file mode 100644
index 2e9876d8..00000000
--- a/src/browser/js/libs/source-map.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-// source-map
-// Copyright (c) 2009-2011, Mozilla Foundation and contributors
-// All rights reserved.
-!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.sourceMap=n():e.sourceMap=n()}(this,function(){return function(e){function n(t){if(r[t])return r[t].exports;var o=r[t]={exports:{},id:t,loaded:!1};return e[t].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=e,n.c=r,n.p="",n(0)}([function(e,n,r){n.SourceMapGenerator=r(1).SourceMapGenerator,n.SourceMapConsumer=r(7).SourceMapConsumer,n.SourceNode=r(10).SourceNode},function(e,n,r){function t(e){e||(e={}),this._file=i.getArg(e,"file",null),this._sourceRoot=i.getArg(e,"sourceRoot",null),this._skipValidation=i.getArg(e,"skipValidation",!1),this._sources=new s,this._names=new s,this._mappings=new a,this._sourcesContents=null}var o=r(2),i=r(4),s=r(5).ArraySet,a=r(6).MappingList;t.prototype._version=3,t.fromSourceMap=function(e){var n=e.sourceRoot,r=new t({file:e.file,sourceRoot:n});return e.eachMapping(function(e){var t={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(t.source=e.source,null!=n&&(t.source=i.relative(n,t.source)),t.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(t.name=e.name)),r.addMapping(t)}),e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&r.setSourceContent(n,t)}),r},t.prototype.addMapping=function(e){var n=i.getArg(e,"generated"),r=i.getArg(e,"original",null),t=i.getArg(e,"source",null),o=i.getArg(e,"name",null);this._skipValidation||this._validateMapping(n,r,t,o),null!=t&&(t=String(t),this._sources.has(t)||this._sources.add(t)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:n.line,generatedColumn:n.column,originalLine:null!=r&&r.line,originalColumn:null!=r&&r.column,source:t,name:o})},t.prototype.setSourceContent=function(e,n){var r=e;null!=this._sourceRoot&&(r=i.relative(this._sourceRoot,r)),null!=n?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[i.toSetString(r)]=n):this._sourcesContents&&(delete this._sourcesContents[i.toSetString(r)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},t.prototype.applySourceMap=function(e,n,r){var t=n;if(null==n){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');t=e.file}var o=this._sourceRoot;null!=o&&(t=i.relative(o,t));var a=new s,u=new s;this._mappings.unsortedForEach(function(n){if(n.source===t&&null!=n.originalLine){var s=e.originalPositionFor({line:n.originalLine,column:n.originalColumn});null!=s.source&&(n.source=s.source,null!=r&&(n.source=i.join(r,n.source)),null!=o&&(n.source=i.relative(o,n.source)),n.originalLine=s.line,n.originalColumn=s.column,null!=s.name&&(n.name=s.name))}var l=n.source;null==l||a.has(l)||a.add(l);var c=n.name;null==c||u.has(c)||u.add(c)},this),this._sources=a,this._names=u,e.sources.forEach(function(n){var t=e.sourceContentFor(n);null!=t&&(null!=r&&(n=i.join(r,n)),null!=o&&(n=i.relative(o,n)),this.setSourceContent(n,t))},this)},t.prototype._validateMapping=function(e,n,r,t){if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||n||r||t)&&!(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&r))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:r,original:n,name:t}))},t.prototype._serializeMappings=function(){for(var e,n,r,t,s=0,a=1,u=0,l=0,c=0,g=0,p="",h=this._mappings.toArray(),f=0,d=h.length;d>f;f++){if(n=h[f],e="",n.generatedLine!==a)for(s=0;n.generatedLine!==a;)e+=";",a++;else if(f>0){if(!i.compareByGeneratedPositionsInflated(n,h[f-1]))continue;e+=","}e+=o.encode(n.generatedColumn-s),s=n.generatedColumn,null!=n.source&&(t=this._sources.indexOf(n.source),e+=o.encode(t-g),g=t,e+=o.encode(n.originalLine-1-l),l=n.originalLine-1,e+=o.encode(n.originalColumn-u),u=n.originalColumn,null!=n.name&&(r=this._names.indexOf(n.name),e+=o.encode(r-c),c=r)),p+=e}return p},t.prototype._generateSourcesContent=function(e,n){return e.map(function(e){if(!this._sourcesContents)return null;null!=n&&(e=i.relative(n,e));var r=i.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)},t.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},t.prototype.toString=function(){return JSON.stringify(this.toJSON())},n.SourceMapGenerator=t},function(e,n,r){function t(e){return 0>e?(-e<<1)+1:(e<<1)+0}function o(e){var n=1===(1&e),r=e>>1;return n?-r:r}var i=r(3),s=5,a=1<>>=s,o>0&&(n|=l),r+=i.encode(n);while(o>0);return r},n.decode=function(e,n,r){var t,a,c=e.length,g=0,p=0;do{if(n>=c)throw new Error("Expected more digits in base 64 VLQ value.");if(a=i.decode(e.charCodeAt(n++)),-1===a)throw new Error("Invalid base64 digit: "+e.charAt(n-1));t=!!(a&l),a&=u,g+=a< =0&&e=n&&r>=e?e-n:e>=t&&o>=e?e-t+l:e>=i&&s>=e?e-i+c:e==a?62:e==u?63:-1}},function(e,n){function r(e,n,r){if(n in e)return e[n];if(3===arguments.length)return r;throw new Error('"'+n+'" is a required argument.')}function t(e){var n=e.match(m);return n?{scheme:n[1],auth:n[2],host:n[3],port:n[4],path:n[5]}:null}function o(e){var n="";return e.scheme&&(n+=e.scheme+":"),n+="//",e.auth&&(n+=e.auth+"@"),e.host&&(n+=e.host),e.port&&(n+=":"+e.port),e.path&&(n+=e.path),n}function i(e){var r=e,i=t(e);if(i){if(!i.path)return e;r=i.path}for(var s,a=n.isAbsolute(r),u=r.split(/\/+/),l=0,c=u.length-1;c>=0;c--)s=u[c],"."===s?u.splice(c,1):".."===s?l++:l>0&&(""===s?(u.splice(c+1,l),l=0):(u.splice(c,2),l--));return r=u.join("/"),""===r&&(r=a?"/":"."),i?(i.path=r,o(i)):r}function s(e,n){""===e&&(e="."),""===n&&(n=".");var r=t(n),s=t(e);if(s&&(e=s.path||"/"),r&&!r.scheme)return s&&(r.scheme=s.scheme),o(r);if(r||n.match(_))return n;if(s&&!s.host&&!s.path)return s.host=n,o(s);var a="/"===n.charAt(0)?n:i(e.replace(/\/+$/,"")+"/"+n);return s?(s.path=a,o(s)):a}function a(e,n){""===e&&(e="."),e=e.replace(/\/$/,"");for(var r=0;0!==n.indexOf(e+"/");){var t=e.lastIndexOf("/");if(0>t)return n;if(e=e.slice(0,t),e.match(/^([^\/]+:\/)?\/*$/))return n;++r}return Array(r+1).join("../")+n.substr(e.length+1)}function u(e){return e}function l(e){return g(e)?"$"+e:e}function c(e){return g(e)?e.slice(1):e}function g(e){if(!e)return!1;var n=e.length;if(9>n)return!1;if(95!==e.charCodeAt(n-1)||95!==e.charCodeAt(n-2)||111!==e.charCodeAt(n-3)||116!==e.charCodeAt(n-4)||111!==e.charCodeAt(n-5)||114!==e.charCodeAt(n-6)||112!==e.charCodeAt(n-7)||95!==e.charCodeAt(n-8)||95!==e.charCodeAt(n-9))return!1;for(var r=n-10;r>=0;r--)if(36!==e.charCodeAt(r))return!1;return!0}function p(e,n,r){var t=e.source-n.source;return 0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t||r?t:(t=e.generatedColumn-n.generatedColumn,0!==t?t:(t=e.generatedLine-n.generatedLine,0!==t?t:e.name-n.name))))}function h(e,n,r){var t=e.generatedLine-n.generatedLine;return 0!==t?t:(t=e.generatedColumn-n.generatedColumn,0!==t||r?t:(t=e.source-n.source,0!==t?t:(t=e.originalLine-n.originalLine,0!==t?t:(t=e.originalColumn-n.originalColumn,0!==t?t:e.name-n.name))))}function f(e,n){return e===n?0:e>n?1:-1}function d(e,n){var r=e.generatedLine-n.generatedLine;return 0!==r?r:(r=e.generatedColumn-n.generatedColumn,0!==r?r:(r=f(e.source,n.source),0!==r?r:(r=e.originalLine-n.originalLine,0!==r?r:(r=e.originalColumn-n.originalColumn,0!==r?r:f(e.name,n.name)))))}n.getArg=r;var m=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/,_=/^data:.+\,.+$/;n.urlParse=t,n.urlGenerate=o,n.normalize=i,n.join=s,n.isAbsolute=function(e){return"/"===e.charAt(0)||!!e.match(m)},n.relative=a;var v=function(){var e=Object.create(null);return!("__proto__"in e)}();n.toSetString=v?u:l,n.fromSetString=v?u:c,n.compareByOriginalPositions=p,n.compareByGeneratedPositionsDeflated=h,n.compareByGeneratedPositionsInflated=d},function(e,n,r){function t(){this._array=[],this._set=Object.create(null)}var o=r(4),i=Object.prototype.hasOwnProperty;t.fromArray=function(e,n){for(var r=new t,o=0,i=e.length;i>o;o++)r.add(e[o],n);return r},t.prototype.size=function(){return Object.getOwnPropertyNames(this._set).length},t.prototype.add=function(e,n){var r=o.toSetString(e),t=i.call(this._set,r),s=this._array.length;(!t||n)&&this._array.push(e),t||(this._set[r]=s)},t.prototype.has=function(e){var n=o.toSetString(e);return i.call(this._set,n)},t.prototype.indexOf=function(e){var n=o.toSetString(e);if(i.call(this._set,n))return this._set[n];throw new Error('"'+e+'" is not in the set.')},t.prototype.at=function(e){if(e>=0&&er||t==r&&s>=o||i.compareByGeneratedPositionsInflated(e,n)<=0}function o(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}var i=r(4);o.prototype.unsortedForEach=function(e,n){this._array.forEach(e,n)},o.prototype.add=function(e){t(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))},o.prototype.toArray=function(){return this._sorted||(this._array.sort(i.compareByGeneratedPositionsInflated),this._sorted=!0),this._array},n.MappingList=o},function(e,n,r){function t(e){var n=e;return"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,""))),null!=n.sections?new s(n):new o(n)}function o(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),t=a.getArg(n,"sources"),o=a.getArg(n,"names",[]),i=a.getArg(n,"sourceRoot",null),s=a.getArg(n,"sourcesContent",null),u=a.getArg(n,"mappings"),c=a.getArg(n,"file",null);if(r!=this._version)throw new Error("Unsupported version: "+r);t=t.map(String).map(a.normalize).map(function(e){return i&&a.isAbsolute(i)&&a.isAbsolute(e)?a.relative(i,e):e}),this._names=l.fromArray(o.map(String),!0),this._sources=l.fromArray(t,!0),this.sourceRoot=i,this.sourcesContent=s,this._mappings=u,this.file=c}function i(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}function s(e){var n=e;"string"==typeof e&&(n=JSON.parse(e.replace(/^\)\]\}'/,"")));var r=a.getArg(n,"version"),o=a.getArg(n,"sections");if(r!=this._version)throw new Error("Unsupported version: "+r);this._sources=new l,this._names=new l;var i={line:-1,column:0};this._sections=o.map(function(e){if(e.url)throw new Error("Support for url field in sections not implemented.");var n=a.getArg(e,"offset"),r=a.getArg(n,"line"),o=a.getArg(n,"column");if(r=0){var i=this._originalMappings[o];if(void 0===e.column)for(var s=i.originalLine;i&&i.originalLine===s;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var l=i.originalColumn;i&&i.originalLine===n&&i.originalColumn==l;)t.push({line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return t},n.SourceMapConsumer=t,o.prototype=Object.create(t.prototype),o.prototype.consumer=t,o.fromSourceMap=function(e){var n=Object.create(o.prototype),r=n._names=l.fromArray(e._names.toArray(),!0),t=n._sources=l.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file;for(var s=e._mappings.toArray().slice(),u=n.__generatedMappings=[],c=n.__originalMappings=[],p=0,h=s.length;h>p;p++){var f=s[p],d=new i;d.generatedLine=f.generatedLine,d.generatedColumn=f.generatedColumn,f.source&&(d.source=t.indexOf(f.source),d.originalLine=f.originalLine,d.originalColumn=f.originalColumn,f.name&&(d.name=r.indexOf(f.name)),c.push(d)),u.push(d)}return g(n.__originalMappings,a.compareByOriginalPositions),n},o.prototype._version=3,Object.defineProperty(o.prototype,"sources",{get:function(){return this._sources.toArray().map(function(e){return null!=this.sourceRoot?a.join(this.sourceRoot,e):e},this)}}),o.prototype._parseMappings=function(e,n){for(var r,t,o,s,u,l=1,p=0,h=0,f=0,d=0,m=0,_=e.length,v=0,C={},y={},A=[],S=[];_>v;)if(";"===e.charAt(v))l++,v++,p=0;else if(","===e.charAt(v))v++;else{for(r=new i,r.generatedLine=l,s=v;_>s&&!this._charIsMappingSeparator(e,s);s++);if(t=e.slice(v,s),o=C[t])v+=t.length;else{for(o=[];s>v;)c.decode(e,v,y),u=y.value,v=y.rest,o.push(u);if(2===o.length)throw new Error("Found a source, but no line and column");if(3===o.length)throw new Error("Found a source and line, but no column");C[t]=o}r.generatedColumn=p+o[0],p=r.generatedColumn,o.length>1&&(r.source=d+o[1],d+=o[1],r.originalLine=h+o[2],h=r.originalLine,r.originalLine+=1,r.originalColumn=f+o[3],f=r.originalColumn,o.length>4&&(r.name=m+o[4],m+=o[4])),S.push(r),"number"==typeof r.originalLine&&A.push(r)}g(S,a.compareByGeneratedPositionsDeflated),this.__generatedMappings=S,g(A,a.compareByOriginalPositions),this.__originalMappings=A},o.prototype._findMapping=function(e,n,r,t,o,i){if(e[r]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[r]);if(e[t]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[t]);return u.search(e,n,o,i)},o.prototype.computeColumnSpans=function(){for(var e=0;e=0){var o=this._generatedMappings[r];if(o.generatedLine===n.generatedLine){var i=a.getArg(o,"source",null);null!==i&&(i=this._sources.at(i),null!=this.sourceRoot&&(i=a.join(this.sourceRoot,i)));var s=a.getArg(o,"name",null);return null!==s&&(s=this._names.at(s)),{source:i,line:a.getArg(o,"originalLine",null),column:a.getArg(o,"originalColumn",null),name:s}}}return{source:null,line:null,column:null,name:null}},o.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return null==e}):!1},o.prototype.sourceContentFor=function(e,n){if(!this.sourcesContent)return null;if(null!=this.sourceRoot&&(e=a.relative(this.sourceRoot,e)),this._sources.has(e))return this.sourcesContent[this._sources.indexOf(e)];var r;if(null!=this.sourceRoot&&(r=a.urlParse(this.sourceRoot))){var t=e.replace(/^file:\/\//,"");if("file"==r.scheme&&this._sources.has(t))return this.sourcesContent[this._sources.indexOf(t)];if((!r.path||"/"==r.path)&&this._sources.has("/"+e))return this.sourcesContent[this._sources.indexOf("/"+e)]}if(n)return null;throw new Error('"'+e+'" is not in the SourceMap.')},o.prototype.generatedPositionFor=function(e){var n=a.getArg(e,"source");if(null!=this.sourceRoot&&(n=a.relative(this.sourceRoot,n)),!this._sources.has(n))return{line:null,column:null,lastColumn:null};n=this._sources.indexOf(n);var r={source:n,originalLine:a.getArg(e,"line"),originalColumn:a.getArg(e,"column")},o=this._findMapping(r,this._originalMappings,"originalLine","originalColumn",a.compareByOriginalPositions,a.getArg(e,"bias",t.GREATEST_LOWER_BOUND));if(o>=0){var i=this._originalMappings[o];if(i.source===r.source)return{line:a.getArg(i,"generatedLine",null),column:a.getArg(i,"generatedColumn",null),lastColumn:a.getArg(i,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}},n.BasicSourceMapConsumer=o,s.prototype=Object.create(t.prototype),s.prototype.constructor=t,s.prototype._version=3,Object.defineProperty(s.prototype,"sources",{get:function(){for(var e=[],n=0;n0?t-u>1?r(u,t,o,i,s,a):a==n.LEAST_UPPER_BOUND?t1?r(e,u,o,i,s,a):a==n.LEAST_UPPER_BOUND?u:0>e?-1:e}n.GREATEST_LOWER_BOUND=1,n.LEAST_UPPER_BOUND=2,n.search=function(e,t,o,i){if(0===t.length)return-1;var s=r(-1,t.length,e,t,o,i||n.GREATEST_LOWER_BOUND);if(0>s)return-1;for(;s-1>=0&&0===o(t[s],t[s-1],!0);)--s;return s}},function(e,n){function r(e,n,r){var t=e[n];e[n]=e[r],e[r]=t}function t(e,n){return Math.round(e+Math.random()*(n-e))}function o(e,n,i,s){if(s>i){var a=t(i,s),u=i-1;r(e,a,s);for(var l=e[s],c=i;s>c;c++)n(e[c],l)<=0&&(u+=1,r(e,u,c));r(e,u+1,c);var g=u+1;o(e,n,i,g-1),o(e,n,g+1,s)}}n.quickSort=function(e,n){o(e,n,0,e.length-1)}},function(e,n,r){function t(e,n,r,t,o){this.children=[],this.sourceContents={},this.line=null==e?null:e,this.column=null==n?null:n,this.source=null==r?null:r,this.name=null==o?null:o,this[u]=!0,null!=t&&this.add(t)}var o=r(1).SourceMapGenerator,i=r(4),s=/(\r?\n)/,a=10,u="$$$isSourceNode$$$";t.fromStringWithSourceMap=function(e,n,r){function o(e,n){if(null===e||void 0===e.source)a.add(n);else{var o=r?i.join(r,e.source):e.source;a.add(new t(e.originalLine,e.originalColumn,o,n,e.name))}}var a=new t,u=e.split(s),l=function(){var e=u.shift(),n=u.shift()||"";return e+n},c=1,g=0,p=null;return n.eachMapping(function(e){if(null!==p){if(!(c0&&(p&&o(p,l()),a.add(u.join(""))),n.sources.forEach(function(e){var t=n.sourceContentFor(e);null!=t&&(null!=r&&(e=i.join(r,e)),a.setSourceContent(e,t))}),a},t.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(e){this.add(e)},this);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);e&&this.children.push(e)}return this},t.prototype.prepend=function(e){if(Array.isArray(e))for(var n=e.length-1;n>=0;n--)this.prepend(e[n]);else{if(!e[u]&&"string"!=typeof e)throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);this.children.unshift(e)}return this},t.prototype.walk=function(e){for(var n,r=0,t=this.children.length;t>r;r++)n=this.children[r],n[u]?n.walk(e):""!==n&&e(n,{source:this.source,line:this.line,column:this.column,name:this.name})},t.prototype.join=function(e){var n,r,t=this.children.length;if(t>0){for(n=[],r=0;t-1>r;r++)n.push(this.children[r]),n.push(e);n.push(this.children[r]),this.children=n}return this},t.prototype.replaceRight=function(e,n){var r=this.children[this.children.length-1];return r[u]?r.replaceRight(e,n):"string"==typeof r?this.children[this.children.length-1]=r.replace(e,n):this.children.push("".replace(e,n)),this},t.prototype.setSourceContent=function(e,n){this.sourceContents[i.toSetString(e)]=n},t.prototype.walkSourceContents=function(e){for(var n=0,r=this.children.length;r>n;n++)this.children[n][u]&&this.children[n].walkSourceContents(e);for(var t=Object.keys(this.sourceContents),n=0,r=t.length;r>n;n++)e(i.fromSetString(t[n]),this.sourceContents[t[n]])},t.prototype.toString=function(){var e="";return this.walk(function(n){e+=n}),e},t.prototype.toStringWithSourceMap=function(e){var n={code:"",line:1,column:0},r=new o(e),t=!1,i=null,s=null,u=null,l=null;return this.walk(function(e,o){n.code+=e,null!==o.source&&null!==o.line&&null!==o.column?((i!==o.source||s!==o.line||u!==o.column||l!==o.name)&&r.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name}),i=o.source,s=o.line,u=o.column,l=o.name,t=!0):t&&(r.addMapping({generated:{line:n.line,column:n.column}}),i=null,t=!1);for(var c=0,g=e.length;g>c;c++)e.charCodeAt(c)===a?(n.line++,n.column=0,c+1===g?(i=null,t=!1):t&&r.addMapping({source:o.source,original:{line:o.line,column:o.column},generated:{line:n.line,column:n.column},name:o.name})):n.column++}),this.walkSourceContents(function(e,n){r.setSourceContent(e,n)}),{code:n.code,map:r}},n.SourceNode=t}])});
diff --git a/src/browser/scss/_vars.scss b/src/browser/scss/_vars.scss
deleted file mode 100644
index 991cd749..00000000
--- a/src/browser/scss/_vars.scss
+++ /dev/null
@@ -1,31 +0,0 @@
-:root {
-
- ////////////////////// COLOR SCHEME
-
- --color-text:rgba(255, 255, 255, .6);
- --color-text-fade:rgba(255, 255, 255, .4);
-
- --color-accent:rgba(82, 168, 255, 1);
- --color-grid: rgba(82, 168, 255, .1);
-
- --color-bg: rgb(25, 31, 42);
- --color-track: rgb(32, 41, 58);
- --color-fg: rgb(40, 49, 67);
- --color-raised: rgb(49, 63, 85);
-
- --color-light:rgba(255, 255, 255, .06);
-
- --color-white: white;
-
- ////////////////////// AUTO
-
- --color-custom:var(--color-accent);
-
- ////////////////////// MISC
-
- --nav-height:40rem;
- --sidepanel-size:300rem;
- --scrollbar-size:20rem;
-
- --grid-width:10;
-}
diff --git a/src/browser/scss/widgets/_inputs.scss b/src/browser/scss/widgets/_inputs.scss
deleted file mode 100644
index f4093822..00000000
--- a/src/browser/scss/widgets/_inputs.scss
+++ /dev/null
@@ -1,62 +0,0 @@
-.input-container {
- width: 100rem;
- height: 60rem;
- padding:1rem;
- .input {
-
- }
-}
-.widget {
- .input {
- display: flex;
- flex: 1 1 100%;
- background:transparent;
- color:var(--color-text-fade);
- overflow: hidden;
- text-align:center;
- padding:1rem;
- border: 1rem solid var(--color-bg);
- background: var(--color-track);
- font-size: 109%;
-
- input {
- display: block;
- flex:1;
- max-width: 100%;
- font: inherit;
- border:0;
- padding:0;
- background: transparent;
- color:var(--color-accent);
- border-radius: inherit;
- -webkit-appearance:none;
- text-align:inherit;
- vertical-align: top;
- letter-spacing: 1rem;
- &:focus {
- color:var(--color-custom);
- }
- }
- canvas {
- flex:1;
- max-width: 100%;
- }
- input + canvas {
- display: none;
- width: 0;
- }
-
-
- }
-
-}
-
-.panel:not(.tab) > .input-container {
- padding: 0rem;
- > .input {
- box-shadow: 0 0 0 1rem var(--color-fg);
- margin:1rem;
- outline: 1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
diff --git a/src/browser/scss/widgets/_plots.scss b/src/browser/scss/widgets/_plots.scss
deleted file mode 100644
index 8dd7d109..00000000
--- a/src/browser/scss/widgets/_plots.scss
+++ /dev/null
@@ -1,96 +0,0 @@
-.led-container, .rgbled-container {
- width:100rem;
- height:100rem;
- padding:1rem;
- .led {
- display: flex;
- flex-direction: row;
- flex: 1 1 100%;
- background: var(--color-track);
- border:1rem solid var(--color-bg);
- --opacity: 0;
- &:after {
- content:"";
- width:100%;
- height: 100%;
- background: var(--color-custom);
- border-radius: inherit;
- opacity: var(--opacity);
- }
- }
-}
-
-.rgbled-container .led {
- --opacity: 1;
-}
-
-.plot-container, .visualizer-container, .eq-container {
- height: 200rem;
- width: 200rem;
- padding:1rem;
- .plot {
- display: flex;
- flex-direction: row;
- flex: 1 1 100%;
- position: relative;
- background: var(--color-track);
- border:1rem solid var(--color-bg);
- }
- canvas {
- flex:1;
- image-rendering:pixelated;
- width: 100%;
- }
-}
-
-
-.meter-container {
- @extend .fader-container;
- --color-knob: transparent;
- .wrapper {
- pointer-events: none;
- }
-}
-
-.text-container {
- width: 100rem;
- height:60rem;
- flex-shrink: 0;
- padding:1rem;
- .text {
- flex: 1 1 100%;
- height:35rem;
- padding: 10rem;
- justify-content: center;
- display: flex;
- align-items: center;
- background: var(--color-track);
- color:var(--color-custom);
- border: 1rem solid var(--color-bg);
- &.vertical {
- transform: rotate(180deg);
- text-overflow: ellipsis;
- overflow: hidden;
- -webkit-writing-mode:vertical-lr;
- writing-mode:vertical-lr;
- }
- }
-}
-
-.panel:not(.tab) > .led-container,
-.panel:not(.tab) > .rgbled-container,
-.panel:not(.tab) > .text-container,
-.panel:not(.tab) > .visualizer-container,
-.panel:not(.tab) > .eq-container,
-.panel:not(.tab) > .plot-container {
- --color-border:transparent;
- padding: 0rem;
- .plot, .text, .led {
- padding: 0rem;
- margin: 1rem;
- background-clip: content-box;
- box-shadow: 0 0 0 1rem var(--color-fg);
- outline:1rem solid var(--color-light);
- border: 1rem solid var(--color-bg);
- }
-}
diff --git a/src/client/app/dom.js b/src/client/app/dom.js
new file mode 100644
index 00000000..5bc059a8
--- /dev/null
+++ b/src/client/app/dom.js
@@ -0,0 +1,107 @@
+var readyCallbacks = [],
+ initState = false
+
+module.exports = {
+
+ init: function() {
+
+ for (var i in readyCallbacks) {
+ readyCallbacks[i]()
+ }
+
+ initState = true
+
+ },
+
+ ready: function(callback) {
+ if (initState) {
+ callback()
+ } else {
+ readyCallbacks.push(callback)
+ }
+ },
+
+ dispatchEvent: function(element, name, data) {
+
+ var event = new CustomEvent(name, {
+ detail: data,
+ bubbles: true,
+ cancelable: true
+ })
+
+ element.dispatchEvent(event)
+
+ },
+
+ addEventListener: function(element, events, listener, capture) {
+
+ var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
+
+ for (var i in eventsAsObject) {
+
+ element.addEventListener(eventsAsObject[i], listener, capture)
+
+ }
+
+ },
+
+ get: function(a, b) {
+
+ var context = b ? a : document,
+ selector = b || a,
+ nodes
+
+ if (selector.indexOf('>') === 0) selector = ':scope ' + selector
+
+ if (selector.indexOf(' ') === -1 && selector.indexOf(',') === -1) {
+ if (selector.indexOf('#') === 0 && context === document) {
+ nodes = [document.getElementById(selector.substr(1, selector.length - 1))]
+ } else if (selector.indexOf('.') === 0) {
+ nodes = context.getElementsByClassName(selector.substr(1, selector.length - 1))
+ }
+ }
+
+ if (!nodes) nodes = context.querySelectorAll(selector)
+
+ return nodes.forEach ? nodes : [...nodes]
+
+ },
+
+ each: function(context, selector, callback) {
+
+ var nodes = module.exports.get(context, selector)
+
+ nodes.forEach(callback)
+
+ return nodes
+
+ },
+
+ index: function(element) {
+ var parent = element.parentNode
+ return parent ? Array.prototype.indexOf.call(parent.children, element) : -1
+ },
+
+ offset: function(element) {
+
+ var offsetLeft = 0,
+ offsetTop = 0
+
+ if (element) {
+ do {
+ if (!isNaN(element.offsetLeft)) {
+ offsetLeft += element.offsetLeft - element.scrollLeft
+ }
+ if (!isNaN(element.offsetTop)) {
+ offsetTop += element.offsetTop - element.scrollTop
+ }
+ } while ((element = element.offsetParent))
+ }
+
+ return {
+ left: offsetLeft,
+ top: offsetTop
+ }
+ }
+
+}
diff --git a/src/client/app/editor/context-menu.js b/src/client/app/editor/context-menu.js
new file mode 100644
index 00000000..7264ea96
--- /dev/null
+++ b/src/client/app/editor/context-menu.js
@@ -0,0 +1,365 @@
+var {updateWidget} = require('./data-workers'),
+ {categories} = require('../widgets/'),
+ widgetManager = require('../managers/widgets'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ {icon} = require('../ui/utils'),
+ editor = require('./'),
+ locales = require('../locales')
+
+
+var multiSelectKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+
+class ContextMenu {
+
+ constructor(){
+
+ this.menu = null
+ this.event = 'fast-click'
+ this.root = document.body
+
+ }
+
+ open(e, actions, parent) {
+
+ var menu = html``
+
+ for (let action of actions) {
+
+ if (Array.isArray(action.action)) {
+
+ let item = html`${raw(action.label)}
`
+
+ menu.appendChild(item)
+
+ this.open(e, action.action, item)
+
+
+ } else {
+
+ let item = html`${raw(action.label)}
`
+
+ menu.appendChild(item)
+
+ item.addEventListener(this.event, (e)=>{
+ e.detail.preventOriginalEvent = true
+ action.action()
+ this.close()
+ })
+
+ }
+
+ }
+
+ if (parent) parent.appendChild(menu)
+
+ if (!parent) {
+
+ this.menu = menu
+
+ this.root.appendChild(menu)
+
+ DOM.each(menu, '.item', (item)=>{
+ item.addEventListener('mouseenter', ()=>{
+ DOM.each(item.parentNode, '.focus', (focused)=>{
+ focused.classList.remove('focus')
+ })
+ item.classList.add('focus')
+ })
+ item.addEventListener('mouseleave', ()=>{
+ if (!item.classList.contains('has-sub')) item.classList.remove('focus')
+ })
+ })
+
+ menu.style.top = e.pageY + 'px'
+ menu.style.left = e.pageX + 'px'
+
+ this.correctPosition(menu)
+
+ DOM.each(menu, '.context-menu', (m)=>{
+ this.correctPosition(m, m.parentNode)
+ })
+
+ }
+
+
+ }
+
+ close() {
+
+ if (this.menu) {
+
+ this.menu.parentNode.removeChild(this.menu)
+ this.menu = null
+
+ }
+
+ }
+
+ correctPosition(menu, parent) {
+
+ var position = DOM.offset(menu),
+ width = menu.offsetWidth,
+ height = menu.offsetHeight,
+ totalWidth = this.root.offsetWidth,
+ totalHeight = this.root.offsetHeight
+
+ if (width + position.left > totalWidth) {
+ menu.style.right = parent ? '100%' : '0'
+ menu.style.left = 'auto'
+ menu.style.marginRight = '2rem'
+ }
+
+ if (height + position.top > totalHeight) {
+ menu.style.top = 'auto'
+ menu.style.bottom = '2rem'
+ }
+
+ }
+
+}
+
+var contextMenu = new ContextMenu()
+
+var handleClick = function(event) {
+
+ if (!EDITING) return
+
+ if (contextMenu.menu && !contextMenu.menu.contains(event.target)) contextMenu.close()
+
+ if (!event.detail[multiSelectKey] && event.type !== 'fast-right-click' && (
+ event.target.classList.contains('ui-resizable-handle') ||
+ event.target.classList.contains('ui-draggable-handle') ||
+ event.target.id === 'open-toggle'
+ )) { return }
+
+ var eventData = event.detail,
+ widget = widgetManager.getWidgetByElement(eventData.target, ':not(.not-editable)')
+
+ if (!widget) return
+
+ // if the widget is not already selected
+ if (!widget.container.classList.contains('editing')) {
+ // add a flag to the original event to prevent draginit
+ // and prevent any further fast-click (ie input focus)
+ eventData.capturedByEditor = true
+ event.capturedByEditor = true
+ }
+
+
+ if (event.type !== 'fast-right-click') {
+ editor.select(widget, {multi: event.detail[multiSelectKey]})
+ }
+
+ // right-click menu
+ if (event.type !== 'fast-right-click') return
+
+ if (!event.detail.shiftKey && !event.detail[multiSelectKey] && editor.selectedWidgets.length <= 1) {
+ editor.select(widget)
+ }
+
+ if (!editor.selectedWidgets.length) return
+
+ var index = editor.selectedWidgets.map((w)=>DOM.index(w.container)).sort((a,b)=>{return b-a}),
+ data = editor.selectedWidgets.map((w)=>w.props),
+ type = editor.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
+ parent = editor.selectedWidgets[0].parent,
+ actions = []
+
+ // case root: only "add tab" option
+ if (parent === widgetManager) {
+ actions.push({
+ label: icon('plus') + ' ' + locales('editor_addtab'),
+ action: ()=>{
+ data[0].tabs.push({})
+
+ var indexes = {addedIndexes: [data[0].tabs.length -1]}
+ updateWidget(editor.selectedWidgets[0], indexes)
+ editor.pushHistory(indexes)
+ }
+ })
+ contextMenu.open(eventData, actions)
+
+ return
+ }
+
+ // case !root
+
+ var clickX = Math.round((eventData.offsetX + eventData.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
+ clickY = Math.round((eventData.offsetY + eventData.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
+
+ actions.push({
+ label: icon('expand') + ' ' + locales('editor_editparent'),
+ action: ()=>{
+ editor.select(parent)
+ }
+ })
+
+ if (type === 'widget') {
+
+ actions.push({
+ label: icon('copy') + ' ' + locales('editor_copy'),
+ action: editor.copyWidget.bind(editor)
+ })
+
+ actions.push({
+ label: icon('cut') + ' ' + locales('editor_cut'),
+ action: editor.cutWidget.bind(editor)
+ })
+
+ var wrapActions = []
+ for (let c of categories.Containers) {
+ if (c === 'clone') continue
+ wrapActions.push({
+ label: c,
+ action: ()=>{
+ var wrap = {type: c, widgets:[], label: c === 'modal' ? 'auto' : false}
+
+ wrap.widgets = data
+
+ var minTop = Math.min(...data.map(x=>isNaN(x.top) ? x.top == 'auto' ? 0 : Infinity : x.top))
+ var minLeft = Math.min(...data.map(x=>isNaN(x.left) ? x.left == 'auto' ? 0 : Infinity : x.left))
+
+ wrap.top = minTop === Infinity ? data[0].top : minTop
+ wrap.left= minLeft === Infinity ? data[0].left : minLeft
+
+ for (var w of wrap.widgets) {
+ if (!isNaN(w.top)) w.top = Math.max(w.top - minTop, 0)
+ if (!isNaN(w.left)) w.left = Math.max(w.left - minLeft, 0)
+ }
+
+ var i
+ for (i of index) {
+ parent.props.widgets.splice(i,1)
+ }
+
+ parent.props.widgets = parent.props.widgets.slice(0, i).concat(wrap, parent.props.widgets.slice(i, parent.props.widgets.length))
+
+ editor.select(updateWidget(parent, {preventSelect: true, removedIndexes: index, addedIndexes: [i]}))
+ editor.pushHistory({removedIndexes: index, addedIndexes: [i]})
+
+ }
+ })
+ }
+
+ actions.push({
+ label: icon('box') + ' ' + locales('editor_wrap'),
+ action: wrapActions
+ })
+
+ }
+
+
+ if (data.length == 1 && (!data[0].tabs || !data[0].tabs.length) && (data[0].widgets)) {
+
+ if (editor.clipboard !== null) {
+
+ var pasteActions = []
+
+ pasteActions.push({
+ label: icon('paste') + ' ' + locales('editor_paste'),
+ action: ()=>{
+ editor.pasteWidget(clickX, clickY)
+ }
+ })
+ pasteActions.push({
+ label: icon('plus-square') + ' ' + locales('editor_pasteindent'),
+ action: ()=>{
+ editor.pasteWidget(clickX, clickY, true)
+ }
+ })
+
+ if (editor.idClipboard && widgetManager.getWidgetById(editor.idClipboard).length) {
+ pasteActions.push({
+ label: icon('clone') + ' ' + locales('editor_clone'),
+ action: ()=>{
+ editor.pasteWidgetAsClone(clickX, clickY)
+ }
+ })
+ }
+
+ actions.push({
+ label: icon('paste') + ' ' + locales('editor_paste'),
+ action: pasteActions
+ })
+
+ }
+
+
+ var addActions = []
+
+ for (let category in categories) {
+
+ var catActions = []
+
+ for (let t in categories[category]) {
+
+ let type = categories[category][t]
+
+ catActions.push({
+
+ label: type,
+ action: ()=>{
+
+ var newData = {type: type}
+
+ if (!eventData.target.classList.contains('tablink')) {
+ newData.top = clickY
+ newData.left= clickX
+ }
+
+ data[0].widgets = data[0].widgets || []
+ data[0].widgets.push(newData)
+
+ var indexes = {addedIndexes: [data[0].widgets.length -1]}
+ updateWidget(editor.selectedWidgets[0], indexes)
+ editor.pushHistory(indexes)
+
+ }
+ })
+
+ }
+
+ addActions.push({
+ label: category,
+ action: catActions
+ })
+
+ }
+
+ actions.push({
+ label: icon('plus') + ' ' + locales('editor_addwidget'),
+ action: addActions
+ })
+
+ }
+
+ if (data.length == 1 && (!data[0].widgets || !data[0].widgets.length) && (data[0].tabs)) {
+
+ actions.push({
+ label: icon('plus') + ' ' + locales('editor_addtab'),
+ action: ()=>{
+ data[0].tabs = data[0].tabs || []
+ data[0].tabs.push({})
+
+ var indexes = {addedIndexes: [data[0].tabs.length -1]}
+ updateWidget(editor.selectedWidgets[0], indexes)
+ editor.pushHistory(indexes)
+
+ }
+ })
+
+ }
+
+ actions.push({
+ label: icon('trash') + ' ' + locales('editor_delete'),
+ action: editor.deleteWidget.bind(editor)
+ })
+
+ contextMenu.open(eventData, actions)
+
+}
+
+document.addEventListener('fast-right-click', handleClick, true)
+document.addEventListener('fast-click', handleClick, true)
diff --git a/src/client/app/editor/data-workers.js b/src/client/app/editor/data-workers.js
new file mode 100644
index 00000000..45b6d9c9
--- /dev/null
+++ b/src/client/app/editor/data-workers.js
@@ -0,0 +1,243 @@
+var widgetManager = require('../managers/widgets'),
+ resize = require('../events/resize'),
+ stateManager = require('../managers/state'),
+ parser = require('../parser'),
+ Panel,
+ sidepanel,
+ editor,
+ scrollState = {},
+ sidepanelScroll
+
+DOM.ready(()=>{
+ sidepanel = DOM.get('#sidepanel')[0]
+})
+
+function updateWidget(widget, options={}) {
+
+ if (options.changedProps) {
+ // alternate routine for small edits
+ var propNames = options.changedProps,
+ propValues = propNames.map(x => widget.props[x]),
+ linkedProps = []
+
+ Object.values(widget.nestedLinkedProps).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(widget.linkedProps).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(widget.linkedPropsValue).forEach(l => linkedProps = linkedProps.concat(l))
+ Object.values(widget.oscReceivers).forEach(r => linkedProps = linkedProps.concat(r.propNames))
+
+ if (
+ // if non dynamic props have changed, skip this and use rebuild routine
+ !propNames.some(n => !widget.isDynamicProp(n))
+ ) {
+
+ var edited = widget.updateProps(options.changedProps, null) || widget
+
+ if (
+ // if prop/osc listeners have changed (@{} / OSC{})
+ // refresh the widget's props cache and update linked props bindings
+ propValues.some(x => typeof x === 'string' && x.match(/OSC\{|@\{/))
+ || propNames.some(n => linkedProps.includes(n))
+ ) {
+ widget.createPropsCache()
+ }
+
+ if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
+ editor.select(edited)
+ }
+
+ return edited
+
+ }
+
+ }
+
+
+ var reuseChildren = options.reuseChildren !== false && widget instanceof Panel
+
+ // save state
+ if (stateManager.queueCounter === 0) {
+ sidepanelScroll = sidepanel.scrollTop
+ scrollState = {}
+ }
+ stateManager.incrementQueue()
+ var toSave = [widget]
+ if (!reuseChildren) {
+ toSave = toSave.concat(widget.getAllChildren())
+ }
+ for (let w of toSave) {
+ if (widgetManager.widgets[w.hash]) {
+ let id = w.getProp('id'),
+ value = w.getValue(),
+ valueProp = w.getProp('value')
+
+ stateManager.pushValueState(id, value)
+ if (valueProp !== '' && valueProp !== undefined) stateManager.pushValueOldProp(id, valueProp)
+ }
+ if (widgetManager.scrollingWidgets.indexOf(w.hash) > -1 && w.scroll) {
+ var s = w.scroll()
+ if (s[0] !== 0 || s[1] !== 0) {
+ scrollState[w.getProp('id')] = s
+ }
+ }
+ }
+
+ var children = undefined,
+ removedChildren = []
+
+ if (reuseChildren) {
+ children = [...widget.children]
+ if (options.removedIndexes) {
+ options.removedIndexes = options.removedIndexes.sort((a, b) => b - a)
+ for (let i of options.removedIndexes) {
+ removedChildren.push(children.splice(i, 1)[0])
+ }
+ }
+ if (options.addedIndexes) {
+ options.addedIndexes = options.addedIndexes.sort((a, b) => a - b)
+ for (let i of options.addedIndexes) {
+ children.splice(i, 0, null)
+ }
+ }
+
+ }
+
+ // get widget's index
+ var index = widget.parent.children.indexOf(widget)
+
+ // remove old widgets
+ var removedWidgets = reuseChildren ?
+ removedChildren.map(x => x.getAllChildren().concat(x)).concat(widget) :
+ widget.getAllChildren().concat(widget)
+
+ widgetManager.removeWidgets(removedWidgets)
+
+ // create new widget
+ var newWidget = parser.parse({
+ data: widget.props,
+ parent: widget.parent,
+ parentNode: widget.parentNode,
+ reCreateOptions: options.reCreateOptions,
+ children: children,
+ index: index
+ })
+
+
+ newWidget.container.parentNode.replaceChild(newWidget.container, widget.container)
+
+ if (newWidget.getProp('type') === 'tab') newWidget.parent.trigger('tab-created', {widget: widget})
+ if (newWidget.getProp('id') === 'root') DOM.get('.editor-root')[0].setAttribute('data-widget', newWidget.hash)
+
+
+ if (reuseChildren && !(newWidget instanceof Panel)) {
+ // remove remaining children if widget is not a container anymore
+ widgetManager.removeWidgets(widget.getAllChildren())
+ }
+
+ if (reuseChildren) {
+ // children don't listen to their parent's 'widget-created' event
+ // so we have to let them know it's been updated
+ widgetManager.trigger('prop-changed', {
+ id: newWidget.getProp('id'),
+ props: [],
+ widget: newWidget,
+ options: {}
+ })
+ }
+
+ resize.check(newWidget.container)
+
+ // restore state
+ stateManager.decrementQueue()
+ if (stateManager.queueCounter === 0) {
+ sidepanel.scrollTop = sidepanelScroll
+ for (let id in scrollState) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ if (w.scroll) w.scroll(scrollState[id])
+ }
+ }
+ }
+
+ if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
+ editor.select(newWidget)
+ }
+
+ return newWidget
+
+}
+
+
+var fakeStore = {}
+
+var incrementWidget = function(data, root){
+
+ if (!data) return
+
+ if (root !== false) {
+ fakeStore = {
+ id:[],
+ address:[]
+ }
+ }
+
+ var id = data.id,
+ address = data.address
+
+ if (id && address == '/'+id) {
+
+ data.address = 'auto'
+
+ } else if (address){
+ var addressref
+ while (fakeStore.address.indexOf(address) != -1 || widgetManager.getWidgetByAddress(addressref).length) {
+ address = address.replace(/([0-9]*)$/,function(m){
+ var n = parseInt(m)+1
+ n = isNaN(n)?1:n
+ return n
+ })
+ addressref = widgetManager.createAddressRef(null, data.preArgs,address)
+ }
+
+ fakeStore.address.push(address)
+
+ data.address = address
+
+ }
+
+ if (id) {
+ while (fakeStore.id.indexOf(id) != -1 || widgetManager.getWidgetById(id).length) {
+ id = id.replace(/([0-9]*)$/,function(m){
+ var n = parseInt(m)+1
+ n = isNaN(n)?1:n
+ return n
+ })
+ }
+
+ fakeStore.id.push(id)
+
+ data.id = id
+
+ }
+
+ if (data.widgets && data.widgets.length) {
+ for (let i in data.widgets) {
+ data.widgets[i] = incrementWidget(data.widgets[i], false)
+ }
+ }
+
+ if (data.tabs && data.tabs.length) {
+ for (let i in data.tabs) {
+ data.tabs[i] = incrementWidget(data.tabs[i], false)
+ }
+ }
+
+ return data
+
+}
+
+module.exports = {
+ updateWidget:updateWidget,
+ incrementWidget:incrementWidget
+}
+
+editor = require('./')
+Panel = require('../widgets/containers/panel')
diff --git a/src/client/app/editor/diff.js b/src/client/app/editor/diff.js
new file mode 100644
index 00000000..8f2902a9
--- /dev/null
+++ b/src/client/app/editor/diff.js
@@ -0,0 +1,32 @@
+module.exports = {
+
+ diff: require('jsondiffpatch'),
+
+ diffToWidget: function(widget, diff) {
+
+ // traverse a diff patch and the associated widget
+ // to return the first node (widget and sub-patch) with actual changes
+
+ var children = diff.tabs || diff.widgets
+
+ if (children) {
+ var childrenKeys = Object.keys(children),
+ deletedChildren = childrenKeys.filter(x => typeof x === 'string' && x.match(/_[0-9]+/)),
+ changedChildren = childrenKeys.filter(x => !isNaN(x))
+ }
+
+ if (
+ !children ||
+ Array.isArray(children) || // 'tabs' or 'widgets' property created
+ deletedChildren.length || // 'tabs' or 'widgets' property created
+ changedChildren.length !== 1 || // children reordered (or same property edited in multiple widgets, but case ignored)
+ Array.isArray(children[changedChildren[0]]) // child item created
+ ) {
+ return [widget, diff]
+ }
+
+ return module.exports.diffToWidget(widget.children[changedChildren[0]], children[changedChildren[0]])
+
+ }
+
+}
diff --git a/src/client/app/editor/edit-field.js b/src/client/app/editor/edit-field.js
new file mode 100644
index 00000000..3236d3f3
--- /dev/null
+++ b/src/client/app/editor/edit-field.js
@@ -0,0 +1,233 @@
+var widgetCategories = require('../widgets/').categories,
+ {updateWidget} = require('./data-workers'),
+ widgetManager = require('../managers/widgets'),
+ {deepCopy} = require('../utils'),
+ {icon, Popup} = require('../ui/utils'),
+ locales = require('../locales'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+module.exports = function editField(editor, widget, propName, defaultValue){
+
+ let dynamic = widget.isDynamicProp(propName),
+ disabled = widget.disabledProps.indexOf(propName) > -1,
+ error = widget.errors[propName]
+
+ let field = html`
+
+ ${propName}
+
+ `
+
+ let input
+
+ if (propName !== 'widgets' && propName !== 'tabs') {
+
+ if (propName == 'type') {
+
+ if (widget.props.type == 'tab' || widget.props.type == 'root') {
+ field.classList.add('disabled')
+ field.appendChild(html``)
+ return field
+ }
+
+ input = html` `
+
+ for (let category in widgetCategories) {
+ var optGroup = html``
+ for (let type of widgetCategories[category]) {
+ optGroup.appendChild(html`
+
+ ${type}
+
+ `)
+ }
+ input.appendChild(optGroup)
+ }
+
+ var wrapper = html`
`
+ wrapper.appendChild(input)
+ field.appendChild(wrapper)
+
+
+ } else {
+
+ var value = typeof widget.props[propName] !== 'string' ?
+ JSON.stringify(widget.props[propName], null, ' ').replace(/\n\s\s\s\s/g, ' ').replace(/\n\s\s(\}|\])/g, ' $1') : widget.props[propName]
+
+ input = html``
+
+ DOM.addEventListener(input, ['input', 'focus'], ()=>{
+ input.setAttribute('rows',0)
+ input.setAttribute('rows', input.value.split('\n').length)
+ })
+
+ input.addEventListener('keydown', (e)=>{
+ if (e.keyCode == 13 && !e.shiftKey) {
+ e.preventDefault()
+ DOM.dispatchEvent(input, 'change')
+ }
+ })
+
+ if (defaultValue.type.includes('boolean')) {
+
+ let toggle = html`
+
+ ${raw(icon('check'))}
+
+ `
+
+ toggle.addEventListener('click', ()=>{
+ input.value = !widget.getProp(propName)
+ DOM.dispatchEvent(input, 'change')
+ })
+
+ field.appendChild(toggle)
+
+ }
+
+ field.appendChild(input)
+
+ }
+ var lock
+ var onChange = ()=>{
+
+ if (lock) return
+ lock = true
+
+ input.blur()
+
+ var v
+
+ try {
+ v = JSON.parseFlex(input.value)
+ } catch(err) {
+ v = input.value
+ }
+
+ var newWidgets = []
+ for (var w of editor.selectedWidgets) {
+ w.props[propName] = v !== '' ? v : deepCopy(defaultValue.value)
+ newWidgets.push(updateWidget(w, {changedProps: [propName], preventSelect: editor.selectedWidgets.length > 1}))
+ }
+ editor.pushHistory()
+ if (newWidgets.length > 1) editor.select(newWidgets)
+
+ lock = false
+
+ }
+
+ input.addEventListener('change', onChange)
+
+
+ } else if (
+ (propName === 'widgets' && (!widget.props.tabs ||! widget.props.tabs.length)) ||
+ (propName === 'tabs' && (!widget.props.widgets ||! widget.props.widgets.length))
+ ) {
+
+ if (editor.selectedWidgets.length > 1) return
+
+ var list = html``
+
+ for (var i in widget.props[propName]) {
+
+ list.appendChild(html`
+
+ ${widget.props[propName][i].id}
+ ${raw(icon('times'))}
+
+ `)
+
+ }
+
+ list.appendChild(html`
+ ${raw(icon('plus'))}
+ `)
+
+
+ list.addEventListener('click', (e)=>{
+
+ switch (e.target.getAttribute('data-action')) {
+
+ case 'select':
+ editor.select(widgetManager.getWidgetByElement(DOM.get(propName === 'widgets' ? widget.widget : widget.wrapper, '> .widget')[DOM.index(e.target.closest('li'))]))
+ break
+
+ case 'remove':
+ var index = DOM.index(e.target.closest('li'))
+ widget.props[propName].splice(index,1)
+ updateWidget(widget, {removedIndexes: [index] })
+ editor.pushHistory({removedIndexes: [index] })
+ break
+
+ case 'add':
+ widget.props[propName] = widget.props[propName] || []
+ widget.props[propName].push({})
+ updateWidget(widget, {addedIndexes: [widget.props[propName].length -1] })
+ editor.pushHistory({addedIndexes: [widget.props[propName].length -1] })
+ break
+
+ }
+
+ })
+
+ var $list = $(list)
+ $list.sortable({
+ items: '.sortables',
+ placeholder: 'sortable-placeholder btn small',
+ start:function(){$(this).sortable( 'refreshPositions' )},
+ update: function(e,ui){
+ var oldindex = $(ui.item).attr('data-index')
+ var index = $(ui.item).index()
+
+ widget.props[propName].splice(index, 0, widget.props[propName].splice(oldindex, 1)[0])
+ updateWidget(widget, {removedIndexes: [index, oldindex], addedIndexes: [index, oldindex]})
+ editor.pushHistory({removedIndexes: [index, oldindex], addedIndexes: [index, oldindex]})
+ }
+ })
+
+ input = html`
`
+ input.appendChild(list)
+ field.appendChild(input)
+
+ }
+
+ var label = DOM.get(field, 'label')[0]
+ label.addEventListener('fast-click', ()=>{
+
+ var htmlHelp = Array.isArray(defaultValue.help) ? defaultValue.help.join(' ').replace(/ -/g, '-') : defaultValue.help
+ htmlHelp = htmlHelp ? html`${raw(htmlHelp.replace(/`([^`]*)`/g, '$1'))}
` : ''
+
+
+ var htmlError = error ? html`${error}
` : '',
+ computedValue = propName !== 'tabs' && propName !== 'widgets' ? widget.getProp(propName) : ['...']
+
+ if (typeof computedValue === 'string') {
+ try {
+ computedValue = JSON.stringify(JSON.parse(computedValue), null, ' ')
+ } catch(e) {}
+ } else {
+ computedValue = JSON.stringify(computedValue, null, ' ')
+ }
+
+ new Popup({closable: true, title: html`${propName} `, content: html`
+
+
+
Type: ${defaultValue.type}
+
Default: ${JSON.stringify(defaultValue.value)}
+
Dynamic: ${dynamic ? 'true' : 'false'}
+
Computed: ${computedValue}
+
+ ${htmlError}
+
+ ${htmlHelp}
+
+ `})
+ })
+
+ if (input) {
+ return field
+ }
+
+
+}
diff --git a/src/client/app/editor/index.js b/src/client/app/editor/index.js
new file mode 100644
index 00000000..af32205b
--- /dev/null
+++ b/src/client/app/editor/index.js
@@ -0,0 +1,837 @@
+var {widgets} = require('../widgets/'),
+ editField = require('./edit-field'),
+ {updateWidget, incrementWidget} = require('./data-workers'),
+ keyboardJS = require('keyboardjs'),
+ {diff, diffToWidget} = require('./diff'),
+ widgetManager = require('../managers/widgets'),
+ {deepCopy} = require('../utils'),
+ macOs = (navigator.platform || '').match('Mac'),
+ SelectArea = require('./select-area'),
+ html = require('nanohtml'),
+ sessionManager
+
+
+const HISTORY_SIZE = 50
+
+var Editor = class Editor {
+
+ constructor() {
+
+ this.wrapper = html`
+
+ `
+
+ this.form = DOM.get(this.wrapper, '.form')[0]
+ this.form.addEventListener('fast-click', (e)=>{
+ if (e.target.classList.contains('separator')) {
+ var name = e.target.getAttribute('data-name'),
+ foldedIndex = this.foldedCategories.indexOf(name)
+ e.target.parentNode.classList.toggle('folded', foldedIndex < 0)
+ if (foldedIndex > -1) {
+ this.foldedCategories.splice(foldedIndex, 1)
+ } else {
+ this.foldedCategories.push(name)
+ }
+
+ }
+ })
+
+
+ this.defaults = {}
+ for (var k in widgets) {
+ this.defaults[k] = widgets[k].defaults()
+ }
+
+ this.selectedWidgets = []
+
+ this.clipboard = null
+ this.idClipboard = null
+
+ this.enabled = false
+ this.enabledOnce = false
+ window.onbeforeunload = ()=>{
+ if (this.enabledOnce) return true
+ }
+
+
+ this.history = []
+ this.historyState = -1
+ this.historySession = null
+
+ this.foldedCategories = []
+
+ this.mousePosition = {x:0, y:0}
+ this.mouveMoveHandler = this.mouseMove.bind(this)
+
+ keyboardJS.withContext('editing', ()=>{
+ keyboardJS.bind('mod + z', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.undo()
+ })
+ keyboardJS.bind(['mod + y', 'mod + shift + z'], (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.redo()
+ })
+ keyboardJS.bind('mod + c', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.copyWidget()
+ })
+ keyboardJS.bind('mod + x', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.cutWidget()
+ })
+ keyboardJS.bind('mod + v', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.pasteWidget(this.mousePosition.x, this.mousePosition.y, false)
+ })
+ keyboardJS.bind('mod + shift + v', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.pasteWidget(this.mousePosition.x, this.mousePosition.y, true)
+ })
+ keyboardJS.bind(macOs ? 'backspace' : 'delete', (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ this.deleteWidget()
+ })
+ keyboardJS.bind(['alt + up', 'alt + down', 'alt + right', 'alt + left'], (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ if (!this.selectedWidgets.length) return
+
+ if (this.selectedWidgets[0].props.height === undefined && e.key.match(/Arrow(Up|Down)/)) return
+ if (this.selectedWidgets[0].props.width === undefined && e.key.match(/Arrow(Left|Right)/)) return
+
+ var deltaW = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
+ deltaH = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
+
+ if (e.shiftKey) {
+ deltaW *= 5
+ deltaH *= 5
+ }
+
+ this.resizeWidget(deltaW, deltaH)
+ })
+ keyboardJS.bind(['up', 'down', 'right', 'left'], (e)=>{
+ if (e.target.classList.contains('no-keybinding')) return
+ if (!this.selectedWidgets.length) return
+
+ if (this.selectedWidgets[0].props.top === undefined && e.key.match(/Arrow(Up|Down)/)) return
+ if (this.selectedWidgets[0].props.left === undefined && e.key.match(/Arrow(Left|Right)/)) return
+
+ var deltaX = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
+ deltaY = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
+
+ if (e.shiftKey) {
+ deltaX *= 5
+ deltaY *= 5
+ }
+
+ this.moveWidget(deltaX, deltaY)
+ })
+ keyboardJS.bind('mod + shift + a', (e)=>{
+ if (!this.selectedWidgets.length) return
+ if (e.target.classList.contains('no-keybinding')) return
+ this.unselect()
+ this.selectedWidgets = []
+ })
+ keyboardJS.bind('mod + a', (e)=>{
+ if (!this.selectedWidgets.length) return
+ if (e.target.classList.contains('no-keybinding')) return
+
+ var curWidget = this.selectedWidgets[0]
+
+ if (curWidget.parent !== widgetManager) {
+ this.select(curWidget.parent.children)
+ }
+ })
+ keyboardJS.bind(['mod + up','mod + down','mod + left' , 'mod + right'], (e)=>{
+
+ if (!this.selectedWidgets.length) return
+ if (e.target.classList.contains('no-keybinding')) return
+
+ var curWidget = this.selectedWidgets[0],
+ toSelect = null
+
+ if (e.key === 'ArrowUp' && curWidget.parent !== widgetManager) {
+
+ toSelect = curWidget.parent
+
+ } else if (e.key === 'ArrowDown') {
+
+ let toSelectList = [...curWidget.children]
+
+ if (toSelectList && toSelectList.length) {
+ toSelectList.sort((a,b) => a.container.offsetLeft>b.container.offsetLeft)
+ toSelect = toSelectList[0]
+ if (toSelect.container.classList.contains('not-editable')) {
+ toSelect = null
+ }
+ }
+
+ }
+ else if((e.key == 'ArrowLeft') || (e.key == 'ArrowRight')){
+
+ if (curWidget.parent === widgetManager) return
+
+ let toSelectList = [...curWidget.parent.children]
+
+ if (toSelectList && toSelectList.length) {
+ toSelectList.sort((a,b) => a.container.offsetLeft > b.container.offsetLeft)
+ var idx = toSelectList.indexOf(curWidget)
+ if (idx >= 0) {
+ var nextIdx = (idx + (e.key === 'ArrowLeft' ? -1 : 1 ) + toSelectList.length) % toSelectList.length
+ toSelect = toSelectList[nextIdx]
+ }
+ }
+ }
+
+ if (toSelect) {
+ this.select(toSelect)
+ }
+
+ })
+
+ keyboardJS.bind('f2', (e)=>{
+ var input = DOM.get(this.form, 'textarea[name="label"]')[0]
+ if (input) {
+ var folded = input.closest('.category.folded')
+ if (folded) DOM.dispatchEvent(DOM.get(folded, '.separator'), 'fast-click')
+ input.focus()
+ input.setSelectionRange(0, input.value.length)
+ }
+ })
+
+ })
+
+ keyboardJS.bind('mod + s', (e)=>{
+ e.preventDefault()
+ sessionManager.save()
+ })
+
+ keyboardJS.bind('mod + o', (e)=>{
+ e.preventDefault()
+ sessionManager.browse()
+ })
+
+ keyboardJS.bind('mod + e', (e)=>{
+ e.preventDefault()
+ if (this.enabled) {
+ this.disable()
+ } else {
+ if (sessionManager.session.type) this.enable()
+ }
+ })
+
+
+ this.selectarea = new SelectArea('.widget:not(.not-editable), .tablink', (elements)=>{
+
+ elements = elements.map(e => widgetManager.getWidgetByElement(e, ':not(.not-editable)')).filter(e => e)
+
+ for (var i in elements) {
+ this.select(elements[i], {multi:true, fromLasso:true})
+ }
+ this.select(this.selectedWidgets)
+
+ })
+
+
+ }
+
+ enable() {
+
+ if (READ_ONLY) return
+
+ EDITING = true
+ this.enabled = true
+
+ this.enabledOnce = true
+
+ DOM.get('.editor-root')[0].setAttribute('data-widget', DOM.get('.root-container')[0].getAttribute('data-widget'))
+ DOM.get('.editor-root')[0].classList.remove('disabled')
+ DOM.get('.disable-editor')[0].classList.remove('on')
+ DOM.get('.enable-editor')[0].classList.add('on')
+ document.body.classList.add('editor-enabled')
+ document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
+
+
+ GRIDWIDTH = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
+
+ var gridForm = html`
+
+ `
+
+ DOM.each(gridForm, '#grid-width-input', (input)=>{
+ DOM.addEventListener(input, 'keyup mouseup change mousewheel', (e)=>{
+ setTimeout(()=>{
+ var v = Math.max(Math.min(parseInt(input.value), 100), 1)
+ if (isNaN(v)) return
+ input.value = v
+ GRIDWIDTH = v
+ document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
+ document.documentElement.style.setProperty('--grid-width', GRIDWIDTH)
+ })
+ })
+ })
+
+ DOM.get(document, '.editor-menu')[0].appendChild(gridForm)
+
+ keyboardJS.setContext('editing')
+
+ document.body.addEventListener('mousemove', this.mouveMoveHandler)
+
+ this.selectarea.enable()
+
+ }
+
+ disable() {
+
+ EDITING = false
+ this.enabled = false
+
+ this.unselect()
+ this.selectedWidgets = []
+ DOM.get('.editor-root')[0].classList.add('disabled')
+ DOM.get('.disable-editor')[0].classList.add('on')
+ DOM.get('.enable-editor')[0].classList.remove('on')
+ document.body.classList.remove('editor-enabled')
+
+ var gridForm = DOM.get('#grid-width-form')[0]
+ if (gridForm) gridForm.parentNode.removeChild(gridForm)
+
+ keyboardJS.setContext('global')
+
+ document.body.removeEventListener('mousemove', this.mouveMoveHandler)
+
+ this.selectarea.disable()
+
+ }
+
+
+ unselect() {
+
+ DOM.get('#editor')[0].innerHTML = ''
+
+ this.form.innerHTML = ''
+
+ DOM.each(document, '.editing', (element)=>{
+ element.classList.remove('editing')
+ })
+
+ $('.widget.ui-resizable').resizable('destroy')
+ $('.widget.ui-draggable').draggable('destroy').find('.ui-draggable-handle').remove()
+
+ }
+
+ select(widget, options={}){
+
+ if (Array.isArray(widget)) {
+
+ this.selectedWidgets = widget
+
+ } else if (options.multi) {
+
+ var sameLevel = false
+
+ while (!sameLevel && widget.parent !== widgetManager) {
+ let test = true
+ for (var w of this.selectedWidgets) {
+ if (w.parent !== widget.parent) test = false
+ }
+ sameLevel = test
+ if (!sameLevel) widget = widget.parent
+ }
+
+ if (!this.selectedWidgets.includes(widget) && sameLevel) {
+
+ this.selectedWidgets.push(widget)
+
+ } else if (sameLevel && !options.fromLasso){
+
+ this.selectedWidgets.splice(this.selectedWidgets.indexOf(widget), 1)
+
+ }
+
+ } else {
+
+ if (widget.container.classList.contains('editing')) return
+
+ this.selectedWidgets = [widget]
+
+
+ }
+
+ if (!options.fromLasso) this.unselect()
+
+ if (this.selectedWidgets.length > 0 && !options.fromLasso) {
+
+ this.createEditForm()
+ this.createSelectionBlock()
+
+ }
+
+ }
+
+
+ createEditForm(){
+
+ var widget = this.selectedWidgets[0],
+ props = this.defaults[widget.props.type]
+
+ this.form.appendChild(html`
+
+
+ ${this.selectedWidgets.length > 1 ? 'Multiple Widgets' : 'Widget'}
+
+
+ `)
+
+ let category
+
+ for (let propName in props) {
+
+ let field,
+ shared = true
+
+ for (var w of this.selectedWidgets) {
+ if (this.defaults[w.props.type][propName] === undefined) {
+ shared = false
+ }
+ }
+
+ if (!shared) continue
+
+ if (propName.indexOf('_') === 0 && propName !== '_props') {
+
+ if (category) this.form.appendChild(category)
+ category = html`
`
+
+ field = html`${props[propName]}
`
+
+ } else if (widget.props[propName] === undefined) {
+
+ continue
+
+ } else {
+
+ field = editField(this, widget, propName, props[propName])
+ if (!field) continue
+
+ }
+
+ if (category) {
+ category.appendChild(field)
+ } else {
+ this.form.appendChild(field)
+ }
+
+ }
+
+ if (category) this.form.appendChild(category)
+
+ this.wrapper.appendChild(this.form)
+ DOM.get('#editor')[0].appendChild(this.wrapper)
+
+ }
+
+ createSelectionBlock(){
+
+ for (let widget of this.selectedWidgets) {
+ DOM.each(document, `[data-widget="${widget.hash}"]`, (item)=>{
+ item.classList.add('editing')
+ })
+ }
+
+ var widget = this.selectedWidgets[0]
+
+ if (widget.props.height !== undefined || widget.props.width !== undefined) {
+
+ let $container = $(widget.container)
+ $container.resizable({
+ handles: 's, e, se',
+ helper: 'ui-helper',
+ resize: (event, ui)=>{
+ ui.size.height = Math.round(ui.size.height / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
+ ui.size.width = Math.round(ui.size.width / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
+ },
+ stop: (event, ui)=>{
+
+ var deltaH = ui.size.height - ui.originalSize.height,
+ deltaW = ui.size.width - ui.originalSize.width
+
+ this.resizeWidget(deltaW, deltaH, ui)
+
+ },
+ grid: [GRIDWIDTH * PXSCALE, GRIDWIDTH * PXSCALE]
+ })
+
+ }
+
+ if (widget.props.top !== undefined) {
+ let $container = $(widget.container)
+ $container.draggable({
+ cursor:'-webkit-grabbing',
+ drag: (event, ui)=>{
+ ui.position.top = Math.round(ui.position.top / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
+ ui.position.left = Math.round(ui.position.left / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
+ },
+ stop: (event, ui)=>{
+ event.preventDefault()
+
+ var deltaX = (ui.helper.position().left + $container.parent().scrollLeft()) / PXSCALE - widget.container.offsetLeft / PXSCALE,
+ deltaY = (ui.helper.position().top + $container.parent().scrollTop()) / PXSCALE - widget.container.offsetTop / PXSCALE
+
+ this.moveWidget(deltaX, deltaY)
+
+ ui.helper.remove()
+ },
+ handle:'.ui-draggable-handle, > .label',
+ grid: [GRIDWIDTH * PXSCALE, GRIDWIDTH * PXSCALE],
+ helper:()=>{
+ return $('
').css({height:$container.outerHeight(),width:$container.outerWidth()})
+ }
+ }).append('
')
+
+ }
+
+
+ }
+
+ mouseMove(e) {
+
+ this.mousePosition.x = Math.round((e.offsetX + e.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
+ this.mousePosition.y = Math.round((e.offsetY + e.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
+
+ }
+
+ copyWidget() {
+
+ if (!this.selectedWidgets.length) return
+
+ var data = this.selectedWidgets.map((w)=>w.props),
+ type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget'
+
+
+ if (type !== 'widget') return
+
+ this.clipboard = JSON.stringify(data)
+
+ if (data.length == 1) {
+ this.idClipboard = this.selectedWidgets[0].getProp('id')
+ } else {
+ this.idClipboard =null
+ }
+
+ }
+
+ cutWidget() {
+
+ if (!this.selectedWidgets.length) return
+
+ var type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
+ parent = this.selectedWidgets[0].parent,
+ index = this.selectedWidgets.map(w => parent.children.indexOf(w)).sort((a,b)=>{return b-a}),
+ data = this.selectedWidgets.map((w)=>w.props),
+ removedIndexes = []
+
+ if (type !== 'widget') return
+
+ this.clipboard = JSON.stringify(data)
+
+ if (data.length == 1) {
+ this.idClipboard = this.selectedWidgets[0].getProp('id')
+ } else {
+ this.idClipboard =null
+ }
+
+ for (var i of index) {
+ removedIndexes.push(i)
+ parent.props.widgets.splice(i,1)
+ }
+
+ this.select(updateWidget(parent, {
+ preventSelect: true,
+ removedIndexes
+ }))
+ this.pushHistory({removedIndexes})
+
+ }
+
+ pasteWidget(x, y, increment) {
+
+ if (!this.selectedWidgets.length || this.clipboard === null) return
+
+ var data = this.selectedWidgets.map((w)=>w.props)
+
+ var pastedData = JSON.parse(this.clipboard),
+ minTop = Infinity,
+ minLeft = Infinity
+
+ for (let i in pastedData) {
+ if (increment) pastedData[i] = incrementWidget(pastedData[i])
+ if (!isNaN(pastedData[i]).top && pastedData[i].top < minTop) {
+ minTop = pastedData[i].top
+ }
+ if (!isNaN(pastedData[i]).left && pastedData[i].left < minLeft) {
+ minLeft = pastedData[i].left
+ }
+ }
+
+ for (let i in pastedData) {
+
+ if (!isNaN(pastedData[i].left)) pastedData[i].left = pastedData[i].left - minLeft + x
+ if (!isNaN(pastedData[i].top)) pastedData[i].top = pastedData[i].top - minTop + y
+
+ }
+
+ data[0].widgets = data[0].widgets || []
+ data[0].widgets = data[0].widgets.concat(pastedData)
+
+ var indexes = {addedIndexes: []}
+ for (let i = 0; i < pastedData.length; i++) {
+ indexes.addedIndexes.push(data[0].widgets.length - 1 - i )
+ }
+ updateWidget(this.selectedWidgets[0], indexes)
+ this.pushHistory(indexes)
+
+ }
+
+ pasteWidgetAsClone(x, y) {
+
+ if (!this.selectedWidgets.length) return
+
+ if (this.clipboard === null || !(this.idClipboard && widgetManager.getWidgetById(this.idClipboard).length)) return
+
+ var data = this.selectedWidgets.map((w)=>w.props)
+
+ var clone = {type: 'clone', widgetId: this.idClipboard},
+ pastedData = JSON.parse(this.clipboard)
+
+ clone.width = pastedData.width
+ clone.height = pastedData.width
+ clone.css = pastedData.css
+
+
+ clone.left = x
+ clone.top = y
+
+ data[0].widgets = data[0].widgets || []
+ data[0].widgets.push(clone)
+
+ var indexes = {addedIndexes: [data[0].widgets.length -1]}
+ updateWidget(this.selectedWidgets[0], indexes)
+ this.pushHistory(indexes)
+
+ }
+
+
+ deleteWidget() {
+
+ if (!this.selectedWidgets.length) return
+
+ var type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
+ parent = this.selectedWidgets[0].parent,
+ index = this.selectedWidgets.map(w => parent.children.indexOf(w)).sort((a,b)=>{return b-a}),
+ removedIndexes = []
+
+ if (this.selectedWidgets[0].getProp('id') === 'root') return
+
+ if (type === 'widget') {
+ for (let i of index) {
+ removedIndexes.push(i)
+ parent.props.widgets.splice(i,1)
+ }
+ } else {
+ for (let i of index) {
+ removedIndexes.push(i)
+ parent.props.tabs.splice(i,1)
+ }
+ }
+
+ this.select(updateWidget(parent, {
+ preventSelect: true,
+ removedIndexes
+ }))
+ this.pushHistory({removedIndexes})
+
+ }
+
+ resizeWidget(deltaW, deltaH, ui) {
+
+ if (!this.selectedWidgets.length) return
+
+ var newWidgets = []
+
+ for (var i = 0; i < this.selectedWidgets.length; i++) {
+
+ let w = this.selectedWidgets[i],
+ nW, nH
+
+ if (i === 0 && ui) {
+ nW = ui.originalSize.width + deltaW
+ nH = ui.originalSize.height + deltaH
+
+ } else {
+ nW = w.container.offsetWidth + deltaW
+ nH = w.container.offsetHeight + deltaH
+ }
+
+ if (w.props.width !== undefined) {
+ var newWidth = Math.max(nW, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.width === 'string' && w.props.width.indexOf('%') > -1) {
+ w.props.width = (100 * PXSCALE * newWidth / w.container.parentNode.offsetWidth).toFixed(2) + '%'
+ } else {
+ w.props.width = newWidth
+ }
+ }
+
+ if (w.props.height !== undefined) {
+ var newHeight = Math.max(nH, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.height === 'string' && w.props.height.indexOf('%') > -1) {
+ w.props.height = (100 * PXSCALE * newHeight / w.container.parentNode.offsetHeight).toFixed(2) + '%'
+ } else {
+ w.props.height = newHeight
+ }
+ }
+
+ if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {changedProps: ['width', 'height'], preventSelect: this.selectedWidgets.length > 1}))
+
+ }
+
+ this.pushHistory()
+
+ if (newWidgets.length > 1) this.select(newWidgets, {preventSelect: this.selectedWidgets.length > 1})
+
+ }
+
+ moveWidget(deltaX, deltaY) {
+
+ if (!this.selectedWidgets.length) return
+
+ var newWidgets = []
+
+ for (var w of this.selectedWidgets) {
+
+ var newTop = w.container.offsetTop / PXSCALE + deltaY
+ if (typeof w.props.top === 'string' && w.props.top.indexOf('%') > -1) {
+ w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.offsetHeight).toFixed(2) + '%'
+ } else {
+ w.props.top = newTop
+ }
+ var newLeft = w.container.offsetLeft / PXSCALE + deltaX
+ if (typeof w.props.left === 'string' && w.props.left.indexOf('%') > -1) {
+ w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2) + '%'
+ } else {
+ w.props.left = newLeft
+ }
+
+ newWidgets.push(updateWidget(w, {changedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
+
+ }
+
+ this.pushHistory()
+
+ if (newWidgets.length > 1) this.select(newWidgets)
+
+ }
+
+
+
+ pushHistory(indexes) {
+
+ if (this.historyState > -1) {
+ this.history.splice(0, this.historyState + 1)
+ this.historyState = -1
+ }
+
+ var d = diff.diff(this.historySession, sessionManager.session)
+
+ if (d) {
+ diff.patch(this.historySession, deepCopy(d))
+ this.history.unshift([deepCopy(d), indexes])
+ if (this.history.length > HISTORY_SIZE) this.history.pop()
+ }
+
+ }
+
+ clearHistory() {
+
+ this.history = []
+ this.historyState = -1
+ this.historySession = deepCopy(sessionManager.session)
+
+ }
+
+ undo() {
+
+ if (this.historyState === this.history.length - 1) return
+
+ this.historyState += 1
+
+ var [patch, indexes] = this.history[this.historyState],
+ d1 = deepCopy(patch),
+ d2 = deepCopy(patch)
+
+ diff.unpatch(this.historySession, d1)
+ diff.unpatch(sessionManager.session, d2)
+
+ this.updateWidgetFromPatch(patch, indexes ? {
+ addedIndexes: deepCopy(indexes.removedIndexes),
+ removedIndexes: deepCopy(indexes.addedIndexes),
+ } : undefined)
+
+ }
+
+ redo() {
+
+ if (this.historyState === -1) return
+
+ var [patch, indexes] = this.history[this.historyState],
+ d1 = deepCopy(patch),
+ d2 = deepCopy(patch)
+
+ diff.patch(this.historySession, d1)
+ diff.patch(sessionManager.session, d2)
+
+ this.updateWidgetFromPatch(patch, indexes ? {
+ addedIndexes: deepCopy(indexes.addedIndexes),
+ removedIndexes: deepCopy(indexes.removedIndexes),
+ } : undefined)
+
+ this.historyState -= 1
+
+ }
+
+ updateWidgetFromPatch(patch, indexes) {
+
+ var [widget, subpatch] = diffToWidget(widgetManager.getWidgetById('root')[0], patch),
+ options = {}
+
+ if (indexes) {
+ options = {...indexes}
+ } else {
+ options.changedProps = Object.keys(subpatch)
+ options.reuseChildren = false
+ }
+
+ updateWidget(widget, options)
+
+ }
+
+
+
+
+}
+
+var editor = new Editor()
+
+module.exports = editor
+
+require('./context-menu')
+sessionManager = require('../managers/session')
diff --git a/src/client/app/editor/select-area.js b/src/client/app/editor/select-area.js
new file mode 100644
index 00000000..cfa023f2
--- /dev/null
+++ b/src/client/app/editor/select-area.js
@@ -0,0 +1,129 @@
+var html = require('nanohtml')
+
+class SelectArea {
+
+ constructor(selector, callback){
+
+ this.startX = 0
+ this.startY = 0
+ this.curX = 0
+ this.curY = 0
+
+ this.rectCoords = [0, 0, 0, 0]
+ this.rectSize = [0, 0]
+ this.elements = []
+
+ this.rect = html`
`
+ document.body.appendChild(this.rect)
+
+ this.selector = selector
+ this.callback = callback
+
+ this.bindedMousedown = this.mousedown.bind(this)
+ this.bindedMousemove = this.mousemove.bind(this)
+ this.bindedMouseup = this.mouseup.bind(this)
+
+ }
+
+ mousedown(e) {
+ if (!e.shiftKey || event.button === 2) return
+ this.startX = this.curX = e.clientX
+ this.startY = this.curY = e.clientY
+ this.down = true
+ this.updateRect()
+ }
+
+ mousemove(e) {
+ if (!this.down) return
+ e.preventDefault()
+ e.stopPropagation()
+ this.curX = e.clientX
+ this.curY = e.clientY
+ this.updateRect()
+ }
+
+ mouseup(e) {
+ if (!this.down) return
+ this.down = false
+
+ if (this.rectSize[0] > 0 && this.rectSize[1] > 0) {
+ this.callback(this.getElements())
+ this.rect.classList.add('hidden')
+ }
+
+ this.elements = []
+
+ }
+
+ updateRect() {
+
+ var x0 = Math.min(this.startX, this.curX),
+ y0 = Math.min(this.startY, this.curY),
+ x1 = Math.max(this.startX, this.curX),
+ y1 = Math.max(this.startY, this.curY),
+ w = x1 - x0,
+ h = y1 - y0
+
+ if (w < 1 || h < 1) {
+ this.rect.classList.add('hidden')
+ } else {
+ this.rect.classList.remove('hidden')
+ this.rect.setAttribute('style', `width:${w}px;height:${h}px;left:${x0}px;top:${y0}px`)
+ }
+
+ this.rectSize = [w, h]
+ this.rectCoords = [x0, x1, y0, y1]
+
+ }
+
+ getElements(){
+
+ var [x0, x1, y0, y1] = this.rectCoords,
+ startEl = document.elementFromPoint(this.startX, this.startY),
+ elements = [startEl]
+
+ this.elements = DOM.each(document, this.selector, (el)=>{
+
+ var {left, right, top, bottom} = el.getBoundingClientRect()
+ if (!(
+ left > x1 ||
+ right < x0 ||
+ top > y1 ||
+ bottom < y0
+ )) {
+ if (el !== startEl) elements.push(el)
+ }
+
+ })
+
+ // slower implementation...
+ // for (var x = x0; x <= x1; x += 10) {
+ // for (var y = y0; y <= y1; y += 10) {
+ // var el = document.elementFromPoint(x, y)
+ // if (elements.indexOf(el) < 0) elements.push(el)
+ // }
+ // }
+
+ return elements
+
+ }
+
+ enable() {
+
+ document.addEventListener('mousedown', this.bindedMousedown)
+ document.addEventListener('mousemove', this.bindedMousemove, true)
+ document.addEventListener('mouseup', this.bindedMouseup)
+
+ }
+
+ disable() {
+
+ document.removeEventListener('mousedown', this.bindedMousedown)
+ document.removeEventListener('mousemove', this.bindedMousemove, true)
+ document.removeEventListener('mouseup', this.bindedMouseup)
+
+ }
+
+}
+
+module.exports = SelectArea
diff --git a/src/client/app/events/click.js b/src/client/app/events/click.js
new file mode 100644
index 00000000..69a1e475
--- /dev/null
+++ b/src/client/app/events/click.js
@@ -0,0 +1,54 @@
+const iOS = require('../ui/ios')
+
+var longTouchTimer = false,
+ clearLongTouchTimer = function() {
+ if (longTouchTimer) {
+ clearTimeout(longTouchTimer)
+ longTouchTimer = false
+ }
+ }
+
+document.body.setAttribute('oncontextmenu', 'return false')
+
+function mouseToFastClick(event) {
+
+ if (event.touchPunch) return
+ if (event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) return
+ if (event.button == 2) event.preventDefault()
+
+ var e = event
+
+ var name = event.button == 2 ? 'fast-right-click' : 'fast-click'
+
+ DOM.dispatchEvent(e.target, name, e)
+
+}
+
+function touchToFastClick(event) {
+
+ var e = event.changedTouches[0]
+
+ DOM.dispatchEvent(e.target, 'fast-click', e)
+
+ if (e.preventOriginalEvent) event.preventDefault()
+
+ longTouchTimer = setTimeout(()=>{
+
+ var off = DOM.offset(e.target)
+
+ e.offsetX = e.pageX - off.left
+ e.offsetY = e.pageY - off.top
+
+ DOM.dispatchEvent(e.target, 'fast-right-click', e)
+
+ clearLongTouchTimer()
+
+ }, 600)
+
+}
+
+if (!iOS) document.addEventListener('mousedown', mouseToFastClick, true)
+document.addEventListener('touchstart', touchToFastClick, {passive: false, capture: true})
+
+
+DOM.addEventListener(document, 'touchend touchmove touchcancel', clearLongTouchTimer)
diff --git a/src/client/app/events/drag.js b/src/client/app/events/drag.js
new file mode 100644
index 00000000..922f2058
--- /dev/null
+++ b/src/client/app/events/drag.js
@@ -0,0 +1,303 @@
+const {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} = require('./utils')
+const iOS = require('../ui/ios')
+
+var targets = {},
+ previousPointers = {}
+
+function pointerDownHandler(event) {
+
+ if (event.capturedByEditor || event.touchPunch) return
+
+ if (!event.multitouch) {
+ for (var i in targets) {
+ if (targets[i] == event.target) return
+ }
+ }
+
+ event = normalizeDragEvent(event)
+
+ targets[event.pointerId] = event.target
+
+ if (event.traversing === TRAVERSING_SAMEWIDGET) {
+ event.traversingType = event.target.closest('.drag-event')._drag_widget.getProp('type')
+ }
+
+ previousPointers[event.pointerId] = event
+
+ triggerWidgetEvent(targets[event.pointerId], 'draginit', event)
+
+}
+
+function pointerMoveHandler(event) {
+
+ event = normalizeDragEvent(event, previousPointers[event.pointerId])
+
+ event.stopPropagation = true
+
+ if (event.traversing) {
+
+ var previousTarget = targets[event.pointerId],
+ target = event.isTouch ?
+ document.elementFromPoint(event.clientX, event.clientY)
+ : event.target
+
+ if (target) target = target.closest('.drag-event')
+
+ if (
+ target && event.traversing === TRAVERSING_SAMEWIDGET
+ && event.traversingType !== target._drag_widget.getProp('type')
+ ) {
+ target = null
+ }
+
+ if (target && event.isTouch) {
+ resetEventOffset(event, target)
+ }
+
+ if (previousTarget !== target) {
+ triggerWidgetEvent(previousTarget, 'dragend', event)
+ }
+
+
+ if (target) {
+ if (event.traversingContainer.contains(target)) {
+ triggerWidgetEvent(target, previousTarget !== target ? 'draginit' : 'drag', event)
+ }
+ }
+
+ targets[event.pointerId] = target
+
+
+ } else {
+ triggerWidgetEvent(targets[event.pointerId], 'drag', event)
+ }
+
+ previousPointers[event.pointerId] = event
+
+}
+
+function pointerUpHandler(event) {
+
+ event = normalizeDragEvent(event, previousPointers[event.pointerId])
+
+ triggerWidgetEvent(targets[event.pointerId], 'dragend', event)
+
+ delete targets[event.pointerId]
+ delete previousPointers[event.pointerId]
+
+}
+
+
+// Move / Up Filter
+
+function pointerMoveFilter(event) {
+
+ if (targets[event.pointerId] !== undefined) {
+ pointerMoveHandler.call(targets[event.pointerId], event)
+ }
+
+}
+
+function pointerUpFilter(event) {
+
+ if (targets[event.pointerId] !== undefined) {
+ pointerUpHandler.call(targets[event.pointerId], event)
+ delete targets[event.pointerId]
+ }
+
+}
+
+// Mouse events wrappers
+
+function mouseMultiWrapper(event) {
+ mouseDownCapture(event, true)
+}
+
+function mouseDownCapture(event, multitouch) {
+ if ((event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) || event.button == 2) return
+ event.pointerId = 'mouse'
+ event.multitouch = multitouch
+ pointerDownHandler(event)
+}
+
+function mouseMoveCapture(event) {
+ event.pointerId = 'mouse'
+ event.inertia = event.ctrlKey ? 10 : 1
+ pointerMoveFilter(event)
+}
+
+function mouseUpCapture(event){
+ if ((event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) || event.button == 2) return
+ event.pointerId = 'mouse'
+ pointerUpFilter(event)
+}
+
+
+// Touch events wrappers
+
+function touchMultiWrapper(event) {
+ touchDownCapture(event, true)
+}
+
+function touchDownCapture(event, multitouch) {
+ event.preventDefault()
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+
+ if (event.traversing) {
+ touchEvent.traversing = event.traversing
+ touchEvent.traversingContainer = event.traversingContainer
+ }
+
+ touchEvent.pointerId = touchEvent.identifier
+ touchEvent.multitouch = multitouch
+
+ pointerDownHandler(touchEvent)
+ }
+}
+
+function touchMoveCapture(event) {
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+
+ var fingers = 0
+ for (var j in event.touches) {
+ if (event.touches[j].target && event.touches[j].target.isSameNode(touchEvent.target)) {
+ fingers += 1
+ if (fingers == 2) {
+ touchEvent.inertia = 10
+ break
+ }
+ }
+ }
+
+ touchEvent.pointerId = touchEvent.identifier
+ pointerMoveFilter(touchEvent)
+ }
+}
+
+function touchUpCapture(event) {
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+ touchEvent.pointerId = touchEvent.identifier
+ pointerUpFilter(touchEvent)
+ }
+}
+
+// Callback trigger
+
+function triggerWidgetEvent(target, name, event) {
+ if (target !== null && target._drag_widget) {
+ target._drag_widget.trigger(name, event)
+ } else if (target !== null) {
+ triggerWidgetEvent(target.closest('.drag-event'), name, event)
+ }
+}
+
+// init
+
+DOM.ready(()=>{
+
+ if (!iOS) document.addEventListener('mousemove', mouseMoveCapture, true)
+ if (!iOS) document.addEventListener('mouseup', mouseUpCapture, true)
+ document.addEventListener('touchmove', touchMoveCapture, true)
+ DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
+
+})
+
+module.exports = {
+
+ setup: function(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options
+ ) {
+ return
+ }
+
+ var {element, multitouch} = options
+
+ element._drag_widget = this
+ element.style.touchAction = 'none'
+ element.classList.add('drag-event')
+
+ if (multitouch) {
+ element.addEventListener('touchstart', touchMultiWrapper, false)
+ if (!iOS) element.addEventListener('mousedown', mouseMultiWrapper)
+ } else {
+ element.addEventListener('touchstart', touchDownCapture, false)
+ if (!iOS) element.addEventListener('mousedown', mouseDownCapture)
+ }
+
+ },
+
+ teardown: function(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options
+ ) {
+ return
+ }
+
+ var {element, multitouch} = options
+
+ delete element._drag_widget
+ element.style.touchAction = ''
+ element.classList.remove('drag-event')
+
+ if (multitouch) {
+ element.removeEventListener('touchstart', touchMultiWrapper, false)
+ if (!iOS) element.removeEventListener('mousedown', mouseMultiWrapper)
+ } else {
+ element.removeEventListener('touchstart', touchDownCapture, false)
+ if (!iOS) element.removeEventListener('mousedown', mouseDownCapture)
+ }
+
+ },
+
+ enableTraversingGestures: function(element, options={}) {
+
+ if (element._traversing) return
+
+ var traversing = options.smart ? TRAVERSING_SAMEWIDGET : true
+
+ element._traversing = traversing
+
+ function makeEventTraversing(event) {
+ if (event.ctrlKey) return
+ event.traversing = traversing
+ if (!event.traversingContainer) event.traversingContainer = element
+ }
+
+ if (!iOS) element.addEventListener('mousedown', makeEventTraversing, true)
+ element.addEventListener('touchstart', makeEventTraversing, true)
+
+ element.addEventListener('disableTraversingGestures', ()=>{
+
+ if (!iOS) element.removeEventListener('mousedown', makeEventTraversing, true)
+ element.removeEventListener('touchstart', makeEventTraversing, true)
+
+ })
+
+ },
+
+ disableTraversingGestures: function(element) {
+
+ if (!element._traversing) return
+
+ delete element._traversing
+
+ DOM.dispatchEvent(element, 'disableTraversingGestures')
+
+ }
+
+}
diff --git a/src/client/app/events/event-emitter.js b/src/client/app/events/event-emitter.js
new file mode 100644
index 00000000..1cdffd61
--- /dev/null
+++ b/src/client/app/events/event-emitter.js
@@ -0,0 +1,128 @@
+var customEvents = {}
+setTimeout(()=>{
+ customEvents['draginit'] = customEvents['drag'] = customEvents['dragend'] = require('./drag')
+ customEvents['resize'] = require('./resize')
+})
+
+// micro optimisation from eventemitter3
+var has = Object.prototype.hasOwnProperty
+
+module.exports = class EventEmitter {
+
+ constructor() {
+
+ this._customBindings = {}
+ this._listeners = {}
+
+ for (var evt in customEvents) {
+ this._customBindings[evt] = 0
+ }
+
+ }
+
+ trigger(evt, data) {
+
+ if (has.call(this._listeners, evt)) {
+ // shallow copy in case a listener gets added/removed while looping
+ var listeners = this._listeners[evt].slice(0)
+ for (var i = 0, len = listeners.length; i !== len; i++) {
+ listeners[i](data)
+ }
+ }
+
+ // Event bubbling
+ if (!data || !data.stopPropagation) {
+ if (this.parent) this.parent.trigger(evt, data)
+ }
+
+ return this
+
+ }
+
+ on(evt, listener, options) {
+
+ if (options) {
+
+ // Custom event setup
+ if (has.call(customEvents, evt)) {
+ this._customBindings[evt]
+ if (this._customBindings[evt] === 0) {
+ listener._options = options
+ customEvents[evt].setup.call(this, options)
+ }
+ this._customBindings[evt]++
+ }
+
+ // Context storing
+ if (options.context) listener._context = options.context
+
+ }
+
+ // Add listener
+ if (!has.call(this._listeners, evt)) this._listeners[evt] = []
+
+ var listeners = this._listeners[evt]
+
+ if (listeners.indexOf(listener) === -1) listeners.push(listener)
+
+ return this
+
+ }
+
+ off(evt, listener, context) {
+
+ // Remove listener
+ if (evt && has.call(this._listeners, evt)) {
+
+ var listeners = this._listeners[evt]
+
+ if (listener) {
+
+ var index = listeners.indexOf(listener)
+
+ if (index !== -1) {
+
+ if (context && context !== listener._context) return this
+
+ listeners.splice(index, 1)
+
+ // Custom event teardown
+ if (has.call(customEvents, evt)) {
+
+ if (this._customBindings[evt] !== 0) {
+ this._customBindings[evt]--
+ if (this._customBindings[evt] === 0) {
+ customEvents[evt].teardown.call(this, listener._options)
+ delete listener._options
+ }
+ }
+
+ }
+
+ }
+
+ } else {
+
+ for (var i = listeners.length - 1; i !== -1; i--) {
+
+ if (!context || context == listeners[i]._context) {
+ this.off(evt, listeners[i], context)
+ }
+
+ }
+
+ }
+
+ } else if (!evt) {
+
+ for (var k in this._listeners) {
+ this.off(k, undefined, context)
+ }
+
+ }
+
+ return this
+
+ }
+
+}
diff --git a/src/client/app/events/resize.js b/src/client/app/events/resize.js
new file mode 100644
index 00000000..f7cf8f9a
--- /dev/null
+++ b/src/client/app/events/resize.js
@@ -0,0 +1,64 @@
+var elements = []
+
+function checkResizes(context, force){
+ // Iterate over all elements to which the 'resize' event is bound.
+ var resizedElems = [],
+ cachedStyles = []
+ for (let i = elements.length - 1; i >= 0; i--) {
+ var elem = elements[i]
+
+ if (!context.contains(elem)) continue
+
+ var style = window.getComputedStyle(elem),
+ width = parseInt(style['width']) - parseInt(style['padding-left']) - parseInt(style['padding-right']),
+ height = parseInt(style['height']) - parseInt(style['padding-top']) - parseInt(style['padding-bottom'])
+
+ if (!width || !height) continue
+
+ // If element size has changed since the last time, update the element
+ // data store and trigger the 'resize' event.
+ if (force || width != elem.resizedataw || height != elem.resizedatah) {
+ elem.resizedataw = width
+ elem.resizedatah = height
+ resizedElems.push(elem)
+ cachedStyles.push(style)
+ }
+ }
+ for (let i = resizedElems.length - 1; i >= 0; i--) {
+ resizedElems[i]._resize_widget.trigger('resize', {
+ width: resizedElems[i].resizedataw,
+ height: resizedElems[i].resizedatah,
+ style:cachedStyles[i],
+ stopPropagation: true
+ })
+ }
+
+}
+
+window.addEventListener('resize', ()=>{checkResizes(document)})
+
+module.exports = {
+
+ setup: function(options) {
+
+ if (!options) return
+ if (elements.indexOf(options.element) == -1) {
+ elements.push(options.element)
+ options.element._resize_widget = this
+ }
+
+ },
+ teardown: function(options) {
+
+ if (!options) return
+
+ if (elements.indexOf(options.element) != -1) {
+ elements.splice(elements.indexOf(options.element), 1)
+ delete options.element._resize_widget
+ }
+
+ },
+
+ check: checkResizes
+
+}
diff --git a/src/client/app/events/utils.js b/src/client/app/events/utils.js
new file mode 100644
index 00000000..52cfc87a
--- /dev/null
+++ b/src/client/app/events/utils.js
@@ -0,0 +1,92 @@
+const Touch = window.Touch || class Touch {}
+
+module.exports = {
+
+ fix: function(e) {
+
+ return {
+
+ target: e.target,
+ offsetX: e.offsetX,
+ offsetY: e.offsetY,
+ pageX: e.pageX,
+ pageY: e.pageY,
+ clientX: e.clientX,
+ clientY: e.clientY,
+ movementX: e.movementX,
+ movementY: e.movementY,
+ pointerId: e.pointerId,
+ pointerType: e.pointerType,
+ button: e.button,
+ ctrlKey: e.ctrlKey,
+ shiftKey: e.shiftKey,
+ inertia: e.multitouch ? 1 : e.inertia,
+ traversing: e.traversing,
+ traversingType: e.traversingType,
+ traversingContainer: e.traversingContainer,
+ multitouch: e.multitouch,
+ isTouch: e instanceof Touch
+ }
+ },
+
+ normalizeDragEvent: function(event, previousEvent) {
+
+ event = module.exports.fix(event)
+
+ if (event.movementX === undefined) {
+
+ event.movementX = previousEvent ? event.pageX - previousEvent.pageX : 0
+ event.movementY = previousEvent ? event.pageY - previousEvent.pageY : 0
+
+ }
+
+ if (event.isTouch && !previousEvent) {
+
+ module.exports.resetEventOffset(event, event.target)
+
+ } else if (event.isTouch && previousEvent) {
+
+ event.offsetX = previousEvent.offsetX + event.movementX
+ event.offsetY = previousEvent.offsetY + event.movementY
+
+ }
+
+ if (event.inertia === undefined) {
+
+ event.inertia = 1
+
+ }
+
+ if (previousEvent) {
+
+ if (previousEvent.traversing) {
+ event.traversing = previousEvent.traversing
+ event.traversingType = previousEvent.traversingType
+ event.traversingContainer = previousEvent.traversingContainer
+ }
+
+ if (previousEvent.multitouch) {
+ event.multitouch = previousEvent.multitouch
+ event.inertia = 1
+ }
+
+ }
+
+
+
+ return event
+
+ },
+
+ resetEventOffset: function(event, target) {
+
+ var off = DOM.offset(target)
+
+ event.offsetX = event.pageX - off.left
+ event.offsetY = event.pageY - off.top
+
+ },
+
+ TRAVERSING_SAMEWIDGET: 1
+
+}
diff --git a/src/browser/js/app/globals.js b/src/client/app/globals.js
similarity index 59%
rename from src/browser/js/app/globals.js
rename to src/client/app/globals.js
index ee959973..9c675325 100644
--- a/src/browser/js/app/globals.js
+++ b/src/client/app/globals.js
@@ -3,7 +3,12 @@ location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, (s,k,v)=>{
ARGV[k]=v
})
-window.PACKAGE = require('../../../../app/package.json')
+window.ELECTRON_FULLSCREEN = window.ELECTRON_FULLSCREEN || false
+
+window.LANG = ARGV.lang === 'debug' ? 'debug' : (ARGV.lang || navigator.language || '').substr(0, 2).toLowerCase()
+
+window.PACKAGE = require('../../../package.json')
+document.title = PACKAGE.productName + ' v' + PACKAGE.version
window.LOADING = null
@@ -15,6 +20,7 @@ window.EDITING = false
window.GRIDWIDTH = 10
+window.CANVAS_FRAMERATE = parseFloat(ARGV.framerate || 60)
window.CANVAS_SCALING = parseFloat(ARGV.forceHdpi) || ( ARGV.hdpi ? window.devicePixelRatio : 1 )
window.INITIALZOOM = ARGV.zoom ? ARGV.zoom : 1
window.PXSCALE = INITIALZOOM
@@ -25,10 +31,11 @@ window.DOUBLE_TAP_TIME = ARGV.doubletap ? ARGV.doubletap : 375
window.JSON.parseFlex = require('json5').parse
+window.DOM = require('./dom')
+
window.$ = require('jquery/dist/jquery.slim.min.js')
require('../libs/jquery.ui')
-require('../libs/jquery.drag')
-require('../libs/jquery.resize')
+require('../libs/jquery.touch')
-require('cardinal-spline-js/curve.js')
+require('cardinal-spline-js/curve.min.js')
diff --git a/src/client/app/ipc/callbacks.js b/src/client/app/ipc/callbacks.js
new file mode 100644
index 00000000..e5093c6a
--- /dev/null
+++ b/src/client/app/ipc/callbacks.js
@@ -0,0 +1,175 @@
+var utils = require('../ui/utils'),
+ osc = require('../osc'),
+ session = require('../managers/session'),
+ widgetManager = require('../managers/widgets'),
+ state = require('../managers/state'),
+ editor = require('../editor/'),
+ locales = require('../locales'),
+ {deepCopy} = require('../utils'),
+ sidepanel = require('../ui/sidepanel'),
+ {TRAVERSING_SAMEWIDGET} = require('../events/utils'),
+ raw = require('nanohtml/raw'),
+ ipc = require('./')
+
+module.exports = {
+
+ bundle: function(data) {
+ for (let i in data) {
+ osc.receive(data[i])
+ }
+ },
+
+ receiveOsc: function(data){
+ osc.receive(data)
+ },
+
+ connected:function(){
+ LOADING.close()
+ },
+
+ sessionList: function(data){
+
+ session.list(data)
+
+ },
+
+ sessionOpen: function(data){
+
+ session.open(data)
+
+ },
+
+ sessionNew: function(){
+
+ session.create()
+
+ },
+
+ stateLoad: function(data){
+
+ state.set(data.state, data.send)
+
+ },
+
+ stateSend:function(){
+ var p = utils.loading(locales('loading_newclient'))
+
+ setTimeout(function(){
+
+ osc.syncOnly = true
+ state.send()
+ osc.syncOnly = false
+
+ p.close()
+ },150)
+
+ },
+
+ editorDisable: function(data){
+
+ editor.disable(data.permanent)
+
+ },
+
+ error: function(data){
+ new utils.Popup({title: raw(utils.icon('exclamation-triangle') + ' ' + locales('error')), content: raw(data), closable:true})
+ },
+
+ reloadCss: function(){
+ var queryString = '?reload=' + Date.now()
+ DOM.each(document, 'link[rel="stylesheet"][hot-reload]', (el)=>{
+ el.href = el.href.replace(/\?.*|$/, queryString)
+ })
+
+ setTimeout(()=>{
+ var root = widgetManager.getWidgetById('root')[0]
+ if (root) root.reCreateWidget()
+ },100)
+
+
+ GRIDWIDTH = getComputedStyle(document.documentElement).getPropertyValue('--grid-width')
+ },
+
+ readOnly: function(){
+ READ_ONLY = true
+ $('.editor-menu .btn').remove()
+ $('.editor-menu .title').addClass('disabled')
+ if (editor.enabled) editor.disable()
+ },
+
+ reload: function(){
+
+ var id = Math.random(),
+ search = location.search,
+ query = 'backupId=' + id
+
+ // disable editor's warning
+ window.onbeforeunload = null
+
+ if (!session.session.type) {
+ window.location.href = window.location.href
+ return
+ }
+
+ try {
+
+ // store session & state backup
+ ipc.send('storeBackup', {
+ backupId: id,
+ session: session.session,
+ state: state.get(),
+ history: editor.history,
+ historyState: editor.historyState,
+ editorEnabled: editor.enabled,
+ sidepanelOpened: document.getElementById('sidepanel').classList.contains('sidepanel-open'),
+ traversing: document.getElementById('container')._traversing
+ })
+
+ // reload page and hold backup id
+
+ if (search) {
+ if (search.includes('backupId=')) {
+ search = search.replace(/backupId=[^&]*/, query)
+ } else {
+ search += '&' + query
+ }
+ } else {
+ search += '?' + query
+ }
+
+ window.location.search = search
+
+ } catch(e) {
+
+ window.location.href = window.location.href
+
+ }
+
+ },
+
+ loadBackup: function(data) {
+
+ session.load(data.session, ()=>{
+
+ state.set(data.state, false)
+
+ editor.historySession = deepCopy(data.session)
+ editor.history = data.history
+ editor.historyState = data.historyState
+ if (data.editorEnabled) editor.enable()
+
+ if (data.sidepanelOpened) sidepanel.open()
+
+ if (data.traversing === TRAVERSING_SAMEWIDGET) {
+ DOM.get('.traversingSmart')[0].click()
+ } else if (data.traversing) {
+ DOM.get('.traversingEnable')[0].click()
+ }
+
+ ipc.send('deleteBackup', data.backupId)
+
+ })
+
+ }
+
+}
diff --git a/src/client/app/ipc/index.js b/src/client/app/ipc/index.js
new file mode 100644
index 00000000..8b32e8a0
--- /dev/null
+++ b/src/client/app/ipc/index.js
@@ -0,0 +1,143 @@
+var EventEmitter = require('../events/event-emitter'),
+ uuid = require('nanoid/generate')('0123456789abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
+
+var reconnectInterval = 5000,
+ hearbeatInterval = 25000,
+ hearbeatTimeout = 5000
+
+class Ipc extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.socket = null
+
+ this.queue = []
+
+ this.reconnect = undefined
+
+ this.hearbeat = undefined
+ this.hearbeatTimeout = undefined
+ this.on('pong', ()=>{
+ this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
+ })
+ this.on('ping', ()=>{
+ this.socket.send('["pong"]')
+ })
+
+ this.open()
+
+ }
+
+ init() {
+
+ var callbacks = require('./callbacks')
+
+ for (let i in callbacks) {
+ let callback = callbacks[i]
+ this.on(i, (data)=>{
+ callback(data)
+ })
+ }
+
+ }
+
+ open() {
+
+ this.socket = new WebSocket('ws://' + window.location.host + '/' + uuid)
+
+ this.socket.onopen = (e)=>{
+
+ this.reconnect = clearInterval(this.reconnect)
+
+ this.hearbeat = setInterval(()=>{
+ if (!this.connected()) return
+ this.socket.send('["ping"]')
+ this.hearbeatTimeout = setTimeout(()=>{
+ if (this.connected()) this.socket.close()
+ }, hearbeatTimeout)
+ }, hearbeatInterval)
+
+ this.trigger('connect')
+ this.flush()
+
+ }
+
+ this.socket.onmessage = (e)=>{
+ this.receive(e.data)
+ }
+
+ this.socket.onclose = this.socket.onerror = ()=>{
+ this.close()
+ }
+
+ }
+
+ close() {
+
+ this.socket = null
+
+ this.hearbeat = clearInterval(this.hearbeat)
+ this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
+ this.dieTimeout = clearTimeout(this.dieTimeout)
+
+ if (!this.reconnect) {
+ this.reconnect = setInterval(()=>{
+ this.open()
+ }, reconnectInterval)
+ }
+
+ }
+
+ connected() {
+
+ return this.socket && this.socket.readyState == this.socket.OPEN
+
+ }
+
+ receive(message) {
+
+ if (typeof message == 'string') {
+
+ var packet = JSON.parse(message)
+
+ if (Array.isArray(packet) && typeof packet[0] == 'string') {
+
+ this.trigger(packet[0], packet[1])
+
+ }
+
+ }
+
+ }
+
+ send(event, data) {
+
+ var packet = JSON.stringify([event, data])
+
+ if (this.connected()) {
+ this.socket.send(packet)
+ } else {
+ this.queue.push(packet)
+ }
+
+ }
+
+ flush(){
+
+ for (var i in this.queue) {
+
+ if (this.connected()) this.socket.send(this.queue[i])
+
+ }
+
+ this.queue = []
+
+ }
+
+}
+
+var ipc = new Ipc()
+
+module.exports = ipc
diff --git a/src/client/app/locales/en.js b/src/client/app/locales/en.js
new file mode 100644
index 00000000..14805661
--- /dev/null
+++ b/src/client/app/locales/en.js
@@ -0,0 +1,64 @@
+module.exports = {
+
+ // editor
+ editor_on: 'On',
+ editor_off: 'Off',
+ editor_root: 'Root',
+ editor_load: 'Load',
+ editor_save: 'Save',
+
+ // editor context-menu
+ editor_editparent: 'Edit parent',
+ editor_copy: 'Copy',
+ editor_cut: 'Cut',
+ editor_wrap: 'Wrap in',
+ editor_paste: 'Paste',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Clone',
+ editor_addwidget: 'Add widget',
+ editor_addtab: 'Add tab',
+ editor_delete: 'Delete',
+ editor_click_for_help: 'Click on the property name to display help',
+
+ // loadings
+ loading_upload: 'Uploading file...',
+ loading_newclient: 'New client connecting...',
+ loading_server: 'Connecting server...',
+ loading_session: 'Loading session...',
+
+ // fullscreen error
+ fs_unnavailable: 'Fullscreen not available',
+ fs_addtohome: 'You must add this page to your home screen to launch it in fullscreen',
+
+ // session
+ session_browse: 'Browse...',
+ session_new: 'New session',
+ session_malformed: 'Malformed session file.',
+ session_parsingerror: 'Parsing error.',
+ session_uploaderror: 'Failed to upload session file.',
+
+ // sidepanel
+ sidepanel_fs: 'Fullscreen',
+ sidepanel_nosleep: 'Stay awake',
+ sidepanel_state: 'State',
+ sidepanel_traversing: 'Traversing gestures',
+ sidepanel_editor: 'Editor',
+
+ // state
+ state_store: 'Store',
+ state_recall: 'Recall',
+ state_send: 'Send All',
+ state_import: 'Import',
+ state_export: 'Export',
+ state_uploaderror: 'Failed to upload state file.',
+
+ // traversing
+ traversing_on: 'On',
+ traversing_smart: 'Smart',
+ traversing_off: 'Off',
+
+ // misc
+ error: 'Error'
+
+
+}
diff --git a/src/client/app/locales/fr.js b/src/client/app/locales/fr.js
new file mode 100644
index 00000000..d0bdae06
--- /dev/null
+++ b/src/client/app/locales/fr.js
@@ -0,0 +1,64 @@
+module.exports = {
+
+ // editor
+ editor_on: 'On',
+ editor_off: 'Off',
+ editor_root: 'Root',
+ editor_load: 'Charger',
+ editor_save: 'Sauver',
+
+ // editor context-menu
+ editor_editparent: 'Éditer parent',
+ editor_copy: 'Copier',
+ editor_cut: 'Couper',
+ editor_wrap: 'Grouper dans',
+ editor_paste: 'Coller',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Clone',
+ editor_addwidget: 'Nouveau widget',
+ editor_addtab: 'Nouvel onglet',
+ editor_delete: 'Supprimer',
+ editor_click_for_help: 'Cliquer sur le nom de la propriété pour afficher l\'aide',
+
+ // loadings
+ loading_upload: 'Téléversement...',
+ loading_newclient: 'Connexion d\'un nouveau client...',
+ loading_server: 'Connexion au serveur...',
+ loading_session: 'Chargement de la session...',
+
+ // fullscreen error
+ fs_unnavailable: 'Plein écran indisponible',
+ fs_addtohome: 'Vous devez ajouter cette page à votre écran d\'accueil pour pouvoir l\'ouvrir en plein écran.',
+
+ // session
+ session_browse: 'Parcourir...',
+ session_new: 'Nouvelle session',
+ session_malformed: 'Fichier de session mal formé.',
+ session_parsingerror: 'Erreur à l\'ouverture de la session.',
+ session_uploaderror: 'Échec à l\'envoi du fichier de session.',
+
+ // sidepanel
+ sidepanel_fs: 'Plein Écran',
+ sidepanel_nosleep: 'Rester allumé',
+ sidepanel_state: 'État',
+ sidepanel_traversing: 'Gestes traversants',
+ sidepanel_editor: 'Éditeur',
+
+ // state
+ state_store: 'Sauver',
+ state_recall: 'Rappeler',
+ state_send: 'Envoyer',
+ state_import: 'Importer',
+ state_export: 'Exporter',
+ state_uploaderror: 'Échec à l\'envoi du fichier d\'état.',
+
+ // traversing
+ traversing_on: 'On',
+ traversing_smart: 'Auto',
+ traversing_off: 'Off',
+
+ // misc
+ error: 'Erreur'
+
+
+}
diff --git a/src/client/app/locales/index.js b/src/client/app/locales/index.js
new file mode 100644
index 00000000..6b1305ee
--- /dev/null
+++ b/src/client/app/locales/index.js
@@ -0,0 +1,10 @@
+var locales = {
+ debug: {/* empty */},
+ en: require('./en'),
+ fr: require('./fr'),
+ ru: require('./ru')
+}
+
+var lang = locales[LANG] ? LANG : 'en'
+
+module.exports = key=>locales[lang][key] || `!${key}!`
diff --git a/src/client/app/locales/ru.js b/src/client/app/locales/ru.js
new file mode 100644
index 00000000..d3cf3483
--- /dev/null
+++ b/src/client/app/locales/ru.js
@@ -0,0 +1,64 @@
+module.exports = { // @https://github.com/suhr
+
+ // editor
+ editor_on: 'Вкл',
+ editor_off: 'Выкл',
+ editor_root: 'Корень',
+ editor_load: 'Загрузить',
+ editor_save: 'Сохранить',
+
+ // editor context-menu
+ editor_editparent: 'К родителю',
+ editor_copy: 'Копировать',
+ editor_cut: 'Вырезать',
+ editor_wrap: 'Обернуть в',
+ editor_paste: 'Вставить',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Клон',
+ editor_addwidget: 'Добавить виджет',
+ editor_addtab: 'Добавить вкладку',
+ editor_delete: 'Удалить',
+ editor_click_for_help: 'Нажмите на название свойства, чтобы отобразить справку',
+
+ // loadings
+ loading_upload: 'Загрузка файла...',
+ loading_newclient: 'Подключается новый клиент...',
+ loading_server: 'Соединение с сервером...',
+ loading_session: 'Загрузка сессии...',
+
+ // fullscreen error
+ fs_unnavailable: 'Полный экран не доступен',
+ fs_addtohome: 'Необходимо добавить эту страницу на главный экран чтобы запустить её в полноэкранном режиме',
+
+ // session
+ session_browse: 'Обзор...',
+ session_new: 'Новая сессия',
+ session_malformed: 'Файл сессии повреждён.',
+ session_parsingerror: 'Ошибка разбора.',
+ session_uploaderror: 'Не удалось загрузить файл сессии.',
+
+ // sidepanel
+ sidepanel_fs: 'Полный экран',
+ sidepanel_nosleep: 'бодрствовать',
+ sidepanel_state: 'Состояние',
+ sidepanel_traversing: 'Скользящие жесты',
+ sidepanel_editor: 'Редактор',
+
+ // state
+ state_store: 'Запомнить',
+ state_recall: 'Вспомнить',
+ state_send: 'Отправить всё',
+ state_import: 'Импорт',
+ state_export: 'Экспорт',
+ state_uploaderror: 'Не удалось загрузить файл состояния.',
+
+ // traversing
+ traversing_on: 'Вкл',
+ traversing_smart: 'Умный',
+ traversing_off: 'Выкл',
+
+ // misc
+ error: 'Ошибка'
+
+
+}
diff --git a/src/client/app/managers/session.js b/src/client/app/managers/session.js
new file mode 100644
index 00000000..f9eff072
--- /dev/null
+++ b/src/client/app/managers/session.js
@@ -0,0 +1,192 @@
+var ipc = require('../ipc/'),
+ parser = require('../parser'),
+ editor = require('../editor/'),
+ lobby = require('../ui/lobby'),
+ {loading, icon, Popup, upload} = require('../ui/utils'),
+ {saveAs} = require('file-saver'),
+ widgetManager = require('./widgets'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw'),
+ locales = require('../locales')
+
+
+var SessionManager = class SessionManager {
+
+ constructor() {
+
+ this.session = []
+ this.lock = false
+
+ }
+
+ load(session, callback) {
+
+ if (this.lock) return
+
+ this.lock = true
+
+ var container = DOM.get('#container')[0]
+
+ container.classList.remove('show')
+ container.innerHTML = ''
+
+ lobby.close()
+
+ var loader = loading(locales('loading_session'))
+
+ setTimeout(()=>{
+ try {
+ parser.reset()
+
+ try {
+
+ if (Array.isArray(session)) session = session[0]
+ if (session.type !== 'root') throw ''
+ this.session = session
+
+ } catch(err) {
+
+ throw new Error(locales('session_malformed'))
+
+ }
+
+ parser.parse({
+ data: this.session,
+ parentNode: DOM.get('#container')[0]
+ })
+ editor.clearHistory()
+
+ } catch (err) {
+ loader.close()
+ lobby.open()
+ new Popup({title: raw(icon('exclamation-triangle')) + ' ' + locales('session_parsingerror'), content: err, closable:true})
+ this.lock = false
+ throw err
+ }
+
+ for (var h in widgetManager.widgets) {
+ if (widgetManager.widgets[h].value !== undefined) {
+ widgetManager.trigger('change', {
+ widget: widgetManager.widgets[h],
+ id: widgetManager.widgets[h].getProp('id'),
+ linkId: widgetManager.widgets[h].getProp('linkId'),
+ options: {}
+ })
+ }
+ }
+
+ if (editor.enabled) editor.disable()
+
+ DOM.dispatchEvent(window, 'resize')
+
+ setTimeout(()=>{
+ loader.close()
+ container.classList.add('show')
+ this.lock = false
+ if (callback) callback()
+ }, 25)
+
+ }, 25)
+
+ }
+
+ save() {
+
+ var sessionfile = JSON.stringify(this.session,null,' '),
+ blob = new Blob([sessionfile],{type : 'application/json'})
+
+ saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.json')
+
+ ipc.send('savingSession')
+
+ }
+
+ list(data) {
+
+ for (let i in data) {
+
+ var max = 50
+ var path = data[i],
+ file = path.split('\\').pop().split('/').pop(),
+ length = data[i].length
+
+ path = path.replace(file,'')
+
+ if (length > max - 3) {
+ path = path.substr(0,Math.floor((path.length)/2)-(length-max)/2) + '...' + path.substr(Math.ceil((path.length)/2)+(length-max)/2, path.length)
+ }
+
+ lobby.list.appendChild(html`
+
+ ${file} (${path})
+ ${READ_ONLY? '' : html`${raw(icon('times'))} `}
+
+ `)
+
+ }
+
+ lobby.list.addEventListener('click', function(e){
+ e.preventDefault()
+ if (e.target.hasAttribute('data-session')) {
+ ipc.send('sessionOpen',{path:e.target.getAttribute('data-session')})
+ } else if (!READ_ONLY && e.target.tagName == 'SPAN') {
+ ipc.send('sessionRemoveFromHistory',e.target.parentNode.getAttribute('data-session'))
+ lobby.list.removeChild(e.target.parentNode)
+ }
+ })
+
+ if (!READ_ONLY) {
+
+ var brw = lobby.footer.appendChild(html`${raw(icon('folder-open'))} ${locales('session_browse')} `)
+ var nws = lobby.footer.appendChild(html`${raw(icon('file'))} ${locales('session_new')} `)
+
+ brw.addEventListener('click', (e)=>{
+ this.browse()
+ })
+
+ nws.addEventListener('click', (e)=>{
+ this.create()
+ })
+
+ }
+
+ DOM.addEventListener(lobby.html, 'mousedown touchstart', function(e){
+ if (e.type == 'mousedown') e.preventDefault()
+ e.target.blur()
+ })
+
+ lobby.open()
+
+ }
+
+ open(data) {
+
+ this.load(data,function(){
+ ipc.send('sessionOpened')
+ })
+
+ }
+
+ browse() {
+
+ upload('.json', (path, result)=>{
+ ipc.send('sessionOpen',{file:result,path:path})
+ }, ()=>{
+ new Popup({title: raw(icon('exclamation-triangle')) + ' ' + locales('error'), content: locales('session_uploaderror'), closable:true})
+ })
+
+ }
+
+ create() {
+ this.load({type: 'root'},function(){
+ require('../ui/sidepanel').open()
+ editor.enable()
+ editor.select(widgetManager.getWidgetById('root'))
+ })
+ }
+
+}
+
+var sessionManager = new SessionManager()
+
+module.exports = sessionManager
diff --git a/src/client/app/managers/state.js b/src/client/app/managers/state.js
new file mode 100644
index 00000000..e049b232
--- /dev/null
+++ b/src/client/app/managers/state.js
@@ -0,0 +1,170 @@
+var widgetManager = require('./widgets'),
+ {icon, Popup, upload} = require('../ui/utils'),
+ {saveAs} = require('file-saver'),
+ locales = require('../locales')
+
+
+var StateManager = class StateManager {
+
+ constructor() {
+
+ this.quickState = []
+
+ this.valueStateQueue = {}
+ this.valueOldPropQueue = {}
+ this.valueNewPropQueue = {}
+ this.queueCounter = 0
+
+ }
+
+ get() {
+
+ var data = []
+
+ for (let i in widgetManager.widgets) {
+
+ var widget = widgetManager.widgets[i]
+
+ if (widget.setValue && widget.getValue) {
+
+ var v = widget.getValue()
+
+ if (v!=undefined) {
+
+ data.push([widget.getProp('id'),v])
+ continue
+
+ }
+
+ }
+ }
+
+ return data
+
+ }
+
+ set(preset,send) {
+
+ for (let i in preset) {
+
+ var data = preset[i],
+ widgets = widgetManager.getWidgetById(data[0])
+
+ if (widgets.length) {
+
+ for (var j=widgets.length-1;j>=0;j--) {
+
+ if (widgets[j].setValue) {
+
+ widgets[j].setValue(data[1],{send:send,sync:true})
+
+ }
+
+ }
+
+ }
+
+ }
+
+ }
+
+ send(options) {
+
+ for (let i in widgetManager.widgets) {
+
+ var widget = widgetManager.widgets[i]
+
+ if (widget.sendValue) {
+ widget.sendValue(null, options)
+ }
+ }
+
+ }
+
+ load() {
+
+ upload('.state', (path, result)=>{
+ this.set(JSON.parse(result),true)
+ }, (e)=>{
+ new Popup({title:icon('exclamation-triangle')+' ' + locales('error'), content: locales('state_uploaderror'), closable:true})
+ })
+
+ }
+
+ save() {
+
+ var state = JSON.stringify(this.get(),null,' ')
+ var blob = new Blob([state],{type : 'application/json'})
+ saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.state')
+
+ }
+
+ quickSave(state) {
+
+ if (state) {
+
+ this.quickState = state
+
+ } else {
+
+ this.quickState = this.get()
+
+ }
+
+ }
+
+ quickLoad() {
+
+ this.set(this.quickState,true)
+
+ }
+
+ pushValueState(id, value) {
+ this.valueStateQueue[id] = value
+ }
+
+ pushValueOldProp(id, value) {
+ this.valueOldPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
+ }
+
+ pushValueNewProp(id, value) {
+ this.valueNewPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
+ if (this.queueCounter == 0) this.flush()
+ }
+
+ flush(){
+ for (let id in this.valueStateQueue) {
+ if (this.valueStateQueue[id] !== undefined) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ w.setValue(this.valueStateQueue[id], {sync: true})
+ }
+ }
+ }
+
+ for (let id in this.valueNewPropQueue) {
+ if (this.valueNewPropQueue[id] != this.valueOldPropQueue[id]) {
+ for (let w of widgetManager.getWidgetById(id)) {
+ w.setValue(w.getProp('value'), {sync: true})
+ }
+ }
+ }
+
+ this.valueStateQueue = {}
+ this.valueOldPropQueue = {}
+ this.valueNewPropQueue = {}
+ }
+
+ incrementQueue() {
+ this.queueCounter++
+ }
+
+ decrementQueue() {
+ this.queueCounter--
+ if (this.queueCounter == 0) this.flush()
+ }
+
+}
+
+var stateManager = new StateManager()
+
+module.exports = stateManager
diff --git a/src/client/app/managers/widgets.js b/src/client/app/managers/widgets.js
new file mode 100644
index 00000000..55213095
--- /dev/null
+++ b/src/client/app/managers/widgets.js
@@ -0,0 +1,337 @@
+var EventEmitter = require('../events/event-emitter'),
+ ipc = require('../ipc/')
+
+var WidgetManager = class WidgetManager extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.widgets = {}
+ this.children = []
+
+ this.addressRoute = {}
+ this.idRoute = {}
+ this.linkIdRoute = {}
+
+ this.linkIdLock = []
+ this.linkIdLockDepth = 0
+
+ this.scrollingWidgets = []
+
+ this.preArgsSeparator = '||||'
+
+ this.on('change', this.onChange.bind(this))
+
+ ipc.on('connect', ()=>{
+ for (var hash in this.widgets) {
+ this.registerWidget(this.widgets[hash])
+ }
+ })
+
+ }
+
+ onChange(e) {
+
+ var {id, widget, linkId, options} = e
+
+ if (linkId) {
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ linkId = linkId.map(x=>x.replace(/^>>\s*/, '')).filter(x=>x.indexOf('<<') < 0)
+ linkId = linkId.filter(x=>this.linkIdLock.indexOf(x)<0)
+ this.linkIdLock = this.linkIdLock.concat(linkId)
+ this.linkIdLockDepth++
+ }
+
+ var widgetsById = this.getWidgetById(id),
+ widgetsByLinkId = linkId ? this.getWidgetByLinkId(linkId) : []
+
+ // Widget that share the same id will update each other
+ // without sending any extra osc message
+ if (widgetsById.length > 1) {
+ let v = widget.getValue()
+ for (let i in widgetsById) {
+ if (widgetsById[i] !== widget) {
+ widgetsById[i].setValue(v,{send:false,sync:false})
+ }
+ }
+ }
+
+ // widgets that share the same linkId will update each other.
+ // Updated widgets will send osc messages normally
+ if (widgetsByLinkId.length > 0) {
+ let v = widget.getValue()
+ for (let i in widgetsByLinkId) {
+ if (widgetsByLinkId[i] !== widget) {
+ widgetsByLinkId[i].setValue(v,{send: options.send,sync: true})
+ }
+ }
+ }
+
+ if (linkId && this.linkIdLockDepth) {
+ this.linkIdLockDepth--
+ if (!this.linkIdLockDepth) {
+ this.linkIdLock = []
+ }
+ }
+
+ }
+
+ createAddressRef(widget, preArgs, address) {
+
+ preArgs = widget ? widget.getProp('preArgs') : preArgs
+ address = widget ? widget.getProp('address') : address
+
+ if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
+ if (preArgs === '') preArgs = []
+
+ preArgs = preArgs.map(x=>typeof x === 'object' && x !== null && x.value !== undefined ? x.value : x)
+
+ return preArgs && preArgs.length ?
+ address + this.preArgsSeparator + preArgs.join(this.preArgsSeparator)
+ : address
+
+ }
+
+ addWidget(widget) {
+
+ var hash = widget.hash,
+ address = this.createAddressRef(widget),
+ id = widget.getProp('id'),
+ linkId = widget.getProp('linkId'),
+ scroll = widget.getProp('scroll')
+
+
+ this.widgets[hash] = widget
+
+ if (!this.idRoute[id]) this.idRoute[id] = []
+ this.idRoute[id].push(hash)
+
+ if (address) {
+ if (!this.addressRoute[address]) this.addressRoute[address] = []
+ this.addressRoute[address].push(hash)
+ }
+
+ if (linkId) {
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ linkId = linkId.map(x=>x.replace(/^<<\s*/, '')).filter(x=>x.indexOf('>>') < 0)
+ for (var i in linkId) {
+ if (linkId[i]) {
+ if (!this.linkIdRoute[linkId[i]]) this.linkIdRoute[linkId[i]] = []
+ this.linkIdRoute[linkId[i]].push(hash)
+ }
+ }
+ }
+
+ if (scroll) {
+ this.scrollingWidgets.push(hash)
+ }
+
+ this.registerWidget(widget)
+
+ }
+
+ registerWidget(widget, updatedData, oldData) {
+
+ ipc.send('addWidget', {
+ hash: widget.hash,
+ data: updatedData || {
+ precision: widget.getProp('precision'),
+ preArgs: widget.getProp('preArgs'),
+ split: widget.getSplit(),
+ target: widget.getProp('target'),
+ address: widget.getProp('address'),
+ noSync: widget.getProp('noSync'),
+ }
+ })
+
+ if (updatedData && oldData) {
+ var address = this.createAddressRef(null, oldData.preArgs, oldData.address),
+ newAddress = this.createAddressRef(widget),
+ hash = widget.hash
+
+ if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
+
+ if (!this.addressRoute[newAddress]) this.addressRoute[newAddress] = []
+ this.addressRoute[newAddress].push(hash)
+ }
+
+ }
+
+ removeWidget(widget) {
+
+ var hash = widget.hash,
+ address = this.createAddressRef(widget),
+ linkId = widget.getProp('linkId'),
+ id = widget.getProp('id'),
+ scroll = widget.getProp('scroll')
+
+ if (this.widgets[hash]) {
+ if (this.widgets[hash].onRemove) this.widgets[hash].onRemove()
+
+ delete this.widgets[hash]
+
+ ipc.send('removeWidget', {
+ hash:hash
+ })
+
+ widget.trigger('widget-removed', {widget: widget})
+
+ }
+ if (id && this.idRoute[id].indexOf(hash) != -1) this.idRoute[id].splice(this.idRoute[id].indexOf(hash), 1)
+ if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
+ if (scroll && this.scrollingWidgets.indexOf(hash) != -1) this.scrollingWidgets.splice(this.scrollingWidgets.indexOf(hash), 1)
+
+ if (!Array.isArray(linkId)) linkId = [linkId]
+ for (var i in linkId) {
+ if (linkId[i] && this.linkIdRoute[linkId[i]] && this.linkIdRoute[linkId[i]].indexOf(hash) != -1) this.linkIdRoute[linkId[i]].splice(this.linkIdRoute[linkId[i]].indexOf(hash), 1)
+ }
+
+ }
+
+ removeWidgets(widgets, nested) {
+
+ for (let i in widgets) {
+
+ if (Array.isArray(widgets[i])) {
+
+ this.removeWidgets(widgets[i], true)
+
+ } else if (this.widgets[widgets[i].hash]) {
+
+ this.removeWidget(widgets[i])
+
+ }
+
+ }
+
+ if (!nested) this.purge()
+
+ }
+
+ purge() {
+
+ for (let route of [this.addressRoute, this.idRoute, this.linkIdRoute]) {
+ for (let key in route) {
+ for (let i=route[key].length-1; i>=0; i--) {
+ let hash = route[key][i]
+ if (!this.widgets[hash]) {
+ route[key].splice(i, 1)
+ }
+ }
+ }
+ }
+
+ for (let i in this.scrollingWidgets) {
+ if (!this.widgets[this.scrollingWidgets[i]]) {
+ this.scrollingWidgets.splice(i, 1)
+ }
+ }
+
+ }
+
+ reset() {
+
+ this.removeWidgets(Object.values(this.widgets))
+
+ this.off()
+
+ this.on('change', this.onChange.bind(this))
+
+ }
+
+
+ getWidgetBy(key, dict, widgets = []) {
+
+ var hash, w
+
+ if (Array.isArray(key)) {
+ for (let i in key) {
+ this.getWidgetBy(key[i], dict, widgets)
+ }
+ return widgets
+ }
+
+ if (dict[key]) {
+ for (let i = dict[key].length-1; i>=0; i--) {
+ hash = dict[key][i]
+ w = this.widgets[hash]
+ if (!w) {
+ dict[key].splice(i,1)
+ } else if (widgets.indexOf(w) == -1) {
+ widgets.push(w)
+ }
+ }
+ }
+
+ return widgets
+
+ }
+
+ getWidgetById(id) {
+
+ return this.getWidgetBy(id, this.idRoute)
+
+ }
+
+ getWidgetByLinkId(linkId) {
+
+ return this.getWidgetBy(linkId, this.linkIdRoute)
+
+ }
+
+ getWidgetByAddress(address) {
+
+ return this.getWidgetBy(address, this.addressRoute)
+
+ }
+
+ getWidgetByAddressAndArgs(address, args) {
+
+ var addressref = address,
+ restArgs = args
+
+ if (typeof args == 'object' && args != null) {
+ for (var i = args.length; i >= 0; i--) {
+
+ var ref = this.createAddressRef(null, args.slice(0,i), address)
+
+ if (this.getWidgetByAddress(ref).length) {
+ addressref = ref
+ restArgs = args.slice(i, args.length)
+ break
+ }
+
+ }
+ } else {
+ restArgs = args
+ }
+
+
+ if (restArgs == null || restArgs.length == 0) restArgs = null
+ else if (restArgs.length == 1) restArgs = restArgs[0]
+
+
+ var widgets = this.getWidgetByAddress(addressref)
+
+ return [
+ widgets,
+ restArgs
+ ]
+
+ }
+
+ getWidgetByElement(e, filter = '') {
+ var element = e ? e.closest('[data-widget]' + filter) : undefined
+ if (element) {
+ return element._widget_instance ?
+ element._widget_instance :
+ this.widgets[element.getAttribute('data-widget')]
+ }
+ }
+
+}
+
+var widgetManager = new WidgetManager()
+
+module.exports = widgetManager
diff --git a/src/client/app/osc.js b/src/client/app/osc.js
new file mode 100644
index 00000000..9f9ca096
--- /dev/null
+++ b/src/client/app/osc.js
@@ -0,0 +1,63 @@
+var widgetManager = require('./managers/widgets'),
+ EventEmitter = require('./events/event-emitter'),
+ ipc = require('./ipc/')
+
+var Osc = class Osc extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.syncOnly = false
+ this.remoteControl = {}
+
+ }
+
+ send(data) {
+
+ if (this.syncOnly) {
+
+ this.sync(data)
+
+ } else {
+
+ ipc.send('sendOsc', data)
+
+ }
+
+ }
+
+ sync(data) {
+
+ ipc.send('syncOsc', data)
+
+ }
+
+ receive(data){
+
+ if (this.remoteControl.exists(data.address)) this.remoteControl.exec(data.address, data.args)
+
+ var [widgets, restArgs] = widgetManager.getWidgetByAddressAndArgs(data.address, data.args)
+
+ for (let i in widgets) {
+ let widgetTarget = widgets[i].getProp('target')
+ // if the message target is provided (when message comes from another client connected to the same server)
+ // then we only update the widgets that have the same target
+ if (!data.target || !widgetTarget || String(widgetTarget) === String(data.target)) {
+ // update matching widgets
+ if (widgets[i] && widgets[i].setValue) widgets[i].setValue(restArgs,{send:false,sync:true,fromExternal:!data.target})
+ }
+ }
+
+ this.trigger(data.address, data.args)
+
+ }
+
+}
+
+
+var osc = new Osc()
+
+module.exports = osc
+
+osc.remoteControl = require('./remote-control')
diff --git a/src/client/app/parser.js b/src/client/app/parser.js
new file mode 100644
index 00000000..fb26c14d
--- /dev/null
+++ b/src/client/app/parser.js
@@ -0,0 +1,117 @@
+var widgetManager = require('./managers/widgets'),
+ stateManager = require('./managers/state'),
+ {deepCopy} = require('./utils')
+
+var Parser = class Parser {
+
+ constructor() {
+
+ this.iterators = {}
+ this.widgets = {}
+ this.defaults = {}
+
+ }
+
+ getIterator(id) {
+
+ this.iterators[id] = (this.iterators[id] || 0) + 1
+ return this.iterators[id]
+
+ }
+
+ reset() {
+
+ this.iterators = {}
+ widgetManager.reset()
+
+ }
+
+ parse(options) {
+
+ var {
+ data,
+ parentNode,
+ parent,
+ tab,
+ reCreateOptions,
+ children,
+ index
+ } = options
+
+ var props = data
+
+ // Set default widget type
+ props.type = tab ? 'tab' : props.type || 'fader'
+
+ // Get widget's defaults
+ var defaults = this.defaults[props.type]
+
+ // Set widget's undefined options to default
+ for (let i in defaults) {
+ if (i.indexOf('_') !== 0 && props[i] === undefined) props[i] = deepCopy(defaults[i])
+ }
+
+ // Genrate widget's id, based on its type
+ if (props.id === 'auto' || !props.id) {
+ var id
+ while (!id || widgetManager.getWidgetById(id).length) {
+ id = props.type + '_' + this.getIterator(props.type)
+ }
+ props.id = id
+ }
+
+ // Generate default address
+ props.address = props.address === 'auto' ? '/' + props.id : props.address
+
+
+ // Remove props that don't apply
+ for (let j in props) {
+ if (defaults[j] === undefined || j[0] === '_') delete props[j]
+ }
+
+ // create widget
+ var widget = new this.widgets[props.type]({
+ container:true,
+ props,
+ parent,
+ parentNode,
+ reCreateOptions,
+ children
+ })
+
+ widgetManager.addWidget(widget)
+
+ widget.created(index)
+
+ // set widget's initial state
+ var defaultValue = widget.getProp('default'),
+ currentValue = widget.getProp('value')
+
+ if (currentValue !== '' && currentValue !== undefined) {
+
+ stateManager.pushValueNewProp(widget.getProp('id'), currentValue)
+
+ } else if (defaultValue !== '' && defaultValue !== undefined) {
+
+ widget.setValue(defaultValue)
+
+ }
+
+
+ parentNode.appendChild(widget.container)
+
+ // Editor needs to get the container object
+ return widget
+
+ }
+
+}
+
+var parser = new Parser()
+
+module.exports = parser
+
+parser.widgets = require('./widgets/').widgets
+for (var k in parser.widgets) {
+ parser.defaults[k] = parser.widgets[k].defaults()._props()
+}
diff --git a/src/client/app/remote-control.js b/src/client/app/remote-control.js
new file mode 100644
index 00000000..926379a4
--- /dev/null
+++ b/src/client/app/remote-control.js
@@ -0,0 +1,207 @@
+var {updateWidget} = require('./editor/data-workers'),
+ editor = require('./editor'),
+ widgetManager = require('./managers/widgets'),
+ deepExtend = require('deep-extend')
+
+var callbacks = {
+ '/EDIT': function(args) {
+
+ if (READ_ONLY) return
+
+ var [id, json] = args,
+ newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
+ widgets = widgetManager.getWidgetById(id)
+
+ if (!widgets.length) return
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var widget = widgets[i],
+ data = widget.props
+
+ for (var k in newdata) {
+ data[k] = newdata[k]
+ }
+
+ updateWidget(widget, {
+ reuseChildren: !(newdata.widgets || newdata.tabs)
+ })
+
+ }
+
+ editor.pushHistory()
+
+ },
+ '/EDIT/MERGE': function(args) {
+
+ if (READ_ONLY) return
+
+ var [id, json] = args,
+ newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
+ widgets = widgetManager.getWidgetById(id)
+
+ if (!widgets.length) return
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var widget = widgets[i],
+ data = widget.props
+
+ deepExtend(data, newdata)
+
+ updateWidget(widget, {
+ reuseChildren: !(newdata.widgets || newdata.tabs)
+ })
+
+ }
+
+ editor.pushHistory()
+
+ },
+ '/EDIT/UNDO': function(args) {
+
+ if (READ_ONLY) return
+
+ editor.undo()
+
+ },
+ '/EDIT/REDO': function(args) {
+
+ if (READ_ONLY) return
+
+ editor.redo()
+
+ },
+ '/EDIT/GET': function(args) {
+
+ var [target, idOrAddress, ...preArgs] = args,
+ widgets = []
+
+ if (idOrAddress[0] == '/') {
+
+ widgets = widgetManager.getWidgetByAddress(
+ widgetManager.createAddressRef(null, preArgs, idOrAddress)
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].sendValue({
+ target: [target],
+ address: '/EDIT/GET',
+ preArgs: [idOrAddress, ...preArgs],
+ v: JSON.stringify(widgets[i].props),
+ noSync: true
+ }, {force: true})
+
+ }
+
+ },
+ '/GET': function(args, transparentReply) {
+
+ var [target, idOrAddress, ...preArgs] = args,
+ widgets = []
+
+ if (idOrAddress[0] == '/') {
+
+ widgets = widgetManager.getWidgetByAddress(
+ widgetManager.createAddressRef(null, preArgs, idOrAddress)
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ let overrides = {
+ target: [target],
+ noSync: true
+ }
+
+ if (!transparentReply) {
+
+ overrides.address = '/GET'
+ overrides.preArgs = [idOrAddress, ...preArgs]
+
+ }
+
+ return widgets[i].sendValue(overrides, {force: true})
+
+ }
+
+ },
+ '/GET/#': function(args) {
+
+ callbacks['/GET'](args, true)
+
+ },
+ '/SET': function(args) {
+
+ var [idOrAddress, ...preArgsOrValue] = args,
+ widgets = [],
+ value = null
+
+ if (idOrAddress[0] == '/') {
+
+ [widgets, value] = widgetManager.getWidgetByAddressAndArgs(
+ idOrAddress,
+ preArgsOrValue
+ )
+
+ } else {
+
+ widgets = widgetManager.getWidgetById(idOrAddress)
+ value = preArgsOrValue
+ if (value.length == 0) value = null
+ else if (value.length == 1) value = value[0]
+
+ }
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].setValue(value, {
+ sync: true,
+ send: true
+ })
+
+ }
+
+ },
+ '/TABS': function(args) {
+
+ if (!Array.isArray(args)) args = [args]
+
+ for (let id of args) {
+ let ws = widgetManager.getWidgetById(id)
+ for (let w of ws) {
+ if (w.getProp('type') === 'tab') {
+ var index = w.parent.children.indexOf(w)
+ w.parent.setValue(index, {sync: true, send: false})
+ }
+ }
+ }
+
+ }
+}
+
+// backward-compatibility
+callbacks['/EDIT_SOFT'] = callbacks['/EDIT/MERGE']
+
+module.exports = {
+ exec: function(name, args){
+ if (callbacks[name]) {
+ callbacks[name](args)
+ }
+ },
+ exists: function(name){
+ return name in callbacks
+ }
+}
diff --git a/src/client/app/stacktrace.js b/src/client/app/stacktrace.js
new file mode 100644
index 00000000..c8a5381c
--- /dev/null
+++ b/src/client/app/stacktrace.js
@@ -0,0 +1,28 @@
+var StackTrace = require('stacktrace-js'),
+ ipc = require('./ipc')
+
+window.onerror = function(msg,url,row,col, error) {
+
+ StackTrace.fromError(error).then((stackframes)=>{
+
+ var stringifiedStack = stackframes.filter((sf)=>{
+
+ return !sf.fileName.match('browser-pack')
+
+ }).map(function(sf) {
+
+ if (sf.functionName.match(/Object\./)) sf.functionName = 'require'
+
+ return ` at ${sf.functionName} (${sf.fileName}:${sf.lineNumber}:${sf.columnNumber})`
+
+ }).join('\n')
+
+ ipc.send('errorLog', `[Renderer process error]\n${msg}\n${stringifiedStack}`)
+
+ }).catch(()=>{
+
+ ipc.send('errorLog', `[Renderer process error]\n${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
+
+ })
+
+}
diff --git a/src/client/app/ui/fullscreen.js b/src/client/app/ui/fullscreen.js
new file mode 100644
index 00000000..eea4d0ac
--- /dev/null
+++ b/src/client/app/ui/fullscreen.js
@@ -0,0 +1,41 @@
+var screenfull = require('screenfull'),
+ {Popup} = require('./utils'),
+ locales = require('../locales')
+
+var fullscreen
+
+if (screenfull.enabled) {
+
+ fullscreen = screenfull
+
+} else {
+
+ class IOSFullScreen {
+
+ constructor(){
+
+ this.enabled = !navigator.standalone
+ this.isFullScreen = navigator.standalone
+
+ }
+
+ toggle(){
+
+ new Popup({
+ title: locales('fs_unnavailable'),
+ content: locales('fs_addtohome'),
+ closable: true
+ })
+
+ }
+
+ on(){}
+
+ }
+
+ fullscreen = new IOSFullScreen()
+
+}
+
+
+module.exports = fullscreen
diff --git a/src/client/app/ui/init.js b/src/client/app/ui/init.js
new file mode 100644
index 00000000..b45aa4da
--- /dev/null
+++ b/src/client/app/ui/init.js
@@ -0,0 +1,5 @@
+require('./zoom')
+require('./lobby').create()
+require('./sidepanel')
+require('../events/click')
+require('./ios')
diff --git a/src/client/app/ui/ios.js b/src/client/app/ui/ios.js
new file mode 100644
index 00000000..be04e7e2
--- /dev/null
+++ b/src/client/app/ui/ios.js
@@ -0,0 +1,25 @@
+// Prevent iOS Pull-To-Refresh
+
+var iOS
+
+if (navigator.platform.match(/iPhone|iPod|iPad/)) {
+
+ iOS = true
+
+ var preventNextMove = false
+
+ document.addEventListener('touchstart', (e)=>{
+ if (e.touches.length === 1 && !e.target._drag_widget) preventNextMove = true
+ }, false)
+
+ document.addEventListener('touchmove', (e)=>{
+ // preventDefault the first overscrolling touchmove
+ if (preventNextMove) {
+ preventNextMove = false
+ e.preventDefault()
+ }
+ }, false)
+
+}
+
+module.exports = iOS
diff --git a/src/client/app/ui/lobby.js b/src/client/app/ui/lobby.js
new file mode 100644
index 00000000..48aeb8a1
--- /dev/null
+++ b/src/client/app/ui/lobby.js
@@ -0,0 +1,51 @@
+var html = require('nanohtml')
+
+class Lobby {
+
+ constructor() {
+
+ this.state = 0
+
+ }
+
+ create() {
+
+ this.html = html`
+
+ `
+
+ this.main = DOM.get(this.html, '.main')[0]
+ this.list = DOM.get(this.html, '.list')[0]
+ this.footer = DOM.get(this.html, '.footer')[0]
+
+ }
+
+ open() {
+ if (this.state) return
+ this.state = 1
+ document.body.appendChild(this.html)
+ setTimeout(()=>{
+ this.main.classList.add('show')
+ })
+ }
+
+ close() {
+ if (!this.state) return
+ this.state = 0
+ this.main.classList.remove('show')
+ document.body.removeChild(this.html)
+ }
+
+}
+
+var lobby = new Lobby()
+
+module.exports = lobby
diff --git a/src/client/app/ui/sidepanel.js b/src/client/app/ui/sidepanel.js
new file mode 100644
index 00000000..60779c25
--- /dev/null
+++ b/src/client/app/ui/sidepanel.js
@@ -0,0 +1,296 @@
+var state = require('../managers/state'),
+ session = require('../managers/session'),
+ editor = require('../editor/'),
+ {icon} = require('./utils'),
+ fullscreen = require('./fullscreen'),
+ {enableTraversingGestures, disableTraversingGestures} = require('../events/drag'),
+ locales = require('../locales'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+var sidepanelData = [
+ {
+ actions: [
+ {
+ title: locales('sidepanel_fs') + (ELECTRON_FULLSCREEN ? ' (F11)' : ''),
+ action:()=>{
+ if (fullscreen.enabled) fullscreen.toggle()
+ },
+ class:'toggle fullscreenToggle' + (!fullscreen.enabled || ELECTRON_FULLSCREEN ? ' disabled' : '')
+ }
+
+ ]
+ },
+ {
+ title: icon('sliders-h') + ' ' + locales('sidepanel_state'),
+ actions: [
+ {
+ title: locales('state_store'),
+ action:()=>{
+ state.quickSave()
+ DOM.get('.quickload')[0].classList.remove('disabled')
+ }
+ },
+ {
+ title: locales('state_recall'),
+ action:state.quickLoad.bind(state),
+ class:'disabled quickload'
+ },
+ {
+ title: locales('state_send'),
+ action:state.send.bind(state)
+ },
+ {
+ title: locales('state_import'),
+ action:state.load.bind(state)
+ },
+ {
+ title: locales('state_export'),
+ action:state.save.bind(state)
+ }
+ ]
+ },
+ {
+ title: icon('magic') + ' ' + locales('sidepanel_traversing'),
+ actions: [
+ {
+ title: locales('traversing_on'),
+ action:(el)=>{
+ DOM.each(el.parentNode, 'a', (el)=>{
+ el.classList.remove('on')
+ })
+ el.classList.add('on')
+ var container = document.getElementById('container')
+ disableTraversingGestures(container)
+ enableTraversingGestures(container)
+ },
+ class:'traversingEnable'
+ },
+ {
+ title: locales('traversing_smart'),
+ action:(el)=>{
+ DOM.each(el.parentNode, 'a', (el)=>{
+ el.classList.remove('on')
+ })
+ el.classList.add('on')
+ var container = document.getElementById('container')
+ disableTraversingGestures(container)
+ enableTraversingGestures(container, {smart: true})
+ },
+ class:'traversingSmart'
+ },
+ {
+ title: locales('traversing_off'),
+ action:(el)=>{
+ DOM.each(el.parentNode, 'a', (el)=>{
+ el.classList.remove('on')
+ })
+ el.classList.add('on')
+ disableTraversingGestures(document.getElementById('container'))
+ },
+ class:'traversingDisable on'
+ }
+ ]
+ },
+ {
+ title: icon('edit') + ' ' + locales('sidepanel_editor'),
+ class:'editor-menu',
+ actions: [
+ {
+ title: locales('editor_on'),
+ action:editor.enable.bind(editor),
+ class:'enable-editor'
+ },
+ {
+ title: locales('editor_off'),
+ action:editor.disable.bind(editor),
+ class:'on disable-editor'
+ },
+ {
+ title: locales('editor_root'),
+ class:'editor-root disabled'
+ },
+ {
+ title: locales('editor_load'),
+ action:session.browse.bind(session)
+ },
+ {
+ title: locales('editor_save'),
+ action:session.save.bind(session)
+ }
+ ]
+ },
+]
+
+
+if (navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) {
+
+ var NoSleep = require('nosleep.js'),
+ noSleep = new NoSleep(),
+ noSleepState = false
+
+ sidepanelData[0].actions.push({
+ title: locales('sidepanel_nosleep'),
+ class: 'toggle',
+ action:(el)=>{
+ noSleepState = el.classList.toggle('on')
+ if (noSleepState) {
+ noSleep.enable()
+ } else {
+ noSleep.disable()
+ }
+ }
+ })
+
+}
+
+
+
+var options = html``
+
+for (let i in sidepanelData) {
+
+ let data = sidepanelData[i],
+ item = html`
+
+
+
+ ${data.title ? html`
${raw(data.title)}
` : ''}
+
+
+
+ `,
+ wrapper = DOM.get(item, '.actions')[0]
+
+ for (let j in data.actions) {
+
+ let actionData = data.actions[j],
+ element = html`${actionData.title} `
+
+ if (actionData.action) element.addEventListener('click', ()=>{actionData.action(element)})
+
+ wrapper.appendChild(element)
+ }
+
+ options.appendChild(item)
+
+}
+
+
+var sidepanel = document.getElementById('sidepanel')
+
+sidepanel.appendChild(html`
+
+`)
+
+sidepanel.appendChild(options)
+
+sidepanel.appendChild(html`
`)
+
+
+// Fullscreen
+
+var fsToggle = DOM.get(sidepanel, '.fullscreenToggle')[0]
+
+if (fullscreen.enabled) {
+ fullscreen.on('change', ()=>{
+ fsToggle.classList.toggle('on', fullscreen.isFullScreen)
+ })
+}
+
+// open / close / toggle
+
+var sidepaneLock = false
+
+function sidepanelOpen() {
+
+ sidepaneLock = true
+
+ DOM.each(document, '#open-toggle, #sidepanel', (el)=>{
+ el.classList.add('sidepanel-open')
+ })
+
+ setTimeout(function(){
+ DOM.get('#container')[0].classList.add('sidepanel-open')
+ setTimeout(function(){
+ DOM.dispatchEvent(window, 'resize')
+ sidepaneLock = false
+ }, 25)
+ }, 250)
+
+}
+
+function sidepanelClose() {
+
+ if (sidepaneLock) return
+
+ DOM.each(document, '#open-toggle, #sidepanel, #container', (el)=>{
+ el.classList.remove('sidepanel-open')
+ })
+
+ setTimeout(function(){
+ DOM.dispatchEvent(window, 'resize')
+ }, 25)
+
+}
+
+function sidepanelToggle() {
+
+ if (sidepanel.classList.contains('sidepanel-open')) {
+ sidepanelClose()
+ } else {
+ sidepanelOpen()
+ }
+
+}
+
+
+DOM.get('#container')[0].addEventListener('fast-click', function(e){
+
+ if (e.target.id == 'open-toggle') {
+ e.stopPropagation()
+ e.detail.preventOriginalEvent = true
+ sidepanelToggle()
+ }
+
+})
+
+document.addEventListener('keydown', function(e){
+ // F10
+ if (e.keyCode==121) sidepanelToggle()
+})
+
+
+// Sidepanel resize
+
+var resizeHandle = html`${raw(icon('bars'))}
`,
+ sidepanelWidth
+
+
+sidepanel.appendChild(resizeHandle)
+
+$(resizeHandle).draggable({
+ cursor:'col-resize',
+ start: ()=>{
+ sidepanelWidth = parseInt(sidepanel.offsetWidth) / PXSCALE
+ sidepanel.classList.add('resizing')
+ },
+ drag: (event, ui)=>{
+ var delta = (ui.originalPosition.left - ui.position.left) / PXSCALE,
+ newWidth = Math.max(sidepanelWidth + delta, 300)
+ if (!isNaN(sidepanelWidth)) {
+ document.documentElement.style.setProperty('--sidepanel-size', newWidth + 'rem')
+ }
+ },
+ stop: ()=>{
+ sidepanel.classList.remove('resizing')
+ }
+})
+
+
+
+module.exports = {
+ open: sidepanelOpen,
+ close: sidepanelClose,
+ toggle: sidepanelToggle
+}
diff --git a/src/client/app/ui/utils.js b/src/client/app/ui/utils.js
new file mode 100644
index 00000000..40ac52e7
--- /dev/null
+++ b/src/client/app/ui/utils.js
@@ -0,0 +1,135 @@
+var popupSingleton = null,
+ uploadSingleton = null,
+ locales = require('../locales'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+module.exports = {
+
+ Popup: class Popup {
+
+ constructor(options) {
+
+ if (options.closable) {
+
+ if (popupSingleton) {
+ popupSingleton.close()
+ popupSingleton = null
+ }
+
+ popupSingleton = this
+
+ }
+
+ this.closable = options.closable
+ this.escKey = options.closable || options.escKey
+ this.enterKey = options.enterKey
+ this.content = options.content
+ this.title = options.title
+ this.state = 0
+
+ this.html = html`
+
+ `
+
+ if (this.closable) {
+ var closer = DOM.get(this.html, '.popup-title .closer')[0]
+ this.html.addEventListener('fast-click',(e)=>{
+ if (e.target === this.html || e.target === closer) {
+ e.detail.preventOriginalEvent = true
+ this.close()
+ }
+ })
+ }
+
+ if (this.escKey) {
+ this.escKeyHandler = ((e)=>{
+ if (e.keyCode==27) this.close()
+ }).bind(this)
+ }
+
+ if (this.enterKey) {
+ this.enterKeyHandler = ((e)=>{
+ if (e.keyCode == 13) this.enterKey.call(this, e)
+ }).bind(this)
+ }
+
+ this.open()
+
+
+ }
+
+
+
+ close() {
+ if (!this.state) return
+ this.state = 0
+
+ if (this.escKey) document.removeEventListener('keydown', this.escKeyHandler)
+ if (this.enterKey) document.removeEventListener('keydown', this.enterKeyHandler)
+ document.body.removeChild(this.html)
+ }
+
+ open() {
+ if (this.state) return
+ this.state = 1
+
+ if (this.escKey) document.addEventListener('keydown', this.escKeyHandler)
+ if (this.enterKey) document.addEventListener('keydown', this.enterKeyHandler)
+ document.body.appendChild(this.html)
+ }
+ },
+
+ loading: function(title){
+ return new module.exports.Popup({
+ title: title,
+ content: html`
`,
+ closable: false
+ })
+ },
+ icon: function(i) {
+ return ` `
+ },
+ iconify:function(string){
+ return String(string).replace(/\^[^\s]*/g,(x)=>{return module.exports.icon(x.substring(1))})
+ },
+ upload: function(types, ok, error) {
+
+ if (uploadSingleton) document.body.removeChild(uploadSingleton)
+
+ uploadSingleton = html` `
+ document.body.appendChild(uploadSingleton)
+
+ uploadSingleton.addEventListener('change',function(e){
+
+
+ var reader = new FileReader(),
+ file = e.target.files[0],
+ loader = module.exports.loading(locales('loading_upload'))
+
+ reader.onerror = reader.onabort = function() {
+ loader.close()
+ error()
+ }
+
+ reader.onload = function(e) {
+ loader.close()
+ ok(file.path, e.target.result)
+ }
+
+ reader.readAsText(file, 'utf-8')
+
+ })
+
+ uploadSingleton.click()
+
+ }
+
+}
diff --git a/src/client/app/ui/zoom.js b/src/client/app/ui/zoom.js
new file mode 100644
index 00000000..bc490c49
--- /dev/null
+++ b/src/client/app/ui/zoom.js
@@ -0,0 +1,29 @@
+// mousewheel zoom
+
+var mod = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+document.addEventListener('mousewheel', function(event) {
+ if (event.ctrlKey) event.preventDefault()
+ if (event[mod]) {
+
+ event.preventDefault()
+
+ if (event.deltaY === 0) return
+
+ var d = - event.deltaY / (10 * Math.abs(event.deltaY))
+
+ PXSCALE = parseFloat(d) + parseFloat(PXSCALE)
+ document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+ DOM.dispatchEvent(window, 'resize')
+ }
+})
+
+document.addEventListener('keydown', function(event){
+ if (event[mod] && (event.keyCode == 96 || event.keyCode == 48)) {
+ PXSCALE = INITIALZOOM
+ document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+ DOM.dispatchEvent(window, 'resize')
+ }
+})
diff --git a/src/client/app/utils.js b/src/client/app/utils.js
new file mode 100644
index 00000000..b2a9c1fd
--- /dev/null
+++ b/src/client/app/utils.js
@@ -0,0 +1,41 @@
+module.exports = {
+
+ deepCopy: function(obj, precision) {
+
+ var copy = obj
+
+ if (obj === null) {
+ return obj
+ }
+
+ if (typeof obj === 'object') {
+ copy = Array.isArray(obj) ? [] : {}
+ for (let key in obj) {
+ copy[key] = module.exports.deepCopy(obj[key], precision)
+ }
+ } else if (typeof obj == 'number') {
+ return precision === undefined ? copy : parseFloat(copy.toFixed(precision))
+ }
+
+ return copy
+
+ },
+
+ deepEqual: function(a, b) {
+
+ // about 2,75 x faster than JSON.stringify(a) === JSON.stringify(b)
+
+ var ta = typeof a,
+ tb = typeof b
+
+ if (ta !== tb) {
+ return false
+ } else if (ta === 'object') {
+ return JSON.stringify(a) === JSON.stringify(b)
+ } else {
+ return a === b
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/buttons/dropdown.js b/src/client/app/widgets/buttons/dropdown.js
new file mode 100644
index 00000000..8a15f868
--- /dev/null
+++ b/src/client/app/widgets/buttons/dropdown.js
@@ -0,0 +1,108 @@
+var Widget = require('../common/widget'),
+ {iconify} = require('../../ui/utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Dropdown extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _dropdown:'dropdown',
+
+ values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
+ '`Array` of possible values to switch between : `[1,2,3]`',
+ '`Object` of label:value pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ 'An empty option will always be prepended to values (sends an osc message without any value); it can be hidden by adding `option:first-child{display:none}` to the widget\'s `css`'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ this.select = this.widget.appendChild(html` `)
+
+ this.values = []
+ this.keys = []
+
+ this.parseValues()
+
+ this.select.addEventListener('change', ()=>{
+ this.setValue(this.values[this.select.selectedIndex - 1], {sync:true, send:true, fromLocal:true})
+ })
+
+ this.value = undefined
+ this.select.selectedIndex = -1
+ this.container.classList.add('noselect')
+
+ }
+
+ parseValues() {
+
+ var i = 0,
+ values = this.getProp('values')
+
+ if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
+ values = values !== '' ? [values] : []
+ }
+
+ this.select.innerHTML = ''
+ this.select.appendChild(html` `)
+
+ this.values = []
+
+ for (var k in values) {
+ this.values.push(values[k])
+ this.select.appendChild(html`
+
+ ${raw(iconify(parseFloat(k) != k ? k : values[k]))}
+
+ `)
+ i++
+ }
+
+ }
+
+ setValue(v,options={}) {
+
+ var i = this.values.indexOf(v)
+
+ this.value = this.values[i]
+
+ if (!options.fromLocal) this.select.selectedIndex = i + 1
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'values':
+ this.parseValues()
+ this.setValue(this.value)
+ return
+
+ }
+
+ return ret
+
+ }
+
+}
+
+Dropdown.dynamicProps = Dropdown.prototype.constructor.dynamicProps.concat(
+ 'values'
+)
+
+
+module.exports = Dropdown
diff --git a/src/client/app/widgets/buttons/push.js b/src/client/app/widgets/buttons/push.js
new file mode 100644
index 00000000..cc124dc5
--- /dev/null
+++ b/src/client/app/widgets/buttons/push.js
@@ -0,0 +1,132 @@
+var Widget = require('../common/widget'),
+ osc = require('../../osc'),
+ html = require('nanohtml')
+
+class Push extends Widget {
+
+ static defaults() {
+
+
+ return super.defaults({
+
+ _push: 'push',
+
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ norelease: {type: 'boolean', value: false, help: 'Set to `true` to prevent sending any osc message when releasing the button'},
+
+ }, ['_value', 'default', 'value'])
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ this.state = 0
+ this.active = 0
+ this.lastChanged = 'state'
+
+ this.on('draginit',()=>{
+ if (this.active) return
+ this.setValuePrivate(this.getProp('on'),{send:true,sync:true})
+ }, {element: this.widget})
+
+ this.on('dragend',()=>{
+ this.setValuePrivate(this.getProp('off'),{send:true,sync:true})
+ }, {element: this.widget})
+
+ this.value = this.getProp('off')
+
+
+ }
+
+ updateValue(){
+
+ this.value = this[this.lastChanged] ?
+ this.getProp('on') != null && this.getProp('on').value !== undefined ? this.getProp('on').value : this.getProp('on')
+ :
+ this.getProp('off') != null && this.getProp('off').value !== undefined ? this.getProp('off').value : this.getProp('off')
+
+ }
+
+ setValuePrivate(v,options={}) {
+
+ if (typeof v == 'object' && v !== null) v = v.value
+ if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
+ this.widget.classList.add('active')
+ this.container.classList.add('active')
+ this.active = 1
+ this.lastChanged = 'active'
+ this.updateValue()
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+ } else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
+ this.widget.classList.remove('active')
+ this.container.classList.remove('active')
+ this.active = 0
+ this.lastChanged = 'active'
+ this.updateValue()
+ if (options.send) this.sendValue(null, {syncOnly: this.getProp('norelease')})
+ if (options.sync) this.changed(options)
+ }
+
+ }
+
+ setValue(v,options={}) {
+
+ if (!options.fromExternal) {
+ this.setValuePrivate(v,options)
+ return
+ }
+ if (typeof v == 'object' && v !== null) v = v.value
+ if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
+ this.widget.classList.add('on')
+ this.container.classList.add('on')
+ this.state = 1
+ if (options.send) this.sendValue()
+ this.lastChanged = 'state'
+ if (options.sync) this.changed(options)
+ } else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
+ this.widget.classList.remove('on')
+ this.container.classList.remove('on')
+ this.state = 0
+ if (options.send) this.sendValue()
+ this.lastChanged = 'state'
+ if (options.sync) this.changed(options)
+ }
+
+ }
+
+ sendValue(overrides, options={}) {
+
+ if (!options.syncOnly) {
+
+ super.sendValue(overrides, options)
+
+ } else {
+
+ osc.sync({
+ h: this.hash,
+ v: this.value
+ })
+
+ }
+
+ }
+
+}
+
+Push.dynamicProps = Push.prototype.constructor.dynamicProps.concat(
+ 'on',
+ 'off',
+ 'norelease'
+)
+
+module.exports = Push
diff --git a/src/client/app/widgets/buttons/switch.js b/src/client/app/widgets/buttons/switch.js
new file mode 100644
index 00000000..80bf6af3
--- /dev/null
+++ b/src/client/app/widgets/buttons/switch.js
@@ -0,0 +1,101 @@
+var Widget = require('../common/widget'),
+ {iconify} = require('../../ui/utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+module.exports = class Switch extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _switch:'switch',
+
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display values horizontally'},
+ showValues: {type: 'boolean', value: false, help: 'If values is an object, set to `true` to display both values and labels instead of labels only'},
+ values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
+ '`Array` of possible values to switch between : `[1,2,3]`',
+ '`Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+
+ if (this.getProp('horizontal')) this.widget.classList.add('horizontal')
+
+ this.values = []
+ this.stringValues = []
+
+ var values = this.getProp('values')
+
+ if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
+ values = [values]
+ }
+
+ var isArray = Array.isArray(values)
+
+ for (var k in values) {
+
+ this.values.push(values[k])
+
+ if (typeof values[k] == 'object') {
+ this.stringValues.push(JSON.stringify(values[k]))
+ } else {
+ this.stringValues.push(0)
+ }
+
+ var label = isArray ? values[k]: k
+ if (this.getProp('showValues') && !isArray) label = label + ': ' + (this.stringValues[this.stringValues.length - 1] || values[k])
+
+ this.widget.appendChild(html`
+ ${raw(iconify(label))}
+ `)
+
+ }
+
+ this.value = undefined
+
+ this.on('draginit', (e)=>{
+
+ var index = 0,
+ node = e.target
+
+ while ( (node = node.previousSibling) ) {
+ if (node.nodeType != 3) {
+ index++
+ }
+ }
+
+ var value = this.values[index]
+
+ if (value!=this.value || this.value===undefined) this.setValue(value,{sync:true,send:true})
+
+ }, {element: this.widget})
+
+ }
+
+ setValue(v, options={}) {
+
+ var i = typeof v == 'object' ?
+ this.stringValues.indexOf(JSON.stringify(v)) :
+ this.values.indexOf(v)
+
+ DOM.each(this.widget, '.on', (el)=>{el.classList.remove('on')})
+
+ if (i!=-1) {
+ this.value = this.values[i]
+ DOM.get(this.widget, '.value')[i].classList.add('on')
+ if (options.send) this.sendValue(this.value)
+ if (options.sync) this.changed(options)
+ } else {
+ this.value = undefined
+ if (options.sync) this.changed(options)
+ }
+
+ }}
diff --git a/src/client/app/widgets/buttons/toggle.js b/src/client/app/widgets/buttons/toggle.js
new file mode 100644
index 00000000..c87c6760
--- /dev/null
+++ b/src/client/app/widgets/buttons/toggle.js
@@ -0,0 +1,91 @@
+var Widget = require('../common/widget'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml')
+
+class Toggle extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _toggle: 'toggle',
+
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the button require a double tap to be toggled instead of a single tap'},
+ led: {type: 'boolean', value: false, help: 'Set to `true` to display the toggle\'s state with a led'},
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ this.state = 0
+ this.active = false
+
+ if (this.getProp('led')) this.container.classList.add('led')
+
+ if (this.getProp('doubleTap')) {
+
+ doubletab(this.widget, ()=>{
+ var newVal = this.state?this.getProp('off'):this.getProp('on')
+ this.setValue(newVal,{sync:true,send:true})
+ })
+
+ } else {
+
+ this.on('draginit',()=>{
+ if (this.active) return
+ this.active = true
+ var newVal = this.state?this.getProp('off'):this.getProp('on')
+ this.setValue(newVal,{sync:true,send:true})
+ }, {element: this.widget})
+
+ this.on('dragend',()=>{
+ this.active = false
+ }, {element: this.widget})
+
+ }
+
+ this.value = this.getProp('off')
+
+ }
+
+ setValue(v,options={}) {
+
+ if (typeof v == 'object' && v !== null) v = v.value
+ if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
+ this.widget.classList.add('on')
+ this.container.classList.add('on')
+ this.state = 1
+ this.value = this.getProp('on')
+ if (options.send) this.sendValue()
+ } else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
+ this.widget.classList.remove('on')
+ this.container.classList.remove('on')
+ this.state = 0
+ this.value = this.getProp('off')
+ if (options.send) this.sendValue()
+ }
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
+
+Toggle.dynamicProps = Toggle.prototype.constructor.dynamicProps.concat(
+ 'on',
+ 'off'
+)
+
+module.exports = Toggle
diff --git a/src/client/app/widgets/common/canvas.js b/src/client/app/widgets/common/canvas.js
new file mode 100644
index 00000000..9c8b90af
--- /dev/null
+++ b/src/client/app/widgets/common/canvas.js
@@ -0,0 +1,205 @@
+var Widget = require('./widget')
+
+class CanvasQueue {
+
+ constructor() {
+
+ this.queue = {}
+ this.flushed = 0
+ this.running = false
+ this.frameLength = 1000 / CANVAS_FRAMERATE
+ this.lastFrame = 0
+ this.bindedLoop = this.loop.bind(this)
+
+ }
+
+ push(widget) {
+
+ this.queue[widget.hash] = widget
+ this.flushed = 0
+
+ if (!this.running) {
+ this.running = true
+ requestAnimationFrame(this.bindedLoop)
+ }
+
+ }
+
+ flush() {
+
+ for (var h in this.queue) {
+ this.queue[h].draw()
+ }
+
+ this.queue = {}
+ this.flushed++
+
+ }
+
+ loop(timestamp) {
+
+ if (this.flushed >= 10) {
+ this.running = false
+ return
+ }
+
+ requestAnimationFrame(this.bindedLoop)
+
+ var delta = timestamp - this.lastFrame
+
+ if (delta > this.frameLength) {
+ this.lastFrame = timestamp - (delta % this.frameLength)
+ this.flush()
+ }
+
+ }
+
+}
+
+var canvasQueue = new CanvasQueue()
+
+
+class Canvas extends Widget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.canvas = DOM.get(this.widget, 'canvas')[0]
+ this.ctx = this.canvas.getContext('2d')
+
+ this.height = undefined
+ this.width = undefined
+ this.scaling = 1
+
+ this.clearRect = []
+
+ this.visible = false
+
+ this.colors = {}
+
+ this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
+
+ this.ctx.arc = (x, y, r, s, e, c)=>{
+
+ CanvasRenderingContext2D.prototype.arc.call(this.ctx, x, y, Math.max(0,r), s, e, c)
+
+ }
+
+ }
+
+ resizeHandleProxy() {
+
+ this.resizeHandle(...arguments)
+
+ }
+
+ resizeHandle(event){
+
+ var {width, height, style} = event,
+ ratio = CANVAS_SCALING * this.scaling
+
+ this.height = height
+ this.width = width
+
+ this.canvas.setAttribute('width', width * ratio)
+ this.canvas.setAttribute('height', height * ratio)
+
+ this.clearRect = []
+
+ if (ratio != 1) {
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.scale(ratio, ratio)
+ }
+
+ this.cacheCanvasStyle(style)
+
+ if (!this.visible) this.visible = true
+
+ requestAnimationFrame(this.draw.bind(this))
+
+ }
+
+ cacheCanvasStyle(style){
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ this.colors.custom = style.getPropertyValue('--color-custom')
+ this.colors.track = style.getPropertyValue('--color-track')
+ this.colors.text = style.getPropertyValue('--color-text')
+ this.colors.raised = style.getPropertyValue('--color-raised')
+ this.colors.bg = style.getPropertyValue('--color-bg')
+ this.colors.fg = style.getPropertyValue('--color-fg')
+ this.colors.faded = style.getPropertyValue('--color-faded')
+ this.colors.light = style.getPropertyValue('--color-light')
+
+ this.fontFamily = style.getPropertyValue('font-family')
+ this.textAlign = style.getPropertyValue('text-align')
+ this.fontSize = parseFloat(style.getPropertyValue('font-size'))
+ this.fontWeight = parseFloat(style.getPropertyValue('font-weight'))
+
+ this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
+ this.ctx.textBaseline = 'middle'
+ this.ctx.textAlign = this.textAlign
+
+ }
+
+ clear() {
+
+ if (!this.clearRect.length) {
+ this.ctx.clearRect(0, 0, this.width, this.height)
+ return
+ }
+
+ if (typeof this.clearRect[0] == 'object') {
+ for (let i in this.clearRect) {
+ this.ctx.clearRect(...this.clearRect[i])
+ }
+ return
+ }
+
+ this.ctx.clearRect(...this.clearRect)
+
+ }
+
+ batchDraw() {
+
+ if (this.visible) canvasQueue.push(this)
+
+ }
+
+ draw(){
+ throw new Error('Calling unimplemented draw() method')
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'color':
+ this.cacheCanvasStyle()
+ this.batchDraw()
+ return
+
+ }
+
+ return ret
+
+
+ }
+
+ onRemove() {
+ this.off('resize')
+ super.onRemove()
+ }
+
+}
+
+Canvas.dynamicProps = Canvas.prototype.constructor.dynamicProps.concat(
+ 'on',
+ 'off'
+)
+
+module.exports = Canvas
diff --git a/src/client/app/widgets/common/container.js b/src/client/app/widgets/common/container.js
new file mode 100644
index 00000000..235909f6
--- /dev/null
+++ b/src/client/app/widgets/common/container.js
@@ -0,0 +1,75 @@
+var Widget = require('./widget')
+
+class Container extends Widget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.on('widget-created', (e)=>{
+
+ if (e.widget.parent === this) {
+
+ var index = e.index
+ if (index !== undefined) {
+ if (!this.children[index]) {
+ this.children[index] = e.widget
+ } else {
+ this.children.splice(index, 0, e.widget)
+ }
+ } else {
+ this.children.push(e.widget)
+ }
+ }
+
+ })
+
+ this.on('widget-removed', (e)=>{
+
+ if (e.widget.parent === this) {
+ this.children.splice(this.children.indexOf(e.widget), 1)
+ }
+
+ })
+
+ }
+
+ alignChildrenProps() {
+
+ // this is needed after editor.undo to fix data shifting:
+ // say we have children [a, b, c] bound with session data [a, b, c]
+ // we delete one widget [ b, c] the data changes too: [ b, c]
+ // undo first only mutates the data: [a, b, c]
+ // so children have their data mutated too, child 'b' gets data 'a' and so on
+ // each child has to get the data corresponding to its index again.
+ // ...right ? :)
+ var tabs = this.getProp('tabs'),
+ widgets= this.getProp('widgets'),
+ type = tabs && tabs.length ? 'tabs' : widgets && widgets.length ? 'widgets' : null,
+ data = type ? this.getProp(type) : null
+
+ if (!type) return
+
+
+ for (let i in this.children) {
+ if (this.children[i] && data[i]) {
+ this.children[i].props = data[i]
+ this.children[i].cachedProps[type] = this.children[i].props[type]
+ if (this.children[i].alignChildrenProps) {
+ this.children[i].alignChildrenProps()
+ }
+ }
+ }
+
+ }
+
+ onRemove() {
+
+ super.onRemove()
+
+ }
+
+}
+
+
+module.exports = Container
diff --git a/src/client/app/widgets/common/osc-receiver.js b/src/client/app/widgets/common/osc-receiver.js
new file mode 100644
index 00000000..1ed396a8
--- /dev/null
+++ b/src/client/app/widgets/common/osc-receiver.js
@@ -0,0 +1,60 @@
+var osc = require('../../osc')
+
+module.exports = class OscReceiver {
+
+ constructor(address, value, parent, propName) {
+
+ try {
+ this.value = JSON.parse(value)
+ } catch (err) {
+ this.value = value
+ }
+
+ this.parent = parent
+ this.propNames = [propName]
+ this.bindedCallback = this.callback.bind(this)
+ this.setAddress(address)
+
+ }
+
+ setAddress(address) {
+
+ if (this.address !== address) {
+
+ if (this.address) osc.off(this.address, this.bindedCallback, this.parent)
+
+ this.address = address
+ osc.on(this.address, this.bindedCallback, {context: this.parent})
+
+ }
+
+ }
+
+ addProp(propName){
+
+ if (!this.propNames.includes(propName)) this.propNames.push(propName)
+
+ }
+
+ callback(args) {
+
+ if (typeof args !== 'object') args = [args]
+ var preArgs = this.parent.getProp('preArgs') || []
+ if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
+ if (args.length >= preArgs.length) {
+ for (var i in preArgs) {
+ if (preArgs[i] !== args[i]) return
+ }
+ var val = args.slice(preArgs.length)
+ if (val.length < 2) val = val[0]
+ try {
+ this.value = JSON.parse(val)
+ } catch (err) {
+ this.value = val
+ }
+ this.parent.updateProps(this.propNames, this.parent)
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/common/widget.js b/src/client/app/widgets/common/widget.js
new file mode 100644
index 00000000..583047e7
--- /dev/null
+++ b/src/client/app/widgets/common/widget.js
@@ -0,0 +1,873 @@
+var EventEmitter = require('../../events/event-emitter'),
+ osc = require('../../osc'),
+ nanoid = require('nanoid/generate'),
+ widgetManager = require('../../managers/widgets'),
+ {math} = require('../utils'),
+ scopeCss = require('scope-css'),
+ {iconify} = require('../../ui/utils'),
+ resize = require('../../events/resize'),
+ OscReceiver = require('./osc-receiver'),
+ {deepCopy, deepEqual} = require('../../utils'),
+ html = require('nanohtml'),
+ updateWidget = ()=>{}
+
+var oscReceiverState = {}
+
+var OSCProps = [
+ 'precision',
+ 'address',
+ 'preArgs',
+ 'target',
+ 'bypass'
+]
+
+var dummyDOM
+
+DOM.ready(()=>{
+ dummyDOM = html`
`
+})
+
+setTimeout(()=>{
+ updateWidget = require('../../editor/data-workers').updateWidget
+})
+
+class Widget extends EventEmitter {
+
+ static defaults(insert={}, except=[], push={}) {
+
+ var defaults = {
+
+ type: {type: 'string', value: 'auto', help: ''},
+ id: {type: 'string', value: 'auto', help: 'Widgets sharing the same `id` will act as clones and update each other\'s value(s) without sending extra osc messages.' },
+ linkId: {type: 'string|array', value: '', help: [
+ 'Widgets sharing the same `linkId` update each other\'s value(s) AND send their respective osc messages.',
+ 'When prefixed with >>, the `linkId` will make the widget act as a master (sending but not receiving)',
+ 'When prefixed with <<, the `linkId` will make the widget act as a slave (receiving but not sending)'
+ ]},
+
+ _geometry:'geometry',
+
+ left: {type: 'number|string', value: 'auto', help: [
+ 'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
+ 'Otherwise, the widget will be absolutely positioned'
+ ]},
+ top: {type: 'number|percentage', value: 'auto', help: [
+ 'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
+ 'Otherwise, the widget will be absolutely positioned'
+ ]},
+ width: {type: 'number|percentage', value: 'auto', help: ''},
+ height: {type: 'number|percentage', value: 'auto', help: ''},
+
+ _style:'style',
+
+ label: {type: 'string|boolean', value: 'auto', help: [
+ 'Set to `false` to hide completely',
+ 'Insert icons using the prefix ^ followed by the icon\'s name : ^play, ^pause, etc'
+ ]},
+ color: {type: 'string', value: 'auto', help: 'CSS color code. Set to "auto" to inherit from parent widget.'},
+ css: {type: 'string', value: '', help: 'CSS rules'},
+
+ _value: 'value',
+
+ default: {type: '*', value: '', help: 'If set, the widget will be initialized with this value when the session is loaded.'},
+ value: {type: '*', value: '', help: 'Define the widget\'s value depending on other widget\'s values / properties using property inheritance and property maths'},
+
+ _osc: 'osc',
+
+ precision: {type: 'integer|string', value: 2, help: [
+ 'Defines the number of decimals to display and to send.',
+ 'Set to `0` to send integers only.',
+ 'Data type can be specified by appending a valid osc type tag to the precision value, for example : `3d` will make the widget send double precision numbers rounded to three decimals'
+ ]},
+ address: {type: 'string', value: 'auto', help: 'OSC address for sending messages, it must start with a /'},
+ preArgs: {type: '*|array', value: '', help: [
+ 'A value or array of values that will be prepended to the OSC messages.',
+ 'Values can be defined as objects if the osc type tag needs to be specified: `{type: "i", value: 1}`'
+ ]},
+ target: {type: 'string|array|null', value: '', help: [
+ 'This defines the targets of the widget\'s OSC messages',
+ '- A `string` or `array` of strings formatted as follow: `ip:port` or `["ip:port"]`',
+ '- If midi is enabled, targets can be `midi:device_name`',
+ '- The special item `"self"` can be used to refer to the emitting client directly.',
+ '- If no target is set, messages can still be sent if the server has default targets',
+ '- The server\'s default targets can be bypassed by setting one of the items to `null`'
+ ]},
+ bypass: {type: 'boolean', value: false, help: 'Set to `true` to prevent the widget from sending any osc message'}
+
+ }
+
+ // okay that's bad, but keys happen to be ordered anyway...
+
+ var alterDefaults = {}
+
+ for (var k in defaults) {
+ if (k === '_value') {
+ for (var l in insert) {
+ alterDefaults[l] = insert[l]
+ }
+ }
+ if (except.indexOf(k) < 0) alterDefaults[k] = defaults[k]
+ }
+
+ for (var m in push) {
+ alterDefaults[m] = push[m]
+ }
+
+ alterDefaults._props = function() {
+ var props = {}
+ for (var k in this) {
+ if (k[0] !== '_') {
+ props[k] = this[k].value
+ }
+ }
+ return props
+ }
+
+
+ return alterDefaults
+
+ }
+
+ constructor(options={}) {
+
+ super()
+
+ this.widget = options.html
+ this.props = options.props
+ this.errors = {}
+ this.parsers = {}
+ this.parent = options.root ? widgetManager : options.parent
+ this.parentNode = options.parentNode
+ this.hash = nanoid('abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
+ this.children = []
+ this.reCreateOptions = options.reCreateOptions
+
+ // strip parent ? no position
+ if (this.parent && this.parent.props && this.parent.props.type == 'strip') {
+ delete this.props.top
+ delete this.props.left
+ delete this.props[this.parent.getProp('horizontal') ? 'height' : 'width']
+ }
+
+ this.createPropsCache()
+
+ if (this.getProp('id') == 'root' && !options.root) {
+ this.cachedProps.id = '_root'
+ this.errors.id = 'There can only be one root'
+ }
+
+ this.disabledProps = []
+
+ // cache precision
+ if (this.props.precision != undefined) {
+ this.precision = Math.min(20,Math.max(this.getProp('precision', undefined, false),0))
+ }
+
+ if (options.container) {
+
+ this.container = html`
+
+ `
+ this.label = html`
`
+ this.container.appendChild(this.label)
+ this.container.appendChild(this.widget)
+ this.container._widget_instance = this
+ this.setContainerStyles()
+ } else {
+ this.container = dummyDOM
+ }
+
+ }
+
+ contains(widget) {
+
+ if (this.children.indexOf(widget) > 0) return true
+
+ var parent = widget.parent
+ while (parent && parent !== widgetManager) {
+ if (parent === this) return true
+ parent = parent.parent
+ }
+ return false
+
+ }
+
+ getAllChildren() {
+
+ var children = []
+ for (var i = 0; i < this.children.length; i++) {
+ if (!this.children[i]) continue
+ children.push(this.children[i])
+ children = children.concat(this.children[i].getAllChildren())
+ }
+ return children
+
+
+ }
+
+ created(index) {
+
+ this.trigger('widget-created', {
+ id: this.getProp('id'),
+ widget: this,
+ options: this.reCreateOptions,
+ index: index
+ })
+
+ }
+
+ changed(options) {
+
+ this.trigger('change', {
+ widget: this,
+ options: options,
+ id: this.getProp('id'),
+ linkId: this.getProp('linkId')
+ })
+
+ }
+
+ sendValue(overrides, options={}) {
+
+ if (this.selfLinkedOSCProps) {
+ this.updateProps(this.selfLinkedOSCProps, this)
+ }
+
+ if (this.getProp('bypass') && !options.force) return
+
+ var data = {
+ h:this.hash,
+ v:this.value
+ }
+
+ if (overrides) {
+ for (var k in overrides) {
+ data[k] = overrides[k]
+ }
+ }
+
+ if (options.syncOnly) {
+
+ osc.sync(data)
+
+ } else {
+
+ osc.send(data)
+
+ }
+
+ }
+
+ setValue() {}
+
+ getValue(withPrecision) {
+
+ return deepCopy(this.value, withPrecision ? this.precision : undefined)
+
+ }
+
+ getSplit() {}
+
+ createPropsCache() {
+
+ // @{props} links lists
+ this.linkedProps = {}
+ this.nestedLinkedProps = {}
+ this.linkedPropsValue = {}
+
+ // OSC{/path} receivers
+ if (this.oscReceivers) {
+ this.removeOscReceivers()
+ }
+ this.oscReceivers = {}
+
+ // Cache resolved props
+ this.cachedProps = {}
+
+ for (var k in this.props) {
+ if (k != 'widgets' && k != 'tabs') {
+ this.cachedProps[k] = this.resolveProp(k, undefined, true)
+ } else {
+ this.cachedProps[k] = this.props[k]
+ }
+ }
+
+ this.createLinkedPropsBindings()
+
+ }
+
+ createLinkedPropsBindings() {
+
+ if (!this.linkedCreatedCallback && Object.keys(this.linkedProps).length) {
+
+ this.linkedCreatedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'widget-created')
+ }
+
+ this.linkedPropChangedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'prop-changed')
+ }
+
+ widgetManager.on('widget-created', this.linkedCreatedCallback, {context: this})
+ widgetManager.on('prop-changed', this.linkedPropChangedCallback, {context: this})
+
+ } else if (this.linkedCreatedCallback && !Object.keys(this.linkedProps).length) {
+
+ widgetManager.off('widget-created', this.linkedCreatedCallback)
+ widgetManager.off('prop-changed', this.linkedPropChangedCallback)
+ delete this.linkedCreatedCallback
+ delete this.linkedPropChangedCallback
+
+ }
+
+ if (!this.linkedValueChangedCallback && Object.keys(this.linkedPropsValue).length) {
+
+ this.linkedValueChangedCallback = (e)=>{
+ this.onLinkedPropsChanged(e, 'change')
+ }
+
+ widgetManager.on('change', this.linkedValueChangedCallback, {context: this})
+
+ } else if (this.linkedPropsValueCallback && !Object.keys(this.linkedPropsValue).length) {
+
+ widgetManager.off('change', this.linkedValueChangedCallback)
+ delete this.linkedValueChangedCallback
+
+ }
+
+ var selfLinkedOSCProps = (this.linkedPropsValue['this'] || []).filter(i=>OSCProps.indexOf(i) > -1)
+ this.selfLinkedOSCProps = selfLinkedOSCProps.length ? selfLinkedOSCProps : false
+
+ }
+
+ onLinkedPropsChanged(e, type) {
+
+ var {id, widget, options} = e,
+ changedProps = type === 'prop-changed' ? e.props : type === 'change' ? ['value'] : undefined,
+ linkedProps = type === 'change' ? this.linkedPropsValue : this.linkedProps
+
+ if (widget === this.parent) {
+ if (type === 'widget-created') return
+ id = 'parent'
+ }
+
+ if (widget === this) id = 'this'
+
+ if (this.nestedLinkedProps[id]) {
+ this.updateLinkedPropsWithNesting(id)
+ }
+
+ if (linkedProps[id]) {
+ this.updateProps(linkedProps[id], widget, options, changedProps)
+ }
+
+ }
+
+ removeOscReceivers() {
+
+ osc.off(undefined, undefined, this)
+ for (var i in this.oscReceivers) {
+ oscReceiverState[i] = this.oscReceivers[i].value
+ }
+ this.oscReceivers = {}
+
+ }
+
+ updateLinkedPropsWithNesting(i) {
+
+ for (var prop of this.nestedLinkedProps[i]) {
+
+ // 1. remove all linked props found in properties bound to the nested link
+ for (var linksStores of [this.linkedPropsValue, this.linkedProps]) {
+ for (let id in linksStores) {
+ if (linksStores[id].includes(prop)) {
+ linksStores[id].splice(linksStores[id].indexOf(prop), 1)
+ if (!linksStores[id].length) delete linksStores[id]
+ }
+ }
+ }
+
+
+ // 2. resolve these props again and recreate links (3rd arg to true)
+ this.resolveProp(prop, undefined, true, this)
+
+ }
+
+
+ }
+
+ resolveProp(propName, propValue, storeLinks=true, originalWidget, originalPropName, context) {
+
+ propValue = propValue !== undefined ? propValue : deepCopy(this.props[propName])
+ originalWidget = originalWidget || this
+ originalPropName = originalPropName || propName
+
+ var variables = {},
+ mathscope = context || {},
+ varnumber = 0
+
+ if (typeof propValue == 'string') {
+
+ propValue = propValue.replace(/@\{[^{}]*(@\{[^{}]*\})*[^{}]*\}/g, (m, nested)=>{
+ // pretty regexp:
+ // @\{
+ // [^{}]*
+ // (
+ // @\{
+ // [^{}]*
+ // \}
+ // )*
+ // [^{}]*
+ // \}
+
+ if (nested) {
+ m = m.replace(nested, this.resolveProp(propName, nested, storeLinks ? 'nested' : false, this))
+ }
+
+ let id = m.substr(2, m.length - 3).split('.'),
+ k, subk
+
+ if (id.length > 1) {
+
+ k = id.pop()
+ subk = undefined
+
+ if (id.length > 1) {
+ subk = k
+ k = id.pop()
+ }
+
+ id = id.join('.')
+
+ } else {
+
+ id = id[0]
+ k = 'value'
+
+ }
+
+ // backward compat
+ if (k === '_value') k = 'value'
+
+ var widgets = id == 'parent' && this.parent ?
+ [this.parent] : id == 'this' ? [this] :
+ widgetManager.getWidgetById(id)
+
+ if (!widgets.length) {
+ var parent = this.parent
+ while (parent && parent != widgetManager) {
+ if (parent.getProp('id') == id) {
+ widgets.push(parent)
+ break
+ }
+ parent = parent.parent
+ }
+ }
+
+
+ // ignore clone wrapper in @parent stack (https://github.com/jean-emmanuel/open-stage-control/issues/379)
+ if (widgets[0] === this.parent && this.parent.getProp('type') === 'clone') widgets = [this.parent.parent]
+
+ if (storeLinks) {
+
+ if (k == 'value') {
+
+ if (!this.linkedPropsValue[id]) this.linkedPropsValue[id] = []
+ if (this.linkedPropsValue[id].indexOf(propName) == -1) this.linkedPropsValue[id].push(propName)
+
+ } else {
+
+ if (!this.linkedProps[id]) this.linkedProps[id] = []
+ if (this.linkedProps[id].indexOf(propName) == -1) this.linkedProps[id].push(propName)
+
+ }
+
+ if (storeLinks === 'nested') {
+ if (!this.nestedLinkedProps[id]) this.nestedLinkedProps[id] = []
+ if (this.nestedLinkedProps[id].indexOf(propName) == -1) this.nestedLinkedProps[id].push(propName)
+ }
+
+ }
+
+ for (var i in widgets) {
+
+ if (widgets[i] === widgetManager) continue
+
+ if (widgets[i].props[k] !== undefined || k === 'value') {
+
+ if (k !== 'value' && originalPropName === k && widgets[i] === originalWidget) {
+ return 'ERR_CIRCULAR_REF'
+ }
+
+ var r = k == 'value' ?
+ widgets[i].getValue(true) :
+ widgets[i].resolveProp(k, undefined, storeLinks, originalWidget, originalPropName)
+
+ if (subk !== undefined && r !== undefined) r = r[subk]
+
+ var varname = 'VAR_' + varnumber
+ varnumber++
+
+ variables[varname] = r
+ mathscope[varname] = r
+
+ return varname
+
+ }
+
+ }
+
+ })
+
+ propValue = propValue.replace(/OSC\{([^}]+)\}/g, (m)=>{
+ let [address, value] = m.substr(4, m.length - 5).split(',').map(x=>x.trim()),
+ resolvedAddress = address.replace(/VAR_[0-9]+/g, (m)=>{
+ return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
+ })
+
+ if (!this.oscReceivers[address]) {
+ this.oscReceivers[address] = new OscReceiver(resolvedAddress, value, this, propName)
+ if (oscReceiverState[address]) {
+ this.oscReceivers[address].value = oscReceiverState[address]
+ delete oscReceiverState[address]
+ }
+ } else {
+ this.oscReceivers[address].setAddress(resolvedAddress)
+ this.oscReceivers[address].addProp(propName)
+ }
+
+ var r = this.oscReceivers[address].value
+
+ var varname = 'VAR_' + varnumber
+ varnumber++
+
+ variables[varname] = r
+ mathscope[varname] = r
+
+ return varname
+ })
+
+ try {
+ propValue = propValue.replace(/#\{(?:[^{}]|\{[^{}]*\})*\}/g, (m)=>{
+ // one bracket nesting allowed, if we need two: #\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}
+
+ // unescape brackets (not needed anymore, just here for backward compatibility)
+ m = m.replace(/\\(\{|\})/g, '$1')
+
+ // espace multiline strings
+ m = m.replace(/`([^`]*)`/g, (m)=>{
+ return m.replace(/"/g,'\\"').replace(/\n/g,'\\n').replace(/`/g,'"')
+ })
+
+ if (!this.parsers[m]) this.parsers[m] = math.compile(m.substr(2, m.length - 3).trim())
+
+ let r = this.parsers[m].eval(mathscope)
+
+ if (r instanceof math.type.ResultSet && !r.entries.length) {
+ r = ''
+ } else if (typeof r === 'object' && r !== null && r.valueOf) {
+ r = r.valueOf()
+ if (Array.isArray(r) && r.length == 1) r = r[0]
+ }
+
+ return typeof r != 'string' ? JSON.stringify(r) : r
+ })
+ } catch (err) {}
+
+ for (let k in variables) {
+ var v = typeof variables[k] === 'string' ? variables[k] : JSON.stringify(variables[k])
+ propValue = propValue.replace(new RegExp(k, 'g'), v)
+ }
+
+ // heuristic to avoid using JSON when unnecessary
+ // if the string doesn't starts with one of these chars
+ // it's going to fail
+ // ref in source: https://github.com/douglascrockford/JSON-js
+ if (' \n+-eE{([0123456789tfn"'.indexOf(propValue[0]) !== -1) {
+ try {
+ propValue = JSON.parse(propValue)
+ } catch (err) {}
+ }
+
+ } else if (propValue != null && typeof propValue == 'object') {
+ for (let k in propValue) {
+ propValue[k] = this.resolveProp(propName, propValue[k], storeLinks, originalWidget, originalPropName, context)
+ }
+ }
+
+ return propValue
+
+
+ }
+
+ getProp(propName) {
+ return this.cachedProps[propName]
+ }
+
+
+ isDynamicProp(propName) {
+
+ return this.constructor.dynamicProps.indexOf(propName) !== -1
+
+ }
+
+ updateProps(propNames, widget, options, updatedProps = []) {
+
+ if (propNames.includes('value')) {
+ propNames.splice(propNames.indexOf('value'), 1)
+ propNames.push('value')
+ }
+
+ var reCreate = false,
+ changedProps = []
+
+ for (var propName of propNames) {
+
+ if (widget === this && updatedProps.includes(propName)) continue
+
+ let propValue = this.resolveProp(propName, undefined, false),
+ oldPropValue = this.getProp(propName)
+
+ if (!deepEqual(oldPropValue, propValue)) {
+
+ if (!this.isDynamicProp(propName)) {
+
+ reCreate = true
+
+ } else {
+
+ this.cachedProps[propName] = propValue
+ changedProps.push({propName, oldPropValue})
+
+ }
+
+
+ }
+ }
+
+ if (reCreate && (!widget || !this.contains(widget)) && widget !== this && !(widget === this && updatedProps.length === 1 && updatedProps[0] === 'value')) {
+
+ return this.reCreateWidget({reCreateOptions: options})
+
+ } else if (changedProps.length) {
+
+ for (var i in changedProps) {
+
+ this.onPropChanged(changedProps[i].propName, options, changedProps[i].oldPropValue)
+ }
+
+ widgetManager.trigger('prop-changed', {
+ id: this.getProp('id'),
+ props: changedProps,
+ widget: this,
+ options: options
+ })
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ switch(propName) {
+
+ case 'value':
+ this.setValue(this.getProp('value'), {sync: true, send: options && options.send})
+ return
+
+ case 'top':
+ case 'left':
+ this.setContainerStyles(['geometry'])
+ return
+
+ case 'height':
+ case 'width':
+ this.setContainerStyles(['geometry'])
+ resize.check(this.container)
+ return
+
+ case 'label':
+ this.setContainerStyles(['label'])
+ if (oldPropValue === false || this.getProp('label') === false) {
+ resize.check(this.container)
+ }
+ return
+
+ case 'css':
+ this.setContainerStyles(['css'])
+ this.onPropChanged('color')
+ var re = /width|height|display/
+ if (re.test(oldPropValue) || re.test(this.getProp('css'))) {
+ resize.check(this.container)
+ }
+ return
+
+ case 'color':
+ this.setContainerStyles(['color'])
+ return
+
+ case 'precision':
+ case 'address':
+ case 'preArgs':
+ case 'target':
+ case 'noSync':
+ if (propName == 'precision') this.precision = Math.min(20,Math.max(this.getProp('precision', undefined, false),0))
+ var data = {},
+ oldData = {
+ preArgs: propName == 'preArgs' ? oldPropValue : this.getProp('preArgs'),
+ address: propName == 'address' ? oldPropValue : this.getProp('address')
+ }
+ data[propName] = this.getProp(propName)
+ if (propName === 'address' && this.getSplit()) {
+ data['split'] = this.getSplit()
+ }
+ widgetManager.registerWidget(this, data, oldData)
+ return
+
+ }
+
+ }
+
+ setContainerStyles(styles = ['geometry', 'label', 'css', 'color']) {
+
+ if (styles.includes('geometry')) {
+
+ // geometry
+ for (let d of ['width', 'height', 'top', 'left']) {
+ let val = this.getProp(d),
+ geometry
+
+ if (val !== undefined) {
+ if (parseFloat(val) < 0) val = 0
+ geometry = parseFloat(val) == val ? parseFloat(val)+'rem' : val
+ }
+
+ if (geometry && geometry != 'auto') {
+ this.container.style[d] = geometry
+ if (d == 'width') this.container.style.minWidth = geometry
+ if (d == 'height') this.container.style.minHeight = geometry
+ if (d == 'top' || d == 'left') this.container.classList.add('absolute-position')
+ }
+ }
+
+ }
+
+ if (styles.includes('label')) {
+
+ // label
+ if (this.getProp('label') === false) {
+ this.container.classList.add('nolabel')
+ } else {
+ this.container.classList.remove('nolabel')
+ var label = this.getProp('label') == 'auto'?
+ this.getProp('id'):
+ iconify(this.getProp('label'))
+
+ this.label.innerHTML = label
+ }
+
+ }
+
+ if (styles.includes('css')) {
+
+ // css
+ var css = String(this.getProp('css')),
+ prefix = '#' + this.hash,
+ scopedCss = scopeCss(css, prefix),
+ unScopedCss = '',
+ extraCssClasses = []
+
+
+ // extra css "class" property
+ css = css.replace(/^[^\S\n]*class[^\S\n]*:[^\S\n]*([^;\n\s]+);?/igm, (m, c)=>{
+ if (c === 'widget' || c.includes('-container')) return
+ extraCssClasses.push(c.replace(/"'/g,''))
+ })
+
+ try {
+
+ dummyDOM.style = css
+ unScopedCss = dummyDOM.getAttribute('style') || ''
+
+ } catch(err) {
+
+ // fallback for browser that don't allow assigning "style" property
+ css
+ .replace(/\{[^}]*\}/g, '')
+ .replace(/^[^@#.]*:.*/gm, (m)=>{
+ unScopedCss += m[m.length - 1] === ';' ? m : m + ';'
+ })
+
+ }
+
+
+
+ if (scopedCss.indexOf('@keyframes') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s+([0-9]+%|to|from)', 'g'), ' $1')
+ if (scopedCss.indexOf('&') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s&', 'g'), prefix)
+
+ var style = html``,
+ oldStyle = DOM.get(this.container, '> style')[0]
+
+ if (oldStyle) {
+ this.container.replaceChild(style, oldStyle)
+ } else if (scopedCss.length || unScopedCss.length){
+ this.container.insertBefore(style, this.widget)
+ }
+
+
+ // apply extra css classes
+
+ if (this.extraCssClasses && this.extraCssClasses.length) {
+ this.container.classList.remove(...this.extraCssClasses)
+ this.extraCssClasses = []
+ }
+
+ if (extraCssClasses.length) {
+ this.container.classList.add(...extraCssClasses)
+ this.extraCssClasses = extraCssClasses
+ }
+
+ }
+
+ if (styles.includes('color')) {
+
+ // color
+ this.container.style.setProperty('--color-custom', this.getProp('color') && this.getProp('color') != 'auto' ? this.getProp('color') : '')
+
+ }
+
+
+ }
+
+ reCreateWidget(options={}){
+
+ return updateWidget(this, options)
+
+ }
+
+ onRemove(){
+
+ widgetManager.off(undefined, undefined, this)
+ this.removeOscReceivers()
+
+ }
+
+}
+
+Widget.dynamicProps = [
+ 'top',
+ 'left',
+ 'height',
+ 'width',
+ 'label',
+ 'css',
+ 'value',
+ 'color',
+ 'precision',
+ 'address',
+ 'preArgs',
+ 'target',
+ 'bypass'
+]
+
+module.exports = Widget
diff --git a/src/client/app/widgets/containers/clone.js b/src/client/app/widgets/containers/clone.js
new file mode 100644
index 00000000..d4e6e4c1
--- /dev/null
+++ b/src/client/app/widgets/containers/clone.js
@@ -0,0 +1,293 @@
+var Container = require('../common/container'),
+ widgetManager = require('../../managers/widgets'),
+ resize = require('../../events/resize'),
+ parser = require('../../parser'),
+ {deepCopy, deepEqual} = require('../../utils'),
+ {diff, diffToWidget} = require('../../editor/diff'),
+ html = require('nanohtml')
+
+var excludedCloneClasses = ['widget', 'absolute-position', 'ui-resizable', 'ui-draggable', 'not-editable']
+
+class Clone extends Container {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _clone:'clone',
+
+ widgetId: {type: 'string', value: '', help: '`id` of the widget to clone'},
+
+ _overrides:'overrides',
+
+ props: {type: 'object', value: {}, help: 'Cloned widget\'s properties to override'},
+
+ }, ['label', 'color', 'linkId', '_value', 'default', 'value', '_osc', 'precision', 'address', 'preArgs', 'target', 'bypass'])
+
+ }
+
+ constructor(options) {
+
+ options.props.label = ''
+ options.props.variables = '@{parent.variables}'
+
+ super({...options, html: html`
`})
+
+ this.cloneLock = false
+ this.cloneTarget = null
+ this.cloneClass = []
+
+ this.container.classList.add('empty')
+
+ this.bindTarget(this.getCloneTarget())
+ if (this.cloneTarget) this.createClone(true)
+
+ // global listener to catch cloneTarget's creation if no target is locked
+ widgetManager.on('widget-created', (e)=>{
+
+ if (this.cloneTarget) return
+
+ var {id, widget} = e
+
+ if (id === this.getProp('widgetId') && this.isValidCloneTarget(widget)) {
+
+ var clone = this.children[0]
+
+ this.unbindTarget()
+
+ if (!clone) {
+
+ this.updateContainer(false)
+ this.bindTarget(widget)
+ this.createClone()
+
+ } else {
+
+ this.bindTarget(widget)
+ this.updateClone()
+
+ }
+
+ }
+
+ }, {context: this})
+
+ widgetManager.on('prop-changed', (e)=>{
+
+ if (!this.cloneTarget) return
+
+ if (e.widget === this.cloneTarget || this.cloneTarget.contains(e.widget)) {
+
+ this.updateClone()
+
+ }
+
+ }, {context: this})
+
+ }
+
+ getCloneTarget() {
+
+ // attempt to acquire a cloneTarget if 'widget-created' event has not been catched
+ // (the target might have been created before the clone itself)
+
+ var widgets = widgetManager.getWidgetById(this.getProp('widgetId'))
+ .filter(el=>this.isValidCloneTarget(el))
+
+ if (widgets.length === 0) return null
+ if (widgets.length === 1) {
+ return widgets[0]
+ }
+
+ // when duplicating clones pointing to an object with a static id,
+ // each clone will recreate an object with the same id internally
+ // we try to get the original one if there is more than 2 clone pointing to the same id (avoiding cloning the clone)
+
+ function isCreatedByAClone(wi){
+ var parent = wi.parent
+ return parent && parent.getProp('type') === 'clone'
+ }
+
+ var target = widgets[0]
+ for (var w of widgets) {
+ if (!isCreatedByAClone(w)) {
+ target = w
+ break
+ }
+ }
+
+ return target
+
+ }
+
+ isValidCloneTarget(widget) {
+
+ return !(widget.contains(this) || this.contains(widget))
+
+ }
+
+ createClone(init) {
+
+ if (this.cloneLock) return
+
+ this.cloneLock = true
+
+ var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')}
+
+ parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ this.updateContainer(!init)
+
+ this.cloneLock = false
+
+ }
+
+ unbindTarget() {
+
+ if (!this.cloneTarget) return
+
+ this.cloneTarget.off(undefined, undefined, this)
+
+ this.cloneTarget = null
+
+ }
+
+ bindTarget(target) {
+
+ if (!target) return
+
+ this.cloneTarget = target
+
+ // listen for cloneTarget's deletion
+ // if it is just edited, its recreation will be catched by the global 'widget-created' event handler
+ this.cloneTarget.on('widget-removed', (e)=>{
+ if (this.cloneTarget === e.widget) {
+ this.unbindTarget()
+ }
+ }, {context: this})
+
+ // listen for cloneTarget's content updates
+ this.cloneTarget.on('widget-created', (e)=>{
+
+ var {widget} = e,
+ parent = widget.parent
+
+ while (parent !== this.cloneTarget && parent !== widgetManager) {
+ // if updated widget is in a nested clone, ignore it:
+ // it will be handled by the nested clone that targets it
+ if (parent.getProp('type') === 'clone') return
+ parent = parent.parent
+ }
+
+ this.updateClone()
+
+ }, {context: this})
+
+ }
+
+ updateClone() {
+
+ if (this.cloneLock) return
+
+ this.cloneLock = true
+
+ var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')},
+ clone = this.children[0]
+
+ var delta = diff.diff(clone.props, data) || {},
+ [widget, patch] = diffToWidget(clone, delta),
+ changedProps = Object.keys(patch)
+
+ if (changedProps.length) {
+
+ diff.patch(widget.props, patch)
+
+
+ if (changedProps.some(x => !widget.isDynamicProp(x))) {
+
+ clone.reCreateWidget({reuseChildren: false})
+ this.updateContainer(false)
+
+ } else {
+
+ widget.updateProps(changedProps, this)
+ this.updateContainer(true)
+
+ }
+
+ }
+
+
+
+ this.cloneLock = false
+
+ }
+
+ updateContainer(checkResize) {
+
+
+ if (this.cloneTarget) {
+
+ var classes = [...this.cloneTarget.container.classList].filter(i=>excludedCloneClasses.indexOf(i) === -1)
+
+ if (!deepEqual(classes, this.cloneClass)) {
+ this.container.classList.remove(...this.cloneClass)
+ this.cloneClass = classes
+ this.container.classList.add(...this.cloneClass)
+ }
+
+ this.container.classList.remove('empty')
+
+ for (var w of this.getAllChildren()) {
+ w.container.classList.add('not-editable')
+ }
+
+ if (checkResize) resize.check(this.widget)
+
+ } else if (this.cloneClass.length) {
+
+ this.container.classList.remove(...this.cloneClass)
+ this.container.classList.add('empty')
+ this.cloneClass = []
+ this.widget.innerHTML = ''
+ widgetManager.removeWidgets(this.getAllChildren())
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'widgetId':
+ this.unbindTarget()
+ this.updateContainer(false)
+ this.bindTarget(this.getCloneTarget())
+ if (this.cloneTarget) this.createClone()
+ return
+
+ }
+
+ }
+
+ onRemove(){
+
+ this.unbindTarget()
+ super.onRemove()
+
+ }
+
+}
+
+Clone.dynamicProps = Clone.prototype.constructor.dynamicProps.concat(
+ 'widgetId'
+)
+
+module.exports = Clone
diff --git a/src/client/app/widgets/containers/modal.js b/src/client/app/widgets/containers/modal.js
new file mode 100644
index 00000000..05fba710
--- /dev/null
+++ b/src/client/app/widgets/containers/modal.js
@@ -0,0 +1,184 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ {icon, iconify} = require('../../ui/utils'),
+ resize = require('../../events/resize'),
+ doubletab = require('../mixins/double_tap'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+module.exports = class Modal extends Panel {
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _modal:'modal',
+
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the modal require a double tap to open instead of a single tap'},
+ popupLabel: {type: 'string', value: '', help: 'Alternative label for the modal popup'},
+ popupWidth: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
+ popupHeight: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
+ popupLeft: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
+ popupTop: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
+
+ }, [], {
+
+ _chidlren:'children',
+
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object'},
+ value: {type: 'integer', value: '', help: [
+ 'Defines the modal\'s state:`0` for closed, `1` for opened'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ options.props.scroll = true
+
+ super(options)
+
+ this.disabledProps = []
+
+ this.popup = html`
+
+ `
+
+ this.container.appendChild(this.popup)
+
+ // convert dimensions / coordinates to rem
+ var geometry = {}
+ for (var g of ['Width', 'Height', 'Left', 'Top']) {
+ geometry[g] = parseFloat(this.getProp('popup' + g)) == this.getProp('popup' + g) ? parseFloat(this.getProp('popup' + g)) + 'rem' : this.getProp('popup' + g)
+ }
+
+ this.popup.style.setProperty('--width', geometry.Width)
+ this.popup.style.setProperty('--height', geometry.Height)
+
+ if (geometry.Left !== 'auto') {
+ this.popup.style.setProperty('--left', geometry.Left)
+ this.popup.classList.add('x-positionned')
+ }
+
+ if (geometry.Top !== 'auto') {
+ this.popup.style.setProperty('--top', geometry.Top)
+ this.popup.classList.add('y-positionned')
+ }
+
+ this.light = this.container.appendChild(html`
`)
+
+ if (this.getProp('doubleTap')) {
+ doubletab(this.light, ()=>{
+ this.setValue(1, {sync:true, send:true})
+ })
+ } else {
+ this.light.addEventListener('fast-click',(e)=>{
+ if (e.capturedByEditor === true) return
+ this.setValue(1, {sync:true, send:true})
+ })
+ }
+
+ var closer = DOM.get(this.popup, '.closer')[0]
+ this.popup.addEventListener('fast-click',(e)=>{
+ if ((e.target === this.popup || e.target === closer) && this.value == 1) {
+ e.detail.preventOriginalEvent = true
+ this.setValue(0, {sync:true, send:true})
+ }
+ })
+
+ this.escapeKeyHandler = ((e)=>{
+ if (e.keyCode==27) this.setValue(0, {sync:true, send:true})
+ }).bind(this)
+
+ this.parentScroll = [0,0]
+ this.value = 0
+ this.init = false
+
+ }
+
+ setValue(v, options={}) {
+
+ if (this.init === undefined) return
+
+ this.value = v ? 1 : 0
+
+ if (!this.init && this.value) {
+ var label = this.getProp('popupLabel') ? iconify(this.getProp('popupLabel')) : DOM.get(this.container, '> .label')[0].innerHTML
+ DOM.get(this.popup, '.popup-title .popup-label')[0].innerHTML = label
+ DOM.get(this.popup, '.popup-content')[0].appendChild(this.widget)
+ this.init = true
+ }
+
+ this.popup.classList.toggle('show', this.value)
+ this.container.classList.toggle('on', this.value)
+ this.light.classList.toggle('on', this.value)
+
+ this.bindEscKey(this.value)
+
+ if (this.value) {
+ resize.check(this.widget, true)
+ }
+
+ if (this.init) this.fixParents()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+
+ }
+
+ bindEscKey(set) {
+
+ if (set) {
+ document.addEventListener('keydown', this.escapeKeyHandler)
+ } else {
+ document.removeEventListener('keydown', this.escapeKeyHandler)
+ }
+
+ }
+
+ onRemove() {
+ this.bindEscKey(false)
+ this.setValue(0)
+ super.onRemove()
+ }
+
+ fixParents() {
+
+ var parent = this.parent,
+ scrollFixed = false
+
+ while (parent && parent.props) {
+
+ // scroll
+ if (!scrollFixed && parent.getProp('type') == 'tab') {
+ if (this.value) {
+ this.parentScroll = [parent.widget.scrollLeft, parent.widget.scrollTop]
+ }
+ parent.widget.scrollLeft = this.value ? 0 : this.parentScroll[0]
+ parent.widget.scrollTop = this.value ? 0 : this.parentScroll[1]
+ parent.widget.style.overflow = this.value ? 'hidden' : ''
+ scrollFixed = true
+ }
+
+ // stacking
+ parent.container.style.zIndex = this.value ? 'initial' : ''
+ parent.container.style.contain = this.value ? 'style size' : ''
+
+ parent = parent.parent
+ }
+
+ this.container.style.contain = this.value ? 'style size' : ''
+
+
+ }
+
+}
diff --git a/src/client/app/widgets/containers/panel.js b/src/client/app/widgets/containers/panel.js
new file mode 100644
index 00000000..e1633c2b
--- /dev/null
+++ b/src/client/app/widgets/containers/panel.js
@@ -0,0 +1,209 @@
+var Container = require('../common/container'),
+ widgetManager = require('../../managers/widgets'),
+ parser = require('../../parser'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Panel extends Container {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _panel:'panel',
+
+ scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ border: {type: 'boolean', value: true, help: 'By default, widgets in panels/strip have their border disabled, except for panels and strips. Set to `false` to apply this rule to the panel too'},
+
+ }, [], {
+
+ _children:'children',
+
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously.'},
+ tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously'},
+
+ value: {type: 'integer', value: '', help: [
+ 'Defines currently opened tab in the widget',
+ 'A tab can be opened only by setting its parent\'s value'
+ ]},
+
+ })
+
+
+ }
+
+ constructor(options) {
+
+
+ super({...options, html: html`
`})
+
+ if (this.getProp('scroll') === false) this.widget.classList.add('noscroll')
+ if (this.getProp('border') === false) this.container.classList.add('noborder')
+ if (this.getProp('tabs') && this.getProp('tabs').length) this.widget.classList.add('has-tabs')
+
+ this.value = -1
+ this.tabs = []
+
+ if (this.getProp('tabs') && this.getProp('tabs').length) {
+
+ this.widget.appendChild(html``)
+ this.navigation = DOM.get(this.widget, '.tablist')[0]
+
+ this.wrapper = this.widget.appendChild(html`
`)
+
+ this.children = options.children || new Array(this.getProp('tabs').length)
+ for (let i = 0; i < this.children.length; i++) {
+ if (this.children[i]) {
+ this.wrapper.appendChild(this.children[i].container)
+ this.children[i].parent = this
+ this.children[i].parentNode = this.wrapper
+ } else {
+ parser.parse({
+ data: this.getProp('tabs')[i],
+ parentNode: this.wrapper,
+ parent: this,
+ tab: true,
+ index: i
+ })
+ }
+ }
+
+ if (options.children) this.alignChildrenProps()
+
+ this.createNavigation()
+
+ this.navigation.addEventListener('fast-click', (e)=>{
+ if (!e.target.hasAttribute('data-widget')) return
+ var index = DOM.index(e.target)
+ this.setValue(index, {sync: true, send:this.value != index})
+ })
+
+ this.on('tab-created', (e)=>{
+ this.createNavigation()
+ e.stopPropagation = true
+ })
+
+ this.setValue(this.getProp('value') || 0)
+
+ } else if (this.getProp('widgets') && this.getProp('widgets').length) {
+
+ this.children = options.children || new Array(this.getProp('widgets').length)
+ for (let i = 0; i < this.children.length; i++) {
+ if (this.children[i]) {
+ this.widget.appendChild(this.children[i].container)
+ this.children[i].parent = this
+ this.children[i].parentNode = this.widget
+ } else {
+ parser.parse({
+ data: this.getProp('widgets')[i],
+ parentNode: this.widget,
+ parent: this,
+ index: i
+ })
+ }
+ }
+
+ if (options.children) this.alignChildrenProps()
+
+
+ }
+
+ if (this.getProp('tabs') && !this.getProp('tabs').length) {
+ this.disabledProps.push(
+ 'precision', 'address', 'preArgs', 'target', 'bypass',
+ 'value', 'default'
+ )
+ }
+ if (this.getProp('widgets') && !this.getProp('widgets').length) {
+ this.disabledProps.push(
+ 'scroll'
+ )
+ }
+
+
+
+ }
+
+ createNavigation() {
+
+ this.navigation.innerHTML = ''
+ this.tabs = []
+
+ DOM.each(this.wrapper, '> .widget', (tab)=>{
+
+ let widget = widgetManager.getWidgetByElement(tab),
+ style = widget.getProp('color') == 'auto' ? '' : `--color-custom:${widget.getProp('color')}`
+
+ this.tabs.push(widget)
+ this.navigation.appendChild(html`
+
+ ${raw(DOM.get(tab, '> .label')[0].innerHTML)}
+
+ `)
+
+ })
+
+
+ this.setValue(this.value)
+
+ }
+
+ setValue(v, options={}) {
+ if (this.tabs.length && typeof v == 'number' && v >= 0 && v < this.tabs.length) {
+
+ for (let i in this.tabs) {
+ if (i != v) this.tabs[i].hide()
+ }
+
+ this.value = v
+
+ this.tabs[v].show()
+ DOM.each(this.navigation, 'li', (el)=>{el.classList.remove('on')})[v].classList.add('on')
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+ }
+
+ scroll(s) {
+
+ if (!s) {
+ return [this.widget.scrollLeft, this.widget.scrollTop]
+ } else {
+ this.widget.scrollLeft = s[0]
+ this.widget.scrollTop = s[1]
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of this.children) {
+ if (w) w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+
+ onRemove() {
+ this.off('resize')
+ super.onRemove()
+ }
+
+}
+
+Panel.dynamicProps = Panel.prototype.constructor.dynamicProps.concat(
+ 'variables'
+)
+
+module.exports = Panel
diff --git a/src/client/app/widgets/containers/root.js b/src/client/app/widgets/containers/root.js
new file mode 100644
index 00000000..3985525c
--- /dev/null
+++ b/src/client/app/widgets/containers/root.js
@@ -0,0 +1,95 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ {icon} = require('../../ui/utils'),
+ {enableTraversingGestures, disableTraversingGestures} = require('../../events/drag'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Root extends Panel {
+
+ static defaults() {
+
+ return Widget.defaults({}, ['label', '_geometry', 'left', 'top', 'width', 'height'], {
+
+ _children:'children',
+
+ traversing: {type: 'boolean', value: false, help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` or `auto` to limit affected widgets by the type of the first touched widget'},
+ variables: {type: '*', value: {}, help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ tabs: {type: 'array', value: [{}], help: 'Each element of the array must be a tab object'},
+ id: {type: 'string', value: 'root', help: 'Widgets sharing the same id will act as clones and update each other\'s value(s) without sending extra osc messages' },
+
+ value: {type: 'integer', value: '', help: [
+ 'Defines currently opened tab in the widget',
+ 'A tab can be opened only by setting its parent\'s value'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ options.root = true
+ options.props.id = 'root'
+ options.props.scroll = true
+ options.props.label = false
+
+ super(options)
+
+ this.widget.classList.add('root')
+
+ this.disabledProps.push('id')
+
+ DOM.each(this.widget, '> .navigation', (el)=>{
+ el.classList.add('main')
+ })
+
+ if (this.getProp('traversing')) this.setTraversing()
+
+ }
+
+ createNavigation() {
+
+ super.createNavigation()
+
+ this.navigation.appendChild(html`
+
+ ${raw(icon('bars'))}
+
+ `)
+
+ }
+
+ setTraversing(update) {
+
+ var traversing = this.getProp('traversing')
+
+ disableTraversingGestures(this.widget)
+
+ if (traversing) {
+ enableTraversingGestures(this.widget, {smart: typeof traversing === 'string' && traversing.match(/smart|auto/)})
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'traversing':
+ this.setTraversing()
+ return
+
+ }
+
+ }
+
+}
+
+Root.dynamicProps = Root.prototype.constructor.dynamicProps.concat(
+ 'traversing'
+)
+
+module.exports = Root
diff --git a/src/client/app/widgets/containers/strip.js b/src/client/app/widgets/containers/strip.js
new file mode 100644
index 00000000..710e2775
--- /dev/null
+++ b/src/client/app/widgets/containers/strip.js
@@ -0,0 +1,60 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget')
+
+module.exports = class Strip extends Panel {
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _strip: 'strip',
+
+ scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display widgets horizontally'},
+ stretch: {type: 'boolean', value: false, help: 'Set to `true` to stretch widgets evenly'},
+ border: {type: 'boolean', value: true, help: 'By default, widgets in panels/strip have their border disabled, except for panels and strips. Set to `false` to apply this rule to the panel too'},
+ spacing: {type: 'integer|percentage', value: 0, help: 'Adds space between widgets. Percents are always relative to the strips width'}
+
+ }, [], {
+
+ _children:'children',
+
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ widgets: {type: 'array', value: [], help: [
+ 'Each element of the array must be a widget object',
+ '- By default, children widgets that don\'t have an explicit `width`/`height` set will be shrinked to respect the sizes specified by others',
+ '- Adding `flex:1;` to a children\'s `css` will give it the ability the fill the remaining space',
+ '- Multiple children can have a `flex:x;` css property (`x` will ponderate their expansion)'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ var defaults = Panel.defaults()._props()
+ for (var k in defaults) {
+ if (!options.props.hasOwnProperty(k))
+ options.props[k] = defaults[k]
+ }
+
+ super(options)
+
+ this.disabledProps = []
+
+ if (this.getProp('spacing')) {
+ var spacing = this.getProp('spacing')
+ if (!isNaN(spacing)) spacing += 'rem'
+ this.widget.style.setProperty('--spacing', spacing)
+ }
+
+ this.container.classList.add(this.getProp('horizontal') ? 'horizontal' : 'vertical')
+ if (this.getProp('stretch')) this.container.classList.add('stretch')
+
+ }
+
+ setValue(){}
+ getValue(){}
+
+}
diff --git a/src/client/app/widgets/containers/tab.js b/src/client/app/widgets/containers/tab.js
new file mode 100644
index 00000000..b983d9b8
--- /dev/null
+++ b/src/client/app/widgets/containers/tab.js
@@ -0,0 +1,69 @@
+var Panel = require('./panel'),
+ Widget = require('../common/widget'),
+ resize = require('../../events/resize')
+
+module.exports = class Tab extends Panel {
+
+ static defaults() {
+
+ return Widget.defaults({}, ['_geometry', 'left', 'top', 'width', 'height'], {
+
+ _children:'children',
+
+ variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A tab cannot contain widgets and tabs simultaneously'},
+ tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A tab cannot contain widgets and tabs simultaneously'},
+
+ value: {type: 'integer', value: '', help: [
+ 'Defines currently opened tab in the widget',
+ 'A tab can be opened only by setting its parent\'s value'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ options.props.scroll = true
+
+ super(options)
+
+ this.container.classList.add('show')
+ this.widget.classList.add('tab')
+
+ this.detached = false
+
+ }
+
+ hide() {
+ if (this.detached) return
+ this.container.removeChild(this.widget)
+ this.container.classList.remove('show')
+ this.detached = true
+
+ }
+ show() {
+ if (!this.detached) return
+ this.container.appendChild(this.widget)
+ this.container.classList.add('show')
+ this.detached = false
+ resize.check(this.widget, true)
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'label':
+ case 'color':
+ if (this.parent.createNavigation) this.parent.createNavigation()
+ return
+
+ }
+
+ }
+
+}
diff --git a/src/browser/js/app/widgets/index.js b/src/client/app/widgets/index.js
similarity index 76%
rename from src/browser/js/app/widgets/index.js
rename to src/client/app/widgets/index.js
index 79c5d6be..c6b0925c 100644
--- a/src/browser/js/app/widgets/index.js
+++ b/src/client/app/widgets/index.js
@@ -7,6 +7,7 @@ module.exports.widgets = {
fader: require('./sliders/fader'),
knob: require('./sliders/knob'),
encoder: require('./sliders/encoder'),
+ range: require('./sliders/range'),
// buttons
toggle: require('./buttons/toggle'),
@@ -20,10 +21,12 @@ module.exports.widgets = {
multixy: require('./pads/multixy'),
// matrices
+ matrix: require('./matrices/matrix'),
+ keyboard: require('./matrices/keyboard'),
+ // deprecated / hidden
multitoggle: require('./matrices/multitoggle'),
multipush: require('./matrices/multipush'),
multifader: require('./matrices/multifader'),
- keyboard: require('./matrices/keyboard'),
// plots
led: require('./plots/led'),
@@ -33,6 +36,9 @@ module.exports.widgets = {
visualizer: require('./plots/visualizer'),
meter: require('./plots/meter'),
text: require('./plots/text'),
+ image: require('./plots/image'),
+ svg: require('./plots/svg'),
+ frame: require('./plots/frame'),
// containers
strip: require('./containers/strip'),
@@ -46,20 +52,23 @@ module.exports.widgets = {
// inputs
input: require('./inputs/input'),
+ keys: require('./inputs/keys'),
+ script: require('./inputs/script'),
+ gyroscope: require('./inputs/gyroscope'),
// maths
+ // deprecated / hidden
formula: require('./maths/formula')
}
module.exports.categories = {
- 'Sliders':['fader','knob', 'encoder'],
+ 'Sliders':['fader','knob', 'encoder', 'range'],
'Buttons':['toggle','push','switch', 'dropdown'],
'Pads':['xy','rgb','multixy'],
- 'Matrices':['multifader','multitoggle','multipush', 'keyboard'],
- 'Plots':['plot','eq','visualizer','led', 'rgbled','meter','text'],
+ 'Matrices':['matrix', 'keyboard'],
+ 'Plots':['plot','eq','visualizer','led', 'rgbled','meter','text', 'image', 'svg', 'frame'],
'Containers':['panel','strip','modal', 'clone'],
'Switchers':['switcher','crossfader'],
- 'Inputs':['input'],
- 'Maths':['formula']
+ 'Inputs':['input', 'keys', 'script', 'gyroscope']
}
diff --git a/src/client/app/widgets/inputs/gyroscope.js b/src/client/app/widgets/inputs/gyroscope.js
new file mode 100644
index 00000000..f1563d0b
--- /dev/null
+++ b/src/client/app/widgets/inputs/gyroscope.js
@@ -0,0 +1,119 @@
+var Widget = require('../common/widget'),
+ GyroNorm = require('gyronorm/dist/gyronorm.complete.min.js'),
+ {icon} = require('../../ui/utils'),
+ {clip} = require('../utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+
+class Gyroscope extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _gyroscope: 'gyroscope',
+
+ frequency: {type: 'number', value: 30, help: 'Value update frequency (updates per seconds)'},
+ normalize: {type: 'boolean', value: true, help: 'Normalize gravity related values'},
+ compass: {type: 'boolean', value: false, help: 'Set to `true` to return the orientation values with respect to the actual north direction of the world instead of the head direction of the device'},
+ screenAdjusted: {type: 'boolean', value: false, help: 'Set to `true` to return screen adjusted values'}
+
+ }, [], {
+
+ value: {type: 'object', value: '', help: [
+ 'The gyroscope\'s value is an object containing multiple values, which can be used by other widgets via the property maths syntax',
+ '- `value.do.alpha`: deviceorientation event alpha',
+ '- `value.do.beta`: deviceorientation event beta',
+ '- `value.do.gamma`: deviceorientation event gamma',
+ '- `value.do.absolute`: deviceorientation event absolute',
+ '- `value.dm.x`: devicemotion event acceleration x',
+ '- `value.dm.y`: devicemotion event acceleration y',
+ '- `value.dm.z`: devicemotion event acceleration z',
+ '- `value.dm.gx`: devicemotion event accelerationIncludingGravity x',
+ '- `value.dm.gy`: devicemotion event accelerationIncludingGravity y',
+ '- `value.dm.gz`: devicemotion event accelerationIncludingGravity z',
+ '- `value.dm.alpha`: devicemotion event rotationRate alpha',
+ '- `value.dm.beta`: devicemotion event rotationRate beta',
+ '- `value.dm.gamma`: devicemotion event rotationRate gamma'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ ${raw(icon('compass'))}
+
+ `})
+
+ this.sensor = new GyroNorm()
+ this.sensor.init({
+
+ frequency: 1000 / clip(this.getProp('frequency'), [0.01, 60]),
+ gravityNormalized: this.getProp('normalize'),
+ orientationBase: this.getProp('compass') ? GyroNorm.WORLD : GyroNorm.GAME,
+ decimalCount: this.getProp('precision'),
+ screenAdjusted: this.getProp('screenAdjusted'),
+ logger: null
+
+ }).then(()=>{
+
+ this.sensor.start((data)=>{
+
+ this.setValue(data, {sync: true, send: true})
+
+ // data.do.alpha ( deviceorientation event alpha value )
+ // data.do.beta ( deviceorientation event beta value )
+ // data.do.gamma ( deviceorientation event gamma value )
+ // data.do.absolute ( deviceorientation event absolute value )
+
+ // data.dm.x ( devicemotion event acceleration x value )
+ // data.dm.y ( devicemotion event acceleration y value )
+ // data.dm.z ( devicemotion event acceleration z value )
+
+ // data.dm.gx ( devicemotion event accelerationIncludingGravity x value )
+ // data.dm.gy ( devicemotion event accelerationIncludingGravity y value )
+ // data.dm.gz ( devicemotion event accelerationIncludingGravity z value )
+
+ // data.dm.alpha ( devicemotion event rotationRate alpha value )
+ // data.dm.beta ( devicemotion event rotationRate beta value )
+ // data.dm.gamma ( devicemotion event rotationRate gamma value )
+
+
+ })
+
+ }).catch((e)=>{
+
+ console.log(e)
+
+ })
+
+ }
+
+
+
+ setValue(v, options={} ) {
+
+ this.value = v
+
+ // if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ onRemove() {
+
+ this.sensor.end()
+
+ super.onRemove()
+
+ }
+
+
+}
+
+module.exports = Gyroscope
diff --git a/src/client/app/widgets/inputs/input.js b/src/client/app/widgets/inputs/input.js
new file mode 100644
index 00000000..5bf6f40a
--- /dev/null
+++ b/src/client/app/widgets/inputs/input.js
@@ -0,0 +1,152 @@
+var Canvas = require('../common/canvas'),
+ {deepCopy} = require('../../utils'),
+ html = require('nanohtml')
+
+module.exports = class Input extends Canvas {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _input:'input',
+
+ vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
+ align: {type: 'string', value: '', help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
+ unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
+ editable: {type: 'boolean', value: true, help: 'Set to `false` to make the input non-editable'}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.value = ''
+ this.stringValue = ''
+ this.focused = false
+
+ if (this.getProp('vertical')) this.widget.classList.add('vertical')
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+
+
+ if (this.getProp('editable')) {
+ this.canvas.setAttribute('tabindex', 0)
+ this.canvas.addEventListener('focus', this.focus.bind(this))
+ this.input = html` `
+ this.input.addEventListener('blur', (e)=>{
+ this.blur(false)
+ })
+ this.input.addEventListener('keydown', (e)=>{
+ if (e.keyCode==13) this.blur()
+ if (e.keyCode==27) this.blur(false)
+ })
+ } else {
+ this.widget.classList.add('not-editable')
+ }
+
+ }
+
+ focus() {
+
+ if (this.focused) return
+ this.focused = true
+
+ this.canvas.setAttribute('tabindex','-1')
+ this.input.value = this.stringValue
+ this.widget.insertBefore(this.input, this.canvas)
+ this.input.focus()
+
+ }
+
+ blur(change=true) {
+
+ if (!this.focused) return
+ this.focused = false
+
+ if (change) this.inputChange()
+
+ this.canvas.setAttribute('tabindex','0')
+ this.widget.removeChild(this.input)
+
+ }
+
+ inputChange() {
+
+ this.setValue(this.input.value, {sync:true, send:true})
+
+ }
+
+ resizeHandle(event){
+
+ super.resizeHandle(event)
+
+ if (this.getProp('vertical')){
+
+ var ratio = CANVAS_SCALING * this.scaling
+
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.rotate(-Math.PI/2)
+ this.ctx.translate(-this.height * ratio, 0)
+
+
+ if (ratio != 1) this.ctx.scale(ratio, ratio)
+ }
+
+
+ }
+
+ setValue(v, options={} ) {
+
+ try {
+ this.value = JSON.parse(v)
+ } catch (err) {
+ this.value = v
+ }
+
+ this.stringValue = this.getStringValue()
+ this.batchDraw()
+
+ if (options.send && !options.fromSync) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ draw() {
+
+ var v = this.stringValue,
+ width = this.getProp('vertical') ? this.height : this.width,
+ height = !this.getProp('vertical') ? this.height : this.width
+
+ if (this.getProp('unit') && v.length) v += ' ' + this.getProp('unit')
+
+ this.clear()
+
+ this.ctx.fillStyle = this.colors.text
+
+ if (this.textAlign == 'center') {
+ this.ctx.fillText(v, Math.round(width/2), Math.round(height/2))
+ } else if (this.textAlign == 'right') {
+ this.ctx.fillText(v, width, Math.round(height/2))
+ } else {
+ this.ctx.fillText(v, 0, Math.round(height/2))
+ }
+
+ this.clearRect = [0, 0, width, height]
+
+ }
+
+ getStringValue() {
+ if (this.value === undefined) return ''
+ return typeof this.value != 'string' ?
+ JSON.stringify(deepCopy(this.value, this.precision)).replace(/,/g, ', ') :
+ this.value
+ }
+
+}
diff --git a/src/client/app/widgets/inputs/keys.js b/src/client/app/widgets/inputs/keys.js
new file mode 100644
index 00000000..772a3749
--- /dev/null
+++ b/src/client/app/widgets/inputs/keys.js
@@ -0,0 +1,142 @@
+var Widget = require('../common/widget'),
+ {icon} = require('../../ui/utils'),
+ keyboardJS = require('keyboardjs'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+class Keys extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _keys:'keys',
+
+ binding: {type: 'string|array', value: '', help: 'Key combo `string` or `array` of strings (see KeyboardJS documentation)'},
+ keydown: {type: 'string', value: '', help: [
+ 'This property is evaluated each time the key combo is pressed. Formulas are given extras variables in this context:',
+ '- `key`: pressed key name (usefull for handling multiple keys with a single keys widget)',
+ '- `ctrl`: control key state',
+ '- `alt`: alt key state',
+ '- `shift`: shift key state',
+ '- `super`: command/windows key state'
+ ]},
+ keyup: {type: 'string', value: '', help: 'Same as `keydown`, but evaluated when releasing the key combo'},
+ repeat: {type: 'boolean', value: true, help: 'Set to `false` to prevent keydown repeats when holding the key combo pressed'},
+
+ })
+
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ ${raw(icon('keyboard'))}
+
+ `})
+
+ if (this.getProp('binding')) {
+
+ this.widget.appendChild(html`${this.getProp('binding')} `)
+
+ this.keyDownHandler = this.keyDown.bind(this)
+ this.keyUpHandler = this.keyUp.bind(this)
+
+ keyboardJS.bind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
+
+ }
+
+ }
+
+ onRemove() {
+
+ super.onRemove()
+
+ if (this.getProp('binding')) {
+
+ keyboardJS.unbind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
+
+ }
+
+ }
+
+ keyDown(e) {
+
+ if (e.target.classList.contains('no-keybinding')) return
+
+ if (!this.getProp('repeat') && e) e.preventRepeat()
+
+ if (this.getProp('keydown') !== '') {
+
+ var context = {
+ key: e.key,
+ ctrl: e.ctrlKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ meta: e.metaKey
+ }
+
+ this.setValue(this.resolveProp('keydown', undefined, false, false, false, context), {sync: true, send: true})
+
+ }
+
+
+ this.showKeydown()
+
+ }
+
+
+ keyUp(e) {
+
+ if (e.target.classList.contains('no-keybinding')) return
+
+ if (this.getProp('keyup') !== '') {
+
+ var context = {
+ key: e.key,
+ ctrl: e.ctrlKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ meta: e.metaKey
+ }
+
+ this.setValue(this.resolveProp('keyup', undefined, false, false, false, context), {sync: true, send: true})
+
+ }
+
+ this.showKeyup()
+
+ }
+
+ showKeydown(){
+
+ this.widget.style.setProperty('--opacity', 1)
+
+ }
+
+ showKeyup(){
+
+ this.widget.style.setProperty('--opacity', 0.75)
+
+ }
+
+ setValue(v, options = {}) {
+
+ this.value = v
+
+ // if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+}
+
+Keys.dynamicProps = Keys.prototype.constructor.dynamicProps.concat(
+ 'keydown',
+ 'keyup',
+ 'repeat'
+)
+
+module.exports = Keys
diff --git a/src/client/app/widgets/inputs/script.js b/src/client/app/widgets/inputs/script.js
new file mode 100644
index 00000000..5676e496
--- /dev/null
+++ b/src/client/app/widgets/inputs/script.js
@@ -0,0 +1,95 @@
+var Widget = require('../common/widget'),
+ widgetManager = require('../../managers/widgets'),
+ {icon} = require('../../ui/utils'),
+ html = require('nanohtml'),
+ raw = require('nanohtml/raw')
+
+
+class Script extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _script:'script',
+
+ condition: {type: 'string', value: 1, help: [
+ 'When the widget receives a value, if this property return a falsy value, the script property won\'t be evaluated. If it\'s non-falsy, it will be evaluated normally. Formulas are given one extra variable in this context:',
+ '- `value`: the value received by the widget'
+ ]},
+ script: {type: 'string', value: '', help: [
+ 'This property is evaluated each time the widget receives a value if condition is non-falsy. Formulas are given extras variables in this context:',
+ '- `value`: the value received by the widget',
+ '- `send(target, address, arg1, arg2, ...)`: function for sending osc messages (ignores the script\'s targets and the server\'s defaults unless `target` is `false`; ignores the script\'s `preArgs`)',
+ '- `set(id, value)`: function for setting a widget\'s value'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ ${raw(icon('code'))}
+
+ `})
+
+ }
+
+
+ static scriptSet(id, value, options) {
+
+ var widgets = widgetManager.getWidgetById(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ return widgets[i].setValue(value, options)
+
+ }
+
+ }
+
+ scriptSend(target, address, ...args) {
+
+ var overrides = {
+ address,
+ v: args,
+ preArgs: []
+ }
+
+ if (target) overrides.target = Array.isArray(target) ? target : [target]
+
+ this.sendValue(overrides)
+
+ }
+
+
+ setValue(v, options={} ) {
+
+ var context = {
+ value: v,
+ send: options.send ? this.scriptSend.bind(this) : ()=>{},
+ set: (id, value)=>{Script.scriptSet(id, value, options)},
+ log: console.log
+ }
+
+ var condition = this.resolveProp('condition', undefined, false, false, false, {value: v})
+
+ if (condition) this.resolveProp('script', undefined, false, false, false, context)
+
+ // if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+
+}
+
+Script.dynamicProps = Script.prototype.constructor.dynamicProps.concat(
+ 'condition',
+ 'script'
+)
+
+module.exports = Script
diff --git a/src/client/app/widgets/maths/formula.js b/src/client/app/widgets/maths/formula.js
new file mode 100644
index 00000000..a3a9c4ca
--- /dev/null
+++ b/src/client/app/widgets/maths/formula.js
@@ -0,0 +1,197 @@
+var Widget = require('../common/widget'),
+ widgetManager = require('../../managers/widgets'),
+ {math} = require('../utils'),
+ Input = require('../inputs/input'),
+ html = require('nanohtml')
+
+
+module.exports = class Formula extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _formula: 'formula',
+
+ formula: {type: 'string', value: '', help: ''},
+ condition: {type: 'string', value: '', help: ''},
+ unit: {type: 'string', value: '', help: ''},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+ `})
+
+
+ this.formulaString = String(this.getProp('formula'))
+ this.conditionString = String(this.getProp('condition'))
+
+ this.input = new Input({
+ props:{
+ ...Input.defaults()._props(),
+ editable:false,
+ precision:this.getProp('precision'),
+ unit: this.getProp('unit')
+ },
+ parent:this, parentNode:this.widget
+ })
+
+ this.widget.appendChild(this.input.widget)
+
+ this.linkedWidgets = []
+
+ if (this.formulaString.length) {
+
+ if (this.formulaString.match(/\$\{([^}]*)\}/g) != null) this.linkedWidgets = this.linkedWidgets.concat(this.formulaString.match(/\$\{([^}]*)\}/g).map((a)=>{return a.substr(2, a.length - 3)}))
+
+ }
+
+ if (this.conditionString.length) {
+
+ if (this.conditionString.match(/\$\{([^}]*)\}/g) != null) this.linkedWidgets = this.linkedWidgets.concat(this.conditionString.match(/\$\{([^}]*)\}/g).map((a)=>{return a.substr(2, a.length - 3)}))
+
+ }
+
+
+ try {
+
+ this.condition = math.compile(this.conditionString.replace(/\$\{([^}]*)\}/g, '_$1'))
+ delete this.errors.condition
+
+ } catch(err) {
+
+ this.errors.condition = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
+
+ }
+
+ try {
+
+ this.formula = math.compile(this.formulaString.replace(/\$\{([^}]*)\}/g, '_$1'))
+ delete this.errors.formula
+
+ } catch(err) {
+
+ this.errors.formula = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
+
+ }
+
+ this.conditionState = true
+
+
+ widgetManager.on('change', this.syncHandle.bind(this), {context: this})
+
+ if (this.formulaString.length) this.updateValue({options:{}})
+
+ }
+
+ syncHandle(e) {
+
+ if (this.linkedWidgets.indexOf(e.id)==-1 || !widgetManager.getWidgetById(e.id).length) return
+ this.updateValue(e)
+
+ }
+
+ updateValue(e){
+
+ var variables = {}
+
+ for (let id of this.linkedWidgets) {
+ if (id !== undefined) {
+ variables['_'+id] = 0
+ let widgets = widgetManager.getWidgetById(id)
+ for (let w of widgets) {
+ if (w.getValue) {
+ variables['_'+id] = w.getValue()
+ break
+ }
+ }
+
+ }
+ }
+
+ if (this.conditionString.length) {
+
+ try {
+
+ var s = this.condition.eval(variables).valueOf()
+
+ if (Array.isArray(s) && s.length == 1) s = s[0]
+
+ this.conditionState = s.data !== undefined ? s.data : s
+
+ delete this.errors.condition
+
+ } catch(err) {
+
+ this.errors.condition = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
+ this.conditionState = false
+ }
+
+ }
+
+ try {
+
+ var v = this.formula.eval(variables).valueOf()
+
+ if (Array.isArray(v) && v.length == 1) v = v[0]
+
+ this.value = v.data ? v.data : v
+
+ this.showValue()
+
+ if (e.options.sync && this.conditionState) this.changed(e.options)
+ if (e.options.send && this.conditionState) this.sendValue()
+
+ delete this.errors.formula
+
+ } catch(err) {
+
+ this.errors.formula = 'Error parsing formula "' + this.formulaString + '" (' + err + ')'
+ this.value = undefined
+
+ }
+
+ }
+
+ showValue() {
+
+ this.input.setValue(this.value)
+
+ if (this.getProp('condition').length && !this.conditionState) {
+ this.input.stringValue = '* ' + this.input.stringValue
+ this.input.batchDraw()
+ }
+
+ }
+
+ getSplit() {
+
+ return typeof this.getProp('split') == 'object' && this.getProp('split').length ? this.getProp('split') : false
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ if (this.input) this.input.onPropChanged('color')
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.input.onRemove()
+ super.onRemove()
+ }
+}
diff --git a/src/client/app/widgets/matrices/_matrix_base.js b/src/client/app/widgets/matrices/_matrix_base.js
new file mode 100644
index 00000000..7cad09ec
--- /dev/null
+++ b/src/client/app/widgets/matrices/_matrix_base.js
@@ -0,0 +1,43 @@
+var Container = require('../common/container'),
+ {enableTraversingGestures} = require('../../events/drag'),
+ html = require('nanohtml')
+
+
+module.exports = class _matrix_base extends Container {
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ this.value = []
+
+ this.on('change',(e)=>{
+
+ if (e.widget === this) return
+
+ this.value[e.widget._index] = e.widget.getValue()
+ this.changed(e.options)
+
+ })
+
+ if (this.getProp('traversing')) enableTraversingGestures(this.widget)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of this.children) {
+ if (w) w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/matrices/keyboard.js b/src/client/app/widgets/matrices/keyboard.js
new file mode 100644
index 00000000..2cff75c3
--- /dev/null
+++ b/src/client/app/widgets/matrices/keyboard.js
@@ -0,0 +1,113 @@
+var _matrix_base = require('./_matrix_base'),
+ parser = require('../../parser')
+
+
+module.exports = class Keyboard extends _matrix_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _matrix: 'matrix',
+
+ keys: {type: 'number', value: 25, help: 'Defines the number keys'},
+ start: {type: 'number', value: 48, help: [
+ 'MIDI note number to start with (default is C4)',
+ 'Standard keyboards settings are: `[25, 48]`, `[49, 36]`, `[61, 36]`, `[88, 21]`'
+ ]},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+
+ }, ['_value', 'default', 'value'], {
+
+ split: {type: 'boolean|string', value: false, help: [
+ '`true`: the widget\'s index will be appended to the matrice\'s osc address',
+ '`false`: it will be prepended to the widget\'s preArgs',
+ '`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
+ ]},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-white:color;` (white keys color)',
+ '- `--color-black:color;` (black keys color)'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ var start = parseInt(this.getProp('start')),
+ keys = parseInt(this.getProp('keys'))
+
+ var strData = JSON.stringify(options.props),
+ pattern = 'wbwbwwbwbwbw',
+ whiteKeys = 0, whiteKeys2 = 0, i
+
+ for (i = start; i < keys + start && i < 109; i++) {
+ if (pattern[i % 12] == 'w') whiteKeys++
+ }
+
+ for (i = start; i < keys + start && i < 109; i++) {
+
+ var data = JSON.parse(strData)
+
+ data.top = data.left = data.height = data.width = 'auto'
+ data.type = 'push'
+ data.id = this.getProp('id') + '/' + i
+ data.label = false
+ data.css = ''
+
+ data.target = '@{parent.target}'
+ data.precision = '@{parent.precision}'
+
+ if (!this.getProp('split')) {
+ data.address = '@{parent.address}'
+ data.preArgs = `#{
+ a = @{parent.preArgs};
+ b = typeof(a) == 'string' and a == '' ? [] : typeof(a) == 'Array' ? a : [a];
+ concat(b, [${i}])
+ }`
+ } else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
+ data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
+ data.preArgs = '@{parent.preArgs}'
+ } else if (this.getProp('split')) {
+ data.address = '@{parent.address}/' + i
+ data.preArgs = '@{parent.preArgs}'
+ }
+
+ var key = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ key._index = i - start
+ key.container.classList.add('not-editable')
+
+ if (pattern[i % 12] == 'w') {
+ key.container.classList.add('white')
+ key.container.style.width = `${100/whiteKeys}%`
+ whiteKeys2++
+ } else {
+ key.container.classList.add('black')
+ key.container.style.width = `${60 / whiteKeys}%`
+ key.container.style.left = `${100 / whiteKeys * (whiteKeys2 - 3/10)}%`
+ }
+
+ this.value[i - start] = this.getProp('off')
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/matrices/matrix.js b/src/client/app/widgets/matrices/matrix.js
new file mode 100644
index 00000000..ab1a15f3
--- /dev/null
+++ b/src/client/app/widgets/matrices/matrix.js
@@ -0,0 +1,112 @@
+var _matrix_base = require('./_matrix_base'),
+ parser = require('../../parser')
+
+class Matrix extends _matrix_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _matrix: 'matrix',
+
+ widgetType: {type: 'string', value: 'toggle', help: 'Defines the type of the widgets in the matrix'},
+ matrix: {type: 'array', value: [2,2], help: 'Defines the number of columns and and rows in the matrix'},
+ start: {type: 'integer', value: 0, help: 'First widget\'s index'},
+ spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+ border: {type: 'boolean', value: true, help: 'Set to `false` to disables the widgets\' borders'},
+ props: {type: 'object', value: {}, help: [
+ 'Defines a set of property to override the widgets\' defaults.',
+ 'Formulas in this field are resolved with an extra variable representing each widget\'s index: `$`'
+ ]}
+
+ }, [], {})
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
+ this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
+ this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
+
+ if (this.getProp('borders') === false) this.widget.classList.add('noborders')
+
+ var start = parseInt(this.getProp('start'))
+
+ if (parser.widgets[this.getProp('widgetType')]) {
+
+ for (var i = start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + start; i++) {
+
+ var props = this.resolveProp('props', undefined, false, false, false, {'$':i})
+ var data = {
+ type: this.getProp('widgetType'),
+ id: this.getProp('id') + '/' + i,
+ label: i,
+ top: 'auto',
+ left: 'auto',
+ height: 'auto',
+ width: 'auto'
+ }
+ if (typeof props === 'object' && props !== null) {
+ Object.assign(data, props)
+ }
+
+ var widget = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ widget._index = i - start
+ widget.container.classList.add('not-editable')
+
+ this.value[i - start] = widget.getValue()
+
+ }
+
+ } else {
+
+ this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'props':
+
+ for (let i = this.children.length - 1; i >= 0; i--) {
+
+ let data = this.resolveProp('props', undefined, false, false, false, {'$':i})
+
+ if (typeof data === 'object' && data !== null) {
+ Object.assign(this.children[i].props, data)
+ }
+ this.children[i].updateProps(Object.keys(data), this)
+ // this.children[i] might have been recreated
+ this.children[i].container.classList.add('not-editable')
+
+ }
+
+ return
+
+ }
+
+ }
+
+}
+
+
+Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
+ 'props'
+)
+
+module.exports = Matrix
diff --git a/src/client/app/widgets/matrices/multifader.js b/src/client/app/widgets/matrices/multifader.js
new file mode 100644
index 00000000..908d99a3
--- /dev/null
+++ b/src/client/app/widgets/matrices/multifader.js
@@ -0,0 +1,111 @@
+var _matrix_base = require('./_matrix_base'),
+ ipc = require('../../ipc'),
+ parser = require('../../parser')
+
+module.exports = class Multifader extends _matrix_base {
+
+ static defaults() {
+
+
+ return super.defaults({
+
+ _matrix:'matrix',
+
+ strips: {type: 'integer', value: 2, help: [
+ 'Number of faders in the row, each fader will inherit its parent\'s properties and the following ones (where i is the fader\'s index in the row)',
+ '- `id`: same as the widget\'s with /i appended to it',
+ '- `label`: i',
+ '- `address`: see split',
+ ]},
+ start: {type: 'integer', value: 0, help: 'First widget\'s index'},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+
+ _fader: 'fader',
+
+ range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
+ logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
+ origin: {type: 'number', value: 'auto', help: 'See fader\'s `origin`'},
+ unit: {type: 'string', value: '', help: 'See fader\'s `unit`'},
+ alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
+ horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
+ pips: {type: 'boolean', value: false, help: 'See fader\'s `pips`'},
+ dashed: {type: 'boolean', value: false, help: 'See fader\'s `dashed`'},
+ snap: {type: 'boolean', value: true, help: 'See fader\'s `snap`'},
+ meter: {type: 'boolean', value: false, help: 'See fader\'s `meter`'},
+ input: {type: 'boolean', value: true, help: 'See fader\'s `input`'},
+ compact: {type: 'boolean', value: false, help: 'See fader\'s `compact`'},
+
+ }, [], {
+
+ split: {type: 'boolean|string', value: false, help: [
+ '- `true`: the widget\'s index will be appended to the matrice\'s osc address',
+ '- `false`: it will be prepended to the widget\'s preArgs',
+ '- `string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ ipc.send('errorLog', `[Warning]\n"${this.getProp('type')}" is deprecated and will be removed in the future, please use "matrix" instead.`)
+
+ this.strips = parseInt(this.getProp('strips'))
+
+ if (this.getProp('horizontal')) {
+ this.widget.classList.add('horizontal')
+ }
+
+ if (this.getProp('compact')) {
+ this.widget.classList.add('compact')
+ }
+
+ var strData = JSON.stringify(options.props)
+ var start = parseInt(this.getProp('start'))
+
+ for (var i = start; i < this.strips + start; i++) {
+
+ var data = JSON.parse(strData)
+
+ data.top = data.left = data.height = data.width = 'auto'
+ data.type = 'fader'
+ data.id = this.getProp('id') + '/' + i
+ data.label = i
+ data.css = ''
+
+ data.target = '@{parent.target}'
+ data.precision = '@{parent.precision}'
+
+ if (!this.getProp('split')) {
+ data.address = '@{parent.address}'
+ data.preArgs = `#{
+ a = @{parent.preArgs};
+ b = typeof(a) == 'string' and a == '' ? [] : typeof(a) == 'Array' ? a : [a];
+ concat(b, [${i}])
+ }`
+ } else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
+ data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
+ data.preArgs = '@{parent.preArgs}'
+ } else if (this.getProp('split')) {
+ data.address = '@{parent.address}/' + i
+ data.preArgs = '@{parent.preArgs}'
+ }
+
+ var fader = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+ fader._index = i - start
+ fader.container.classList.add('not-editable')
+
+ this.value[i-start] = this.getProp('range').min
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/matrices/multipush.js b/src/client/app/widgets/matrices/multipush.js
new file mode 100644
index 00000000..714a7e65
--- /dev/null
+++ b/src/client/app/widgets/matrices/multipush.js
@@ -0,0 +1,103 @@
+var _matrix_base = require('./_matrix_base'),
+ ipc = require('../../ipc'),
+ parser = require('../../parser')
+
+module.exports = class Multipush extends _matrix_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _matrix: 'matrix',
+
+ matrix: {type: 'array', value: [2,2], help: [
+ 'Defines the number of columns and and rows in the matrix. Each cell will contain a push button that will inherit its parent\'s properties and the following ones (where i is the push\'s index)',
+ '- `id`: same as the widget\'s with /i appended to it',
+ '- `label`: i',
+ '- `address`: see split'
+ ]},
+ start: {type: 'integer', value: 0, help: 'First widget\'s index'},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+ spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
+
+ _push: 'push',
+
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ norelease: {type: 'boolean', value: false, help: 'Set to `true` to prevent sending any osc message when releasing the button'},
+
+ }, ['_value', 'default', 'value'], {
+
+ split: {type: 'boolean|string', value: false, help: [
+ '`true`: the widget\'s index will be appended to the matrice\'s osc address',
+ '`false`: it will be prepended to the widget\'s preArgs',
+ '`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ ipc.send('errorLog', `[Warning]\n"${this.getProp('type')}" is deprecated and will be removed in the future, please use "matrix" instead.`)
+
+ this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
+ this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
+ this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
+
+ var strData = JSON.stringify(options.props)
+ var start = parseInt(this.getProp('start'))
+
+ for (var i = start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + start; i++) {
+
+ var data = JSON.parse(strData)
+
+ data.top = data.left = data.height = data.width = 'auto'
+ data.type = 'push'
+ data.id = this.getProp('id') + '/' + i
+ data.label = i
+ data.css = ''
+
+ data.target = '@{parent.target}'
+ data.precision = '@{parent.precision}'
+
+ if (!this.getProp('split')) {
+ data.address = '@{parent.address}'
+ data.preArgs = `#{
+ a = @{parent.preArgs};
+ b = typeof(a) == 'string' and a == '' ? [] : typeof(a) == 'Array' ? a : [a];
+ concat(b, [${i}])
+ }`
+ } else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
+ data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
+ data.preArgs = '@{parent.preArgs}'
+ } else if (this.getProp('split')) {
+ data.address = '@{parent.address}/' + i
+ data.preArgs = '@{parent.preArgs}'
+ }
+
+ var push = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+
+ push._index = i - start
+ push.container.classList.add('not-editable')
+
+ this.value[i - start] = this.getProp('off')
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/matrices/multitoggle.js b/src/client/app/widgets/matrices/multitoggle.js
new file mode 100644
index 00000000..a275d4fd
--- /dev/null
+++ b/src/client/app/widgets/matrices/multitoggle.js
@@ -0,0 +1,102 @@
+var _matrix_base = require('./_matrix_base'),
+ ipc = require('../../ipc'),
+ parser = require('../../parser')
+
+module.exports = class Multitoggle extends _matrix_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _matrix:'matrix',
+
+ matrix: {type: 'array', value: [2,2], help: [
+ 'Defines the number of columns and and rows in the matrix. Each cell will contain a toggle button that will inherit its parent\'s properties and the following ones (where i is the toggle\'s index)',
+ '- `id`: same as the widget\'s with /i appended to it',
+ '- `label`: i',
+ '- `address`: see split'
+ ]},
+ start: {type: 'integer', value: 0, help: 'First widget\'s index'},
+ spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
+ traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
+
+ _toggle: 'toggle',
+
+ led: {type: 'boolean', value: false, help: 'Set to `true` to display the toggle\'s state with a led'},
+ on: {type: '*', value: 1, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see preArgs)'
+ ]},
+ off: {type: '*', value: 0, help: [
+ 'Set to `null` to send send no argument in the osc message',
+ 'Can be an `object` if the type needs to be specified (see `preArgs`)'
+ ]},
+
+ }, [], {
+
+ split: {type: 'boolean|string', value: false, help: [
+ '`true`: the widget\'s index will be appended to the matrice\'s osc address',
+ '`false`: it will be prepended to the widget\'s `preArgs`',
+ '`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ ipc.send('errorLog', `[Warning]\n"${this.getProp('type')}" is deprecated and will be removed in the future, please use "matrix" instead.`)
+
+ this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
+ this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
+ this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
+
+ var strData = JSON.stringify(options.props)
+ var start = parseInt(this.getProp('start'))
+
+ for (var i = start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + start; i++) {
+
+ var data = JSON.parse(strData)
+
+ data.top = data.left = data.height = data.width = 'auto'
+ data.type = 'toggle'
+ data.id = this.getProp('id') + '/' + i
+ data.label = i
+ data.css = ''
+
+ data.target = '@{parent.target}'
+ data.precision = '@{parent.precision}'
+
+ if (!this.getProp('split')) {
+ data.address = '@{parent.address}'
+ data.preArgs = `#{
+ a = @{parent.preArgs};
+ b = typeof(a) == 'string' and a == '' ? [] : typeof(a) == 'Array' ? a : [a];
+ concat(b, [${i}])
+ }`
+ } else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
+ data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
+ data.preArgs = '@{parent.preArgs}'
+ } else if (this.getProp('split')) {
+ data.address = '@{parent.address}/' + i
+ data.preArgs = '@{parent.preArgs}'
+ }
+
+ var toggle = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this
+ })
+ toggle._index = i - start
+ toggle.container.classList.add('not-editable')
+
+ this.value[i-start] = this.getProp('off')
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/mixins/double_tap.js b/src/client/app/widgets/mixins/double_tap.js
new file mode 100644
index 00000000..7ad8ceb1
--- /dev/null
+++ b/src/client/app/widgets/mixins/double_tap.js
@@ -0,0 +1,37 @@
+module.exports = (element, callback)=>{
+
+ var lastTapTime = 0,
+ lastTapX,
+ lastTapY
+
+ element.addEventListener('fast-click', (event)=>{
+
+ if (event.capturedByEditor) return
+
+ var tapTime = Date.now(),
+ tapLength = tapTime - lastTapTime,
+ eventData = event.detail
+
+ if (
+
+ tapLength < DOUBLE_TAP_TIME &&
+ Math.abs(lastTapX - eventData.pageX) < 20 &&
+ Math.abs(lastTapY - eventData.pageY) < 20
+
+ ) {
+
+ // execute callback at next cycle to ensure draginit events are resolved first
+ setTimeout(callback, 0)
+ lastTapTime = 0
+
+ } else {
+
+ lastTapTime = tapTime
+ lastTapX = eventData.pageX
+ lastTapY = eventData.pageY
+
+ }
+
+ })
+
+}
diff --git a/src/browser/js/app/widgets/mixins/touch_state.js b/src/client/app/widgets/mixins/touch_state.js
similarity index 69%
rename from src/browser/js/app/widgets/mixins/touch_state.js
rename to src/client/app/widgets/mixins/touch_state.js
index 90b26224..ce3f857d 100644
--- a/src/browser/js/app/widgets/mixins/touch_state.js
+++ b/src/client/app/widgets/mixins/touch_state.js
@@ -1,11 +1,11 @@
-module.exports = (self, element)=>{
+module.exports = (self, options)=>{
var sendTouchState = self.getProp('touchAddress') && self.getProp('touchAddress').length
self.touched = 0
self.setValueTouchedQueue = undefined
- element.on('draginit',(e)=>{
+ self.on('draginit',(e)=>{
self.touched += 1
if (self.touched == 1 && sendTouchState)
self.sendValue({
@@ -13,9 +13,9 @@ module.exports = (self, element)=>{
v:1,
split:false
})
- })
+ }, options)
- element.on('dragend', (e, data, traversing)=>{
+ self.on('dragend', (e)=>{
if (self.touched == 1) {
self.touched = 0
@@ -34,8 +34,18 @@ module.exports = (self, element)=>{
} else if (self.touched > 1){
self.touched -= 1
- if (traversing) self.touched = 1
}
- })
+ }, options)
+
+ self.onRemove = ()=>{
+ if (sendTouchState && self.touched > 0) {
+ self.sendValue({
+ address:self.getProp('touchAddress'),
+ v:0,
+ split:false
+ })
+ }
+ self.__proto__.onRemove.call(self)
+ }
}
diff --git a/src/browser/js/app/widgets/pads/_fake_fader.js b/src/client/app/widgets/pads/_fake_fader.js
similarity index 92%
rename from src/browser/js/app/widgets/pads/_fake_fader.js
rename to src/client/app/widgets/pads/_fake_fader.js
index 58b5f8a1..4ac7cbc7 100644
--- a/src/browser/js/app/widgets/pads/_fake_fader.js
+++ b/src/client/app/widgets/pads/_fake_fader.js
@@ -9,7 +9,7 @@ module.exports = class _fake_fader extends Fader {
if (arguments.cancelDraw) this.noDraw = true
}
- sendValue() {
+ sendValue() {
// disabled
}
diff --git a/src/client/app/widgets/pads/multixy.js b/src/client/app/widgets/pads/multixy.js
new file mode 100644
index 00000000..ecdeba44
--- /dev/null
+++ b/src/client/app/widgets/pads/multixy.js
@@ -0,0 +1,281 @@
+var Pad = require('./pad'),
+ Xy = require('./xy'),
+ {clip} = require('../utils'),
+ touchstate = require('../mixins/touch_state')
+
+
+var xyDefaults = Xy.defaults()._props()
+
+
+module.exports = class MultiXy extends Pad {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _mutlixy: 'multi xy',
+
+ points: {type: 'integer|array', value: 2, help: [
+ 'Defines the number of points on the pad',
+ 'Can be an array of strings that will be used as labels for the points (ex: `[\'A\', \'B\']`)'
+ ]},
+
+
+ _xy: 'xy',
+
+ pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
+ logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'}
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+ split: {type: 'boolean|object', value: false, help: [
+ 'Set to `true` to send separate osc messages for each point\'s x and y axis. The address will be the same as the widget\'s with `/N/x` or `/N/y` appended to it, where N is the point\'s id (or the point\'s label if points is an array)',
+ 'Can be set as an `object` to specify a different address : `[\'/0/x\', \'/0/y\', \'/1/x\', \'/2/y\']`',
+ 'Note: the widget will only respond to its original osc address, not to the splitted version'
+ ]},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--background: background;`: sets the dragging area\'s background',
+ '- `--pips-color: color;`',
+ '- `--pips-opacity: number;`',
+ '- `--color-text: point-color;`',
+ 'Pads can be targetted individually with the .pad-X selector (where X is the pad\'s index)',
+ ]}
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.npoints = typeof this.getProp('points') == 'object' ? this.getProp('points').length : this.getProp('points')
+ this.labels = typeof this.getProp('points') == 'object'
+ this.pointSize = parseInt(this.getProp('pointSize'))
+
+ this.pads = []
+
+ for (let i = 0; i < this.npoints; i++) {
+ this.pads[i] = new Xy({props:{
+ ...xyDefaults,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ default:this.getProp('default').length === this.getProp('points') * 2 ? [this.getProp('default')[i*2], this.getProp('default')[i*2 + 1]] : '',
+ rangeX:this.getProp('rangeX'),
+ rangeY:this.getProp('rangeY'),
+ precision:this.getProp('precision'),
+ logScaleX:this.getProp('logScaleX'),
+ logScaleY:this.getProp('logScaleY'),
+ pointSize: this.getProp('pointSize'),
+ pips: this.getProp('pips') && i == this.npoints-1,
+ input:false
+ }, parent: this})
+ this.pads[i].sendValue = ()=>{}
+ this.pads[i].widget.classList.add('pad-' + i)
+ this.wrapper.appendChild(this.pads[i].widget)
+
+ }
+
+
+ this.value = []
+
+ this.padsCoords = []
+ this.touchMap = {}
+
+ touchstate(this, {element: this.wrapper, multitouch: true})
+
+ this.on('draginit',(e)=>{
+
+ var id
+
+ if (!this.touchMap[e.pointerId]) {
+
+ var ndiff, diff = -1
+
+ for (var i in this.pads) {
+
+ if (Object.values(this.touchMap).indexOf(i) != -1) continue
+
+ ndiff = Math.abs(e.offsetX - this.padsCoords[i][0]) + Math.abs(e.offsetY - (this.padsCoords[i][1] + this.height))
+
+ if (diff == -1 || ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+
+ }
+
+ this.touchMap[e.pointerId] = id
+
+
+ }
+
+ if (!id) return
+
+ e.stopPropagation = true
+
+ this.pads[id].trigger('draginit', e)
+
+ }, {element: this.wrapper, multitouch: true})
+
+ this.on('drag',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ this.pads[i].trigger('drag', e)
+
+ }, {element: this.wrapper[0], multitouch: true})
+
+ this.on('dragend',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ e.stopPropagation = true
+
+ this.pads[i].trigger('dragend', e)
+
+ delete this.touchMap[e.pointerId]
+
+ }, {element: this.wrapper, multitouch: true})
+
+ this.on('change',(e)=>{
+ if (e.widget == this) return
+ e.stopPropagation = true
+ this.setValue(this.getValue(), e.options)
+ })
+
+
+ var v = []
+ for (let i = 0; i < this.npoints * 2; i = i + 2) {
+ [v[i],v[i+1]] = this.pads[i/2].getValue()
+ }
+
+ this.setValue(v)
+
+ }
+
+ resizeHandle() {
+
+ super.resizeHandle(...arguments)
+ this.updateHandlesPosition()
+
+ }
+
+ updateHandlesPosition() {
+
+ for (var i=0;i{
+ var s={},
+ t
+ for (var i=0; i
+
+
+
+
+ `})
+
+ this.wrapper = DOM.get(this.widget, '.wrapper')[0]
+
+ this.pointSize = parseInt(this.getProp('pointSize'))
+ this.widget.style.setProperty('--pointSize', this.pointSize + 'rem')
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ super.cacheCanvasStyle(style)
+
+ this.colors.pips = style.getPropertyValue('--color-pips') || this.colors.custom
+ this.colors.pipsOpacity = style.getPropertyValue('--pips-opacity')
+ this.colors.pointOpacity = style.getPropertyValue('--point-opacity')
+
+ }
+
+}
+
+Pad.dynamicProps = Pad.prototype.constructor.dynamicProps.filter(n => n !== 'precision')
+
+module.exports = Pad
diff --git a/src/client/app/widgets/pads/rgb.js b/src/client/app/widgets/pads/rgb.js
new file mode 100644
index 00000000..91f9d8df
--- /dev/null
+++ b/src/client/app/widgets/pads/rgb.js
@@ -0,0 +1,266 @@
+var Pad = require('./pad'),
+ Xy = require('./xy'),
+ Fader = require('./_fake_fader'),
+ {clip, mapToScale, hsbToRgb, rgbToHsb} = require('../utils'),
+ Input = require('../inputs/input'),
+ html = require('nanohtml')
+
+var faderDefaults = Fader.defaults()._props(),
+ xyDefaults = Xy.defaults()._props()
+
+module.exports = class Rgb extends Pad {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _rgb:'rgb',
+
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ range: {type: 'object', value: {min: 0, max: 255}, help: 'Defines the widget\'s output scale.'},
+ input: {type: 'boolean', value: true, help: 'Set to `false` to hide the built-in input widget'},
+ alpha:{type: 'boolean', value: false, help: 'Set to `true` to enable alpha channel'}
+
+ }, ['color'], {
+
+ split: {type: 'boolean|object', value: false, help: [
+ 'Set to `true` to send separate osc messages for for r and g & b. The address will be the same as the widget\'s with `/r`, `/g` or `/b` appended to it',
+ 'Can be set as an `object` to specify a different address : `[\'/r\', \'/g\', \'b\']`',
+ 'Note: the widget will only respond to its original osc address, not to the splitted version'
+ ]}
+ })
+
+ }
+
+ constructor(options) {
+
+ options.props.pointSize = 10
+
+ super(options)
+
+ this.hueWrapper = this.widget.appendChild(html`
`)
+
+ this.hue = new Fader({props:{
+ ...faderDefaults,
+ id:'h',
+ compact:true,
+ pips:false,
+ horizontal:true,
+ snap:this.getProp('snap'),
+ range:{min:0,max:360},
+ input:false,
+ precision:2
+ }, cancelDraw: false, parent: this})
+ this.hue.sendValue = ()=>{}
+ this.hueWrapper.appendChild(this.hue.widget)
+ this.hue.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragHandle(true)
+ })
+
+ this.pad = new Xy({props:{
+ ...xyDefaults,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ rangeX:{min:0,max:100},
+ rangeY:{min:0,max:100},
+ precision:2,
+ pointSize: this.getProp('pointSize'),
+ pips: false,
+ input:false
+ }, parent: this})
+ this.pad.sendValue = ()=>{}
+ this.wrapper.appendChild(this.pad.widget)
+ this.pad.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragHandle()
+ })
+
+ if (this.getProp('alpha')) {
+ this.alphaWrapper = this.widget.appendChild(html`
`)
+ this.alpha = new Fader({props:{
+ ...faderDefaults,
+ id:'a',
+ compact:true,
+ pips:false,
+ horizontal:true,
+ snap:this.getProp('snap'),
+ range:{min:0,max:255},
+ default: 255,
+ input:false,
+ precision:2
+ }, cancelDraw: false, parent: this})
+ this.alpha.sendValue = ()=>{}
+ this.alphaWrapper.appendChild(this.alpha.widget)
+ this.alpha.on('change',(e)=>{
+ e.stopPropagation = true
+ this.dragAlphaHandle()
+ })
+ }
+
+ if (this.getProp('input')) {
+
+ this.input = new Input({
+ props:{...Input.defaults()._props(), precision:this.getProp('precision'), unit:this.getProp('unit')},
+ parent:this, parentNode:this.widget
+ })
+ this.widget.appendChild(this.input.widget)
+ this.input.on('change', (e)=>{
+ e.stopPropagation = true
+ this.setValue(this.input.getValue(), {sync:true, send:true})
+ this.showValue()
+ })
+
+ }
+
+
+ this.value = []
+
+ this.hsb = {h:0,s:0,b:0}
+
+ this.setValue([this.getProp('range').min, this.getProp('range').min, this.getProp('range').min])
+
+ }
+
+ dragHandle(hue) {
+ var h = this.hue.value,
+ s = this.pad.value[0],
+ b = this.pad.value[1]
+
+ if (h != this.hsb.h ||s != this.hsb.s || b != this.hsb.b) {
+
+ this.hsb.h = this.hue.value
+ this.hsb.s = this.pad.value[0]
+ this.hsb.b = this.pad.value[1]
+
+ this.update({nohue:!hue})
+
+ var rgb = hsbToRgb(this.hsb)
+ for (var k in rgb) {
+ rgb[k] = mapToScale(rgb[k], [0, 255], [this.getProp('range').min, this.getProp('range').max])
+ }
+
+ if (rgb.r != this.value[0] || rgb.g != this.value[1] || rgb.b != this.value[2]) {
+ this.setValue([rgb.r, rgb.g, rgb.b], {
+ send: true,
+ sync: true,
+ dragged: true,
+ nohue: !hue
+ })
+ }
+ }
+
+ }
+
+ dragAlphaHandle() {
+
+ var alpha = this.alpha.value
+ if (alpha !== this.value[3]) {
+ this.setValue([this.value[0], this.value[1], this.value[2], alpha], {
+ send: true,
+ sync: true,
+ dragged: true,
+ nohue: true
+ })
+ }
+
+
+ }
+
+ setValue(v, options={}) {
+
+ if (!v || v.length < 3) return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ var value = Array(this.getProp('alpha') ? 4 : 3)
+ for (var i = 0; i < value.length; i++) {
+ value[i] = clip(v[i], [this.getProp('range').min, this.getProp('range').max])
+ }
+
+ if (value.length === 4 && value[3] === undefined) value[3] = this.alpha.value
+
+ var hsb = rgbToHsb({
+ r: value[0],
+ g: value[1],
+ b: value[2]
+ })
+
+ if (!options.dragged) {
+ this.pad.setValue([hsb.s, hsb.b])
+ if (value.length === 4) this.alpha.setValue(value[3])
+ }
+
+ this.hsb = hsb
+ this.value = value
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.update({dragged:options.dragged, nohue:options.nohue || (v[0]==v[1]&&v[1]==v[2])})
+
+ }
+
+ update(options={}) {
+
+ if (!options.nohue && !options.dragged) {
+ var hue = hsbToRgb({h:this.hsb.h,s:100,b:100}),
+ hueStr = `rgb(${Math.round(hue.r)},${Math.round(hue.g)},${Math.round(hue.b)})`
+ this.canvas.setAttribute('style',`background-color:${hueStr}`)
+ this.hue.setValue(this.hsb.h, {sync: false, send:false, dragged:false})
+ }
+
+
+ this.showValue()
+
+ }
+
+ draw() {}
+
+ showValue() {
+
+ if (this.getProp('input')) this.input.setValue(this.value)
+
+ }
+
+ getSplit() {
+
+ return this.getProp('split')?
+ typeof this.getProp('split') == 'object' && this.getProp('split').length == 3 ?
+ this.getProp('split')
+ : [this.getProp('address') + '/r', this.getProp('address') + '/g', this.getProp('address') + '/b']
+ : false
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of [this.hue, this.pad]) {
+ w.onPropChanged('color')
+ }
+ if (this.input) this.input.onPropChanged('color')
+ if (this.alpha) this.alpha.onPropChanged('color')
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.hue.onRemove()
+ this.pad.onRemove()
+ if (this.input) this.input.onRemove()
+ if (this.alpha) this.alpha.onRemove()
+ super.onRemove()
+ }
+
+}
diff --git a/src/client/app/widgets/pads/xy.js b/src/client/app/widgets/pads/xy.js
new file mode 100644
index 00000000..e99e348e
--- /dev/null
+++ b/src/client/app/widgets/pads/xy.js
@@ -0,0 +1,314 @@
+var Pad = require('./pad'),
+ Fader = require('./_fake_fader'),
+ doubletab = require('../mixins/double_tap'),
+ Input = require('../inputs/input'),
+ touchstate = require('../mixins/touch_state')
+
+var faderDefaults = Fader.defaults()._props()
+
+module.exports = class Xy extends Pad {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _xy:'xy',
+
+ pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
+ snap: {type: 'boolean', value: false, help: [
+ 'By default, the points are dragged from their initial position.',
+ 'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
+ logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'},
+ input: {type: 'boolean', value: true, help: 'Set to false to hide the built-in input widget'},
+ doubleTap: {type: 'boolean|string', value: false, help: [
+ 'Set to `true` to make the fader reset to its default value when receiving a double tap.',
+ 'Can also be an osc address, which case the widget will just send an osc message: `/ `'
+ ]},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`)'},
+ split: {type: 'boolean|object', value: false, help: [
+ 'Set to `true` to send separate osc messages for each point\'s x and y axis. The address will be the same as the widget\'s with `/x` or `/y` appended to it',
+ 'Can be set as an `object` to specify a different address : [\'/osc_address_x\', \'/osc_address_y\']',
+ 'Note: the widget will only respond to its original osc address, not to the splitted version'
+ ]},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--background: background;`: sets the dragging area\'s background',
+ '- `--pips-color: color;`',
+ '- `--pips-opacity: number;`',
+ '- `--point-opacity: number;`',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.faders = {
+ x: new Fader({props:{
+ ...faderDefaults,
+ id:0,
+ compact:true,
+ pips:false,
+ horizontal:true,
+ height:'100%',
+ width:'100%',
+ default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeX'),
+ origin:'auto',
+ precision:this.getProp('precision'),
+ logScale:this.getProp('logScaleX'),
+ input:false
+ }, cancelDraw: true, parent: this}),
+ y: new Fader({props:{
+ ...faderDefaults,
+ id:1,
+ compact:true,
+ pips:false,
+ horizontal:false,
+ height:'100%',
+ width:'100%',
+ default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeY'),
+ origin:'auto',
+ precision:this.getProp('precision'),
+ logScale:this.getProp('logScaleY'),
+ input:false
+ }, cancelDraw: true, parent: this}),
+ }
+
+ this.faders.x.margin = this.faders.y.margin = this.pointSize + 1
+
+ this.value = [this.faders.x.value, this.faders.y.value]
+
+ this.wrapper.appendChild(this.faders.x.widget)
+ this.wrapper.appendChild(this.faders.y.widget)
+
+ this.faders.x.on('change',(e)=>{
+ e.stopPropagation = true
+ })
+
+ this.faders.y.on('change',(e)=>{
+ e.stopPropagation = true
+ })
+
+ touchstate(this, {element: this.wrapper})
+ this.active = false
+
+ this.on('draginit',(e)=>{
+ e.stopPropagation = true
+ this.active = true
+ this.faders.x.trigger('draginit', e)
+ this.faders.y.trigger('draginit', e)
+ this.dragHandle()
+ }, {element: this.wrapper})
+
+ this.on('drag',(e)=>{
+ this.faders.x.trigger('drag', e)
+ this.faders.y.trigger('drag', e)
+ this.dragHandle()
+ }, {element: this.wrapper})
+
+ this.on('dragend', (e)=>{
+ e.stopPropagation = true
+ this.active = false
+ this.faders.x.trigger('dragend', e)
+ this.faders.y.trigger('dragend', e)
+ if (this.getProp('spring')) {
+ this.setValue([this.faders.x.springValue,this.faders.y.springValue],{sync:true,send:true})
+ } else {
+ this.batchDraw()
+ }
+ }, {element: this.wrapper})
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubletab(this.widget, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ })
+
+ } else {
+
+ doubletab(this.wrapper, ()=>{
+ this.faders.x.setValue(this.faders.x.springValue, {sync: false, send:false, dragged:true})
+ this.faders.y.setValue(this.faders.y.springValue, {sync: false, send:false, dragged:true})
+ this.setValue([this.faders.x.springValue,this.faders.y.springValue],{sync:true, send:true})
+ })
+
+ }
+
+ }
+
+ if (this.getProp('input')) {
+
+ this.input = new Input({
+ props:{...Input.defaults()._props(), precision:this.getProp('precision'), unit:this.getProp('unit')},
+ parent:this, parentNode:this.widget
+ })
+ this.widget.appendChild(this.input.widget)
+ this.input.on('change', (e)=>{
+ e.stopPropagation = true
+ this.setValue(this.input.getValue(), {sync:true, send:true})
+ this.showValue()
+ })
+
+ }
+
+ this.setValue([0,0])
+
+ }
+
+ dragHandle(){
+
+ var x = this.faders.x.value,
+ y = this.faders.y.value
+
+
+ if (x != this.value[0] || y != this.value[1]) {
+ this.setValue([x, y],{send:true,sync:true,dragged:true})
+ } else {
+ this.batchDraw()
+ }
+
+ }
+
+
+ setValue(v, options={}) {
+
+ if (!v || !v.length || v.length!=2) return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ if (!options.dragged) {
+ this.faders.x.setValue(v[0], {sync: false, send:false, dragged:false})
+ this.faders.y.setValue(v[1], {sync: false, send:false, dragged:false})
+ }
+
+ this.value = [
+ this.faders.x.value,
+ this.faders.y.value
+ ]
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.batchDraw()
+
+ this.showValue()
+
+ }
+
+ draw() {
+
+ var pointSize = this.pointSize * PXSCALE,
+ margin = (this.pointSize + 1) * PXSCALE,
+ x = this.faders.x.percentToCoord(this.faders.x.percent),
+ y = this.faders.y.percentToCoord(this.faders.y.percent)
+
+ this.clear()
+
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.colors.custom
+
+
+ if (this.getProp('pips')) {
+ this.ctx.strokeStyle = this.colors.pips
+ this.ctx.globalAlpha = this.colors.pipsOpacity
+ this.ctx.beginPath()
+ for (var pip of this.faders.x.rangeKeys.concat(this.faders.x.valueToPercent(this.faders.x.originValue))) {
+ if (pip == 0 || pip == 100) continue
+ var xpip = Math.round(2 * this.faders.x.percentToCoord(pip)) / 2
+ if (xpip === parseInt(xpip)) xpip -= 0.5
+ this.ctx.moveTo(xpip, margin)
+ this.ctx.lineTo(xpip, this.height - margin)
+ }
+ for (pip of this.faders.y.rangeKeys.concat(this.faders.y.valueToPercent(this.faders.y.originValue))) {
+ if (pip == 0 || pip == 100) continue
+ var ypip = Math.round(2 * this.faders.y.percentToCoord(pip)) / 2
+ if (ypip === parseInt(ypip)) ypip -= 0.5
+ this.ctx.moveTo(margin, ypip)
+ this.ctx.lineTo(this.width - margin, ypip)
+ }
+ this.ctx.stroke()
+
+ } else {
+
+ this.clearRect = [x - margin - PXSCALE, y - margin - PXSCALE, (margin + PXSCALE) * 2, (margin + PXSCALE) * 2]
+
+ }
+
+
+ this.ctx.strokeStyle = this.colors.custom
+ this.ctx.globalAlpha = this.active ? 1 : 0.7
+ this.ctx.lineWidth = 2 * PXSCALE
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
+ this.ctx.stroke()
+
+
+
+ this.ctx.fillStyle = this.colors.custom
+ this.ctx.globalAlpha = this.colors.pointOpacity
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize / 1.5, Math.PI * 2, false)
+ this.ctx.fill()
+
+
+ }
+
+ showValue() {
+
+ if (this.getProp('input')) this.input.setValue(this.value)
+
+ }
+
+ getSplit() {
+
+ return this.getProp('split')?
+ typeof this.getProp('split') == 'object' && this.getProp('split').length == 2 ?
+ this.getProp('split')
+ : [this.getProp('address') + '/x', this.getProp('address') + '/y']
+ : false
+
+ }
+
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of [this.faders.x, this.faders.y]) {
+ w.onPropChanged('color')
+ }
+ if (this.input) this.input.onPropChanged('color')
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.faders.x.onRemove()
+ this.faders.y.onRemove()
+ if (this.input) this.input.onRemove()
+ super.onRemove()
+ }
+
+}
diff --git a/src/browser/js/app/widgets/plots/_biquad_response.js b/src/client/app/widgets/plots/_biquad_response.js
similarity index 92%
rename from src/browser/js/app/widgets/plots/_biquad_response.js
rename to src/client/app/widgets/plots/_biquad_response.js
index 7efdd8a7..f3345a96 100644
--- a/src/browser/js/app/widgets/plots/_biquad_response.js
+++ b/src/client/app/widgets/plots/_biquad_response.js
@@ -8,13 +8,13 @@ module.exports = function(options,linear,resolution) {
var {type, freq, q, gain} = options,
Fs = 44100,
a0,a1,a2,b1,b2,norm,
- ymin, ymax, minVal, maxVal,
+ minVal, maxVal,
len = resolution
var V = Math.pow(10, Math.abs(gain) / 20)
var K = Math.tan(Math.PI * freq / Fs)
switch (type) {
- case "lowpass":
+ case 'lowpass':
norm = 1 / (1 + K / q + K * K)
a0 = K * K * norm
a1 = 2 * a0
@@ -23,7 +23,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - K / q + K * K) * norm
break
- case "highpass":
+ case 'highpass':
norm = 1 / (1 + K / q + K * K)
a0 = 1 * norm
a1 = -2 * a0
@@ -32,7 +32,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - K / q + K * K) * norm
break
- case "bandpass":
+ case 'bandpass':
norm = 1 / (1 + K / q + K * K)
a0 = K / q * norm
a1 = 0
@@ -41,7 +41,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - K / q + K * K) * norm
break
- case "notch":
+ case 'notch':
norm = 1 / (1 + K / q + K * K)
a0 = (1 + K * K) * norm
a1 = 2 * (K * K - 1) * norm
@@ -50,7 +50,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - K / q + K * K) * norm
break
- case "peak":
+ case 'peak':
if (gain >= 0) {
norm = 1 / (1 + 1/q * K + K * K)
a0 = (1 + V/q * K + K * K) * norm
@@ -68,7 +68,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - V/q * K + K * K) * norm
}
break
- case "lowshelf":
+ case 'lowshelf':
if (gain >= 0) {
norm = 1 / (1 + Math.SQRT2 * K + K * K)
a0 = (1 + Math.sqrt(2*V) * K + V * K * K) * norm
@@ -86,7 +86,7 @@ module.exports = function(options,linear,resolution) {
b2 = (1 - Math.sqrt(2*V) * K + V * K * K) * norm
}
break
- case "highshelf":
+ case 'highshelf':
if (gain >= 0) {
norm = 1 / (1 + Math.SQRT2 * K + K * K)
a0 = (V + Math.sqrt(2*V) * K + K * K) * norm
@@ -110,9 +110,9 @@ module.exports = function(options,linear,resolution) {
for (var i = 0; i < len; i++) {
var w, phi, y
if (linear)
- w = i / (len - 1) * Math.PI; // 0 to pi, linear scale
+ w = i / (len - 1) * Math.PI // 0 to pi, linear scale
else
- w = Math.exp(Math.log(1 / 0.001) * i / (len - 1)) * 0.001 * Math.PI; // 0.001 to 1, times pi, log scale
+ w = Math.exp(Math.log(1 / 0.001) * i / (len - 1)) * 0.001 * Math.PI // 0.001 to 1, times pi, log scale
phi = Math.pow(Math.sin(w/2), 2)
diff --git a/src/client/app/widgets/plots/_plots_base.js b/src/client/app/widgets/plots/_plots_base.js
new file mode 100644
index 00000000..9871818f
--- /dev/null
+++ b/src/client/app/widgets/plots/_plots_base.js
@@ -0,0 +1,208 @@
+var {mapToScale} = require('../utils'),
+ Canvas = require('../common/canvas'),
+ html = require('nanohtml')
+
+module.exports = class _plots_base extends Canvas {
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.value = []
+ this.rangeX = this.getProp('rangeX') || {min:0,max:1}
+ this.rangeY = this.getProp('rangeY') || {min:0,max:1}
+ this.logScaleX = this.getProp('logScaleX')
+ this.logScaleY = this.getProp('logScaleY')
+ this.pips = {
+ x : {
+ min: Math.abs(this.rangeX.min)>=1000?this.rangeY.min/1000+'k':this.rangeX.min,
+ max: Math.abs(this.rangeX.max)>=1000?this.rangeY.max/1000+'k':this.rangeX.max
+ },
+ y : {
+ min: Math.abs(this.rangeY.min)>=1000?this.rangeY.min/1000+'k':this.rangeY.min,
+ max: Math.abs(this.rangeY.max)>=1000?this.rangeY.max/1000+'k':this.rangeY.max
+ }
+ }
+ this.smooth = this.getProp('smooth') === true ? 0.25 : this.getProp('smooth') === false ? 0 : parseFloat(this.getProp('smooth')) || 0
+
+ }
+
+ resizeHandle() {
+
+ this.updateData()
+ super.resizeHandle(...arguments)
+
+ }
+
+ draw() {
+
+ this.ctx.clearRect(0,0,this.width,this.height)
+
+ if (this.getProp('bars')) {
+ this.draw_bars()
+ } else {
+ var points = this.draw_line()
+ if (this.getProp('dots')) {
+ this.draw_dots(points)
+ }
+ }
+
+ if (this.getProp('pips')) this.draw_pips()
+
+ }
+
+ draw_pips() {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.colors.text
+
+ if (this.pips.x) {
+
+ this.ctx.textBaseline = 'bottom'
+ this.ctx.textAlign = 'left'
+ this.ctx.fillText(this.pips.x.min,(this.pips.y?12:2)*PXSCALE,this.height)
+ this.ctx.textAlign = 'right'
+ this.ctx.fillText(this.pips.x.max,this.width-2*PXSCALE,this.height)
+
+ }
+
+ if (this.pips.y) {
+
+ this.ctx.save()
+ this.ctx.translate(0, this.height)
+ this.ctx.rotate(-Math.PI/2)
+
+ this.ctx.textBaseline = 'top'
+ this.ctx.textAlign = 'left'
+ this.ctx.fillText(this.pips.y.min,(this.pips.x?12:2)*PXSCALE,2*PXSCALE)
+ this.ctx.textAlign = 'right'
+ this.ctx.fillText(this.pips.y.max,this.height-2*PXSCALE,2*PXSCALE)
+ this.ctx.rotate(Math.PI/2)
+ this.ctx.restore()
+
+ }
+
+ }
+
+ draw_line() {
+
+ var points = []
+
+ for (let i in this.value) {
+
+ if (this.value[i].length) {
+ points.push(mapToScale(this.value[i][0],[this.rangeX.min,this.rangeX.max],[0,this.width],0,this.logScaleX,true))
+ points.push(mapToScale(this.value[i][1],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true))
+ } else {
+ points.push(mapToScale(i,[0,this.value.length-1],[0,this.width],0,this.logScaleX,true))
+ points.push(mapToScale(this.value[i],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true))
+ }
+
+ }
+
+ if (points.length < 4) return points
+
+ this.ctx.beginPath()
+
+ this.ctx.curve(points, this.smooth, Math.round(this.width/(points.length/2 - 1)))
+
+ this.ctx.globalAlpha = 0.7
+ this.ctx.lineWidth = 2 * PXSCALE
+ this.ctx.strokeStyle = this.colors.custom
+ this.ctx.stroke()
+
+ if (this.getProp('origin') !== false) {
+
+ var origin = mapToScale(this.getProp('origin') || this.rangeY.min,[this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
+
+ this.ctx.globalAlpha = 0.1
+ this.ctx.fillStyle = this.colors.custom
+ this.ctx.lineTo(this.width,origin)
+ this.ctx.lineTo(0,origin)
+ this.ctx.closePath()
+ this.ctx.fill()
+
+ }
+
+ return points
+
+ }
+
+ draw_dots(points) {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.fillStyle = this.colors.custom
+ this.ctx.strokeStyle = this.colors.track
+ this.ctx.lineWidth = 2 * PXSCALE
+ for (var i = 0; i < points.length; i += 2) {
+ this.ctx.beginPath()
+ this.ctx.arc(points[i], points[i + 1], 3 * PXSCALE, 0, 2*Math.PI)
+ this.ctx.fill()
+ this.ctx.stroke()
+ }
+
+ }
+
+ draw_bars() {
+
+ var barWidth = Math.round(this.width / this.value.length),
+ offset = Math.round((this.width - barWidth * this.value.length) / 2)
+
+ var origin = mapToScale(this.getProp('origin') || this.rangeY.min,[this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
+
+ this.ctx.beginPath()
+
+ for (let i in this.value) {
+ var y = mapToScale(this.value[i].length ? this.value[i][1] : this.value[i],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true)
+ this.ctx.rect(offset + i * barWidth, Math.min(y, origin), barWidth - PXSCALE, Math.abs(Math.min(y - origin)))
+
+ }
+
+ this.ctx.globalAlpha = 0.4
+ this.ctx.fillStyle = this.colors.custom
+ this.ctx.fill()
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof v == 'string') {
+ try {
+ v = JSON.parseFlex(v)
+ } catch(err) {}
+ }
+
+ if (typeof v == 'object' && v !== null) {
+
+ if (Array.isArray(v)) {
+
+ this.value = v
+
+ } else {
+
+ for (var i in v) {
+ if (!isNaN(i)) this.value[i] = v[i]
+ }
+
+ }
+
+ this.batchDraw()
+
+ if (options.sync) this.changed(options)
+
+ }
+
+
+ }
+
+ updateData() {
+
+ // update the coordinates to draw
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/eq.js b/src/client/app/widgets/plots/eq.js
new file mode 100644
index 00000000..abca866f
--- /dev/null
+++ b/src/client/app/widgets/plots/eq.js
@@ -0,0 +1,91 @@
+var {clip} = require('../utils'),
+ _biquad_response = require('./_biquad_response'),
+ _plots_base = require('./_plots_base')
+
+module.exports = class Eq extends _plots_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _eq:'eq',
+
+ pips: {type: 'boolean', value: true, help: 'Set to false to hide the scale'},
+ resolution: {type: 'number', value: 128, help: 'Defines the number of points used to compute the frequency response'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ origin: {type: 'number|boolean', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
+ logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
+ smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
+
+ }, ['target', 'precision', 'bypass'], {})
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.filters && options.props.filters.length) {
+ options.props.value = options.props.filters
+ delete options.props.filters
+ }
+
+ super(options)
+
+ this.rangeX = {min:20,max:22050}
+ this.pips.x.min = '20'
+ this.pips.x.max = '22k'
+
+ this.resolution = clip(this.getProp('resolution'),[64,1024])
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof v == 'string') {
+ try {
+ v = JSON.parseFlex(v)
+ } catch(err) {}
+ }
+
+ if (Array.isArray(v)) {
+
+ var filters = v,
+ eqResponse = []
+
+ if (v.length === this.resolution) {
+
+ eqResponse = v
+
+ } else {
+
+ for (let i in filters) {
+
+ var filterResponse
+
+ if (!filters[i].type) filters[i].type = 'peak'
+
+ if (!filters[i].on) {
+ filterResponse = _biquad_response({type:'peak',freq:1,gain:0,q:1},!this.getProp('logScaleX'), this.resolution)
+ } else {
+ filterResponse = _biquad_response(filters[i],!this.getProp('logScaleX'), this.resolution)
+ }
+
+ for (var k in filterResponse) {
+ if (eqResponse[k]===undefined) {
+ eqResponse[k]=[0,0]
+ }
+
+ eqResponse[k] = [filterResponse[k][0], eqResponse[k][1]+filterResponse[k][1]]
+ }
+
+ }
+
+ }
+
+ if (eqResponse.length) super.setValue(eqResponse, options)
+
+ }
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/frame.js b/src/client/app/widgets/plots/frame.js
new file mode 100644
index 00000000..242ac719
--- /dev/null
+++ b/src/client/app/widgets/plots/frame.js
@@ -0,0 +1,72 @@
+var Widget = require('../common/widget'),
+ html = require('nanohtml'),
+ locales = require('../../locales'),
+ localUrlRe = /(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.1[6-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.2[0-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.3[0-1]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)/
+
+class Frame extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _frame: 'frame',
+
+ border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
+
+ }, ['color', 'target', 'precision', 'bypass'], {
+
+ label: {type: 'string|boolean', value: 'auto', help: [
+ 'Set to `false` to hide completely',
+ 'Insert icons using the prefix ^ followed by the icon\'s name : ^play, ^pause, etc',
+ 'If set to `false`, all pointer-events will be disabled on the frame as long as the editor is enabled to ensure it can be selected'
+ ]},
+ value: {type: 'string', value: '', help: [
+ 'External web page URL. Only local URLs are allowed (starting with `http://127.0.0.1/`, `http://10.x.x.x/`, `http://192.168.x.x/`, etc)',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+
+ this.frame = DOM.get(this.widget, 'iframe')[0]
+ this.errorText = html`${locales('iframe_unauthorized')}`
+ this.errorTextMounted = false
+
+
+ }
+
+ setValue(v, options={}) {
+
+ this.value = v
+
+ var parser = document.createElement('a')
+ parser.href = this.value
+
+ if (parser.hostname.match(localUrlRe)) {
+ this.frame.setAttribute('src', this.value)
+ this.widget.classList.remove('error')
+ if (this.errorTextMounted) {
+ this.widget.removeChild(this.errorText)
+ this.errorTextMounted = false
+ }
+ } else {
+ this.frame.setAttribute('src', '')
+ this.widget.classList.add('error')
+ this.widget.appendChild(this.errorText)
+ this.errorTextMounted = true
+ }
+
+ if (options.sync) this.changed(options)
+
+ }
+
+
+}
+
+module.exports = Frame
diff --git a/src/client/app/widgets/plots/image.js b/src/client/app/widgets/plots/image.js
new file mode 100644
index 00000000..4114c0b4
--- /dev/null
+++ b/src/client/app/widgets/plots/image.js
@@ -0,0 +1,94 @@
+var Widget = require('../common/widget'),
+ ipc = require('../../ipc'),
+ html = require('nanohtml')
+
+module.exports = class Led extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _image:'image',
+
+ size: {type: 'string', value: 'cover', help: 'CSS background-size'},
+ position: {type: 'string', value: 'center', help: 'CSS background-position'},
+ repeat: {type: 'string', value: 'no-repear', help: 'CSS background-repeat'},
+ border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
+ cache: {type: 'boolean', value: true, help: [
+ 'Set to false to disable image caching (forces file reload when updating or editing the widget).',
+ 'When true, sending `reload` to the widget reloads its image without changing its value'
+ ]}
+
+ }, ['color', 'target', 'precision', 'bypass'], {
+
+ value: {type: 'string', value: '', help: [
+ '- File `url` or `absolute path`',
+ '- Base64 encoded image : `data:image/...`'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ if (!this.getProp('border')) this.container.classList.add('noborder')
+
+ this.widget.style.setProperty('background-size', this.getProp('size'))
+ this.widget.style.setProperty('background-position', this.getProp('position'))
+ this.widget.style.setProperty('background-repeat', this.getProp('repeat'))
+
+ if (this.getProp('stream') !== '') {
+ this.bindedOnStreamUpdate = this.onStreamUpdate.bind(this)
+ ipc.on('video', this.bindedOnStreamUpdate)
+ }
+
+ }
+
+ setValue(v, options={}) {
+
+ var s = v==null ? '' : '' + v,
+ cache_query = ''
+
+ if (!s.length) {
+
+ this.value = this.getProp('value')
+
+ } else if (s != 'reload') {
+
+ if (s.length > 1) this.value = s
+
+ }
+
+ if (typeof this.value === 'string' && this.value.length) {
+
+ cache_query = this.getProp('cache') || this.value.indexOf('base64') != -1 ?
+ '' : (this.value.indexOf('?') != -1 ? '&' : '?') + Date.now()
+
+ }
+
+ this.widget.style.setProperty('background-image', `url(${this.value}${cache_query})`)
+
+ if (options.sync) this.changed(options)
+
+ }
+
+ onStreamUpdate(event) {
+
+ var [stream, data] = event
+ if (stream === this.getProp('stream')) {
+ this.setValue('data:image/jpeg;base64,' + data)
+ }
+
+ }
+
+ onRemove() {
+
+ if (this.bindedOnStreamUpdate) ipc.off('video', this.bindedOnStreamUpdate)
+ super.onRemove()
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/led.js b/src/client/app/widgets/plots/led.js
new file mode 100644
index 00000000..3b0b6540
--- /dev/null
+++ b/src/client/app/widgets/plots/led.js
@@ -0,0 +1,45 @@
+var {mapToScale} = require('../utils'),
+ Widget = require('../common/widget'),
+ html = require('nanohtml')
+
+module.exports = class Led extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _led:'led',
+
+ range: {type: 'object', value: {min:0,max:1}, help: 'Value to led intensity mapping range'},
+ logScale: {type: 'boolean', value: false, help: 'Set to `true` to use a logarithmic mapping scale)'},
+
+ }, ['target', 'precision', 'bypass'], {})
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.widgetId) {
+ options.props.value = '@{' + options.props.widgetId + '}'
+ delete options.props.widgetId
+ }
+
+ super({...options, html: html`
`})
+
+ this.setValue(this.getProp('range').min)
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof v != 'number') return
+
+ this.value = v
+ this.widget.style.setProperty('--opacity', mapToScale(v,[this.getProp('range').min,this.getProp('range').max],[0,1],false,this.getProp('logScale'),true))
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/meter.js b/src/client/app/widgets/plots/meter.js
new file mode 100644
index 00000000..c2600635
--- /dev/null
+++ b/src/client/app/widgets/plots/meter.js
@@ -0,0 +1,64 @@
+var Fader = require('../sliders/fader'),
+ Widget = require('../common/widget')
+
+module.exports = class Meter extends Fader {
+
+ static defaults() {
+
+ return Widget.defaults({
+
+ _meter:'meter',
+
+ range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
+ logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
+ origin: {type: 'number', value: 'auto', help: 'See fader\'s `origin`'},
+ unit: {type: 'string', value: 'auto', help: 'See fader\'s `unit`'},
+ alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
+ horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
+ pips: {type: 'boolean', value: false, help: 'See fader\'s `pips`'},
+ dashed: {type: 'boolean', value: false, help: 'See fader\'s `dashed`'},
+ gradient: {type: 'array|object', value: [], help: [
+ 'When set, the meter\'s gauge will be filled with a linear color gradient',
+ '- each item must be a CSS color string.',
+ '- as an `object`: each key must be a number between 0 and 1',
+ '- each item must be a CSS color string.',
+ 'Examples: `[\'blue\', \'red\']`, {\'0\': \'blue\', \'0.9\': \'blue\', \'1\': \'red\'} '
+ ]},
+
+ }, ['target', 'precision', 'bypass'], {
+
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-gauge: color;`',
+ '- `--color-knob: color;`',
+ '- `--color-pips: color;`',
+ '- `--gauge-opacity: number;`'
+ ]},
+
+ })
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.widgetId) {
+ options.props.value = '@{' + options.props.widgetId + '}'
+ delete options.props.widgetId
+ }
+ options.props.compact = true
+ options.props.input = false
+
+ super(options)
+
+ this.widget.classList.add('meter')
+
+ this.off(/drag(.*)?/)
+
+ }
+
+ sendValue() {
+ // disabled
+ }
+
+}
diff --git a/src/client/app/widgets/plots/plot.js b/src/client/app/widgets/plots/plot.js
new file mode 100644
index 00000000..55cfc59b
--- /dev/null
+++ b/src/client/app/widgets/plots/plot.js
@@ -0,0 +1,47 @@
+var _plots_base = require('./_plots_base')
+
+module.exports = class Plot extends _plots_base {
+
+ static defaults() {
+
+
+ return super.defaults({
+
+ _plot:'plot',
+
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
+ logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it.'},
+ dots: {type: 'boolean', value: true, help: ''},
+ bars: {type: 'boolean', value: false, help: 'Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing)'},
+ smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
+ pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+
+ }, ['target', 'precision', 'bypass'], {
+
+ value: {type: 'array|string', value: '', help: [
+ '- `Array` of `y` values',
+ '- `Array` of `[x, y]` `array` values',
+ '- `String` `array`',
+ '- `String` `object` to update specific coordinates only: `{0:1, 4:0}` will change the 1st and 5th points\' coordinates',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.points && options.props.points.length) {
+ options.props.value = options.props.points
+ delete options.props.points
+ }
+
+ super(options)
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/rgbled.js b/src/client/app/widgets/plots/rgbled.js
new file mode 100644
index 00000000..6bae6abe
--- /dev/null
+++ b/src/client/app/widgets/plots/rgbled.js
@@ -0,0 +1,72 @@
+var Widget = require('../common/widget'),
+ {clip} = require('../utils'),
+ html = require('nanohtml')
+
+module.exports = class Rbgled extends Widget {
+
+ static defaults() {
+
+ return super.defaults({}, ['color', 'target', 'precision', 'bypass'], {
+
+ value: {type: 'array|string', value: '', help: [
+ '- `Array`: `[r, g, b]` (`r`, `g` and `b` between `0` and `255`)',
+ '- `Array`: `[r, g, b, alpha]` (`alpha` between `0` and `255`)',
+ '- `String`: CSS color',
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.widgetId) {
+ options.props.value = '@{' + options.props.widgetId + '}'
+ delete options.props.widgetId
+ }
+
+ super({...options, html: html`
+
+
+ `})
+
+ this.setValue([0,0,0,0])
+
+ }
+
+
+ setValue(v, options={}) {
+
+ var c = ''
+
+ if (Array.isArray(v) && v.length >= 3) {
+
+ for (let i in [0,1,2]) {
+ v[i] = parseInt(clip(v[i],[0,255]))
+ }
+
+ v[3] = clip(v[3] != undefined ? v[3] : 1,[0,1])
+
+ c = `rgba(${v[0]}, ${v[1]}, ${v[2]}, ${v[3]})`
+
+ } else if (typeof v == 'string') {
+
+ c = v
+
+
+ } else {
+
+ return
+
+ }
+
+ this.value = v
+
+ this.widget.style.setProperty('--color-led', c)
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
diff --git a/src/client/app/widgets/plots/svg.js b/src/client/app/widgets/plots/svg.js
new file mode 100644
index 00000000..c9301b97
--- /dev/null
+++ b/src/client/app/widgets/plots/svg.js
@@ -0,0 +1,98 @@
+var Widget = require('../common/widget'),
+ morph = require('nanomorph'),
+ html = require('nanohtml')
+
+
+class Svg extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _svg:'svg',
+
+ svg: {type: 'string', value: '', help: [
+ 'Svg xml definition:',
+ '- will be wrapped in a `< svg />` element',
+ '- `` commands support a special percent notation (`%x` and `%y`)'
+ ]}
+
+ }, ['color', 'target', 'precision', 'bypass'], {})
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.height = undefined
+ this.width = undefined
+
+ this.on('resize', this.resizeHandleProxy.bind(this), {element: this.widget})
+
+ }
+
+ updateSvg(){
+
+ if (!this.width || !this.height) return
+
+ var svg = this.getProp('svg')
+
+ svg = svg.replace(/<\/svg>/gi, 'x')
+ svg = svg.replace(/([0-9.]+%x)/gi, m=>(parseFloat(m) * this.width / 100).toFixed(2))
+ svg = svg.replace(/([0-9.]+%y)/gi, m=>(parseFloat(m) * this.height / 100).toFixed(2))
+
+
+ var newSvg = html` `,
+ node = html`${newSvg}
`
+
+ newSvg.innerHTML = svg
+
+ morph(this.widget, node)
+
+ }
+
+ resizeHandleProxy() {
+
+ this.resizeHandle(...arguments)
+
+ }
+
+ resizeHandle(event){
+
+ var {width, height} = event
+
+ this.height = height
+ this.width = width
+
+ this.updateSvg()
+
+ }
+
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'svg':
+ this.updateSvg()
+ return
+
+ }
+
+ }
+
+
+}
+
+Svg.dynamicProps = Svg.prototype.constructor.dynamicProps.concat(
+ 'svg'
+)
+
+module.exports = Svg
diff --git a/src/client/app/widgets/plots/text.js b/src/client/app/widgets/plots/text.js
new file mode 100644
index 00000000..f332e7f4
--- /dev/null
+++ b/src/client/app/widgets/plots/text.js
@@ -0,0 +1,60 @@
+var {iconify} = require('../../ui/utils'),
+ Widget = require('../common/widget'),
+ html = require('nanohtml')
+
+module.exports = class Text extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _text: 'text',
+
+ vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
+ wrap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to wrap long lines automatically.',
+ 'This will not break overflowing words by default, word-breaking can be enabled by adding `word-break: break-all;` to the `css` property',
+ ]},
+ align: {type: 'string', value: '', help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
+
+ }, ['target', 'precision', 'bypass'], {})
+
+ }
+
+ constructor(options) {
+
+ // backward compat
+ if (options.props.widgetId) {
+ options.props.value = '@{' + options.props.widgetId + '}'
+ delete options.props.widgetId
+ }
+ super({...options, html: html`
`})
+
+ if (this.getProp('vertical')) this.widget.classList.add('vertical')
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+ if (this.getProp('wrap')) this.widget.classList.add('wrap')
+
+ this.defaultValue = this.getProp('default') || ( this.getProp('label')===false ?
+ this.getProp('id'):
+ this.getProp('label')=='auto'?
+ this.getProp('id'):
+ this.getProp('label') )
+
+ this.value = this.defaultValue
+
+ this.setValue(this.value)
+
+ }
+
+
+ setValue(v, options={}) {
+
+ this.value = v==null ? this.defaultValue : v
+ this.widget.innerHTML = iconify(String(this.value).replace(/\n/g,' '))
+
+ if (options.sync) this.changed(options)
+
+ }
+
+}
diff --git a/src/browser/js/app/widgets/plots/visualizer.js b/src/client/app/widgets/plots/visualizer.js
similarity index 52%
rename from src/browser/js/app/widgets/plots/visualizer.js
rename to src/client/app/widgets/plots/visualizer.js
index 6488f0f4..ed930494 100644
--- a/src/browser/js/app/widgets/plots/visualizer.js
+++ b/src/client/app/widgets/plots/visualizer.js
@@ -1,60 +1,43 @@
-var {mapToScale, clip} = require('../utils'),
- _plots_base = require('./_plots_base'),
- widgetManager = require('../../managers/widgets')
+var {clip} = require('../utils'),
+ _plots_base = require('./_plots_base')
module.exports = class Visualizer extends _plots_base {
static defaults() {
- return {
- type:'visualizer',
- id:'auto',
-
- _geometry:'geometry',
-
- left:'auto',
- top:'auto',
- width:'auto',
- height:'auto',
-
- _style:'style',
-
- label:'auto',
- color:'auto',
- css:'',
+ return super.defaults({
_visualizer:'visualizer',
- widgetId:'',
- duration:1,
- range: {min:0,max:1},
- origin: 'auto',
- logScale: false,
- smooth: false,
- pips:true,
- value:'',
+ duration: {type: 'number', value: 1, help: 'Defines visualization duration in seconds'},
+ range: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
+ logScale: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis'},
+ smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
+ pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
- _osc:'osc',
-
- address:'auto',
- preArgs:[],
- }
+ }, ['target', 'precision', 'bypass'], {})
}
constructor(options) {
+ // backward compat
+ if (options.props.widgetId) {
+ options.props.value = '@{' + options.props.widgetId + '}'
+ delete options.props.widgetId
+ }
+
super(options)
- this.fps = 30
+ this.fps = CANVAS_FRAMERATE
this.pips.y.min = Math.abs(this.getProp('range').min) >= 1000? this.getProp('range').min/1000+'k' : this.getProp('range').min
this.pips.y.max = Math.abs(this.getProp('range').max) >= 1000? this.getProp('range').max/1000+'k' : this.getProp('range').max
this.pips.x = false
this.rangeY = this.getProp('range') || {min:0,max:1}
this.logScaleY = this.getProp('logScale')
this.length = Math.round(clip(this.fps * this.getProp('duration'), [8, 4096]))
- this.data = new Array(this.length).fill(this.rangeY.min)
- this.value = this.getProp('range').min
+ this.value = new Array(this.length).fill(this.rangeY.min)
this.cancel = false
this.looping = false
this.clock = 0
@@ -64,18 +47,11 @@ module.exports = class Visualizer extends _plots_base {
}
- syncHandle(e) {
-
- if (this.getProp('widgetId')!=e.id || !widgetManager.getWidgetById(e.id).length || !e.widget) return
- this.setValue(e.widget.getValue())
-
- }
-
startLoop() {
- this.clock = new Date().getTime()
+ this.clock = Date.now()
if (!this.looping) {
- this.lastUpdate = new Date().getTime()
+ this.lastUpdate = Date.now()
this.looping = true
this.ticks = 0
this.loop()
@@ -84,7 +60,7 @@ module.exports = class Visualizer extends _plots_base {
loop() {
- var t = new Date().getTime()
+ var t = Date.now()
if (t -this.clock >= this.watchDuration) {
this.looping = false
@@ -95,7 +71,7 @@ module.exports = class Visualizer extends _plots_base {
if (Math.floor(this.ticks) > 0) {
this.shiftData(Math.floor(this.ticks))
this.ticks -= Math.floor(this.ticks)
- this.draw()
+ this.batchDraw()
}
this.lastUpdate = t
@@ -111,25 +87,36 @@ module.exports = class Visualizer extends _plots_base {
shiftData(n) {
for (var i=0; i `)'
+ ]},
- _osc:'osc',
+ }, [], {
- precision:2,
- address:'auto',
- touchAddress:'',
- preArgs:[],
- target:[]
- }
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+
+ })
}
constructor(options) {
- var html = `
+ super({...options, html: html`
- `
- super({...options, html: html})
+ `})
- this.wrapper = this.widget.find('.wrapper')
+ this.wrapper = DOM.get(this.widget, '.wrapper')[0]
this.ticks = Math.abs(parseInt(this.getProp('ticks')))
this.knob = new EncoderKnob({props:{
@@ -87,7 +75,7 @@ module.exports = class Encoder extends _widgets_base {
snap:true,
range:{min:0,max:this.ticks},
pips:false,
- }})
+ }, parent: this})
this.knob.noDraw = true
@@ -97,18 +85,24 @@ module.exports = class Encoder extends _widgets_base {
range:{min:0,max:this.ticks},
origin:this.ticks/2,
pips:false,
- }})
+ }, parent: this})
- this.wrapper.append(this.knob.widget.addClass('drag-knob'))
- this.wrapper.append(this.display.widget.addClass('display-knob'))
+ this.knob.widget.classList.add('drag-knob')
+ this.display.widget.classList.add('display-knob')
+
+ this.wrapper.appendChild(this.knob.widget)
+ this.wrapper.appendChild(this.display.widget)
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
this.previousValue = this.ticks/2
- this.wrapper.on('change',(e)=>{
- e.stopPropagation()
+ this.on('change',(e)=>{
+
+ if (e.widget == this) return
+
+ e.stopPropagation = true
var value = this.knob.getValue()
@@ -130,34 +124,37 @@ module.exports = class Encoder extends _widgets_base {
})
- this.wrapper.on('draginit', (e)=>{
+ this.knob.on('draginit', (e)=>{
if (this.getProp('touchAddress') && this.getProp('touchAddress').length
- && e.target == this.wrapper[0])
+ && e.target == this.wrapper)
this.sendValue({
address:this.getProp('touchAddress'),
v:1
})
})
- this.wrapper.on('dragend', (e)=>{
+ this.knob.on('dragend', (e)=>{
if (this.getProp('release') !== '' && this.value !== this.getProp('release')) {
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
this.setValue(this.getProp('release'), {sync:true, send:true, dragged:false})
}
- if (this.getProp('touchAddress') && this.getProp('touchAddress').length
- && e.target == this.wrapper[0])
+ if (
+ this.getProp('touchAddress') && this.getProp('touchAddress').length
+ && e.target == this.wrapper
+ ) {
this.sendValue({
address:this.getProp('touchAddress'),
v:0
})
+ }
})
if (this.getProp('doubleTap')) {
doubletab(this.wrapper, ()=>{
- this.knob.setValue(this.ticks/2)
- this.display.setValue(this.ticks/2)
+ this.knob.setValue(this.ticks/2)
+ this.display.setValue(this.ticks/2)
if (this.getProp('release') !== '' && this.value !== this.getProp('release')) {
this.setValue(this.getProp('release'), {sync:true, send:true, dragged:false})
}
@@ -165,11 +162,11 @@ module.exports = class Encoder extends _widgets_base {
}
- this.wrapper.on('mousewheel', (e)=>{
+ this.wrapper.addEventListener('mousewheel', (e)=>{
- if (e.originalEvent.wheelDeltaX || e.originalEvent.wheelDelta == 0) return
+ if (e.wheelDeltaX || e.wheelDelta == 0) return
- var direction = e.originalEvent.wheelDelta / Math.abs(e.originalEvent.wheelDelta)
+ var direction = e.wheelDelta / Math.abs(e.wheelDelta)
this.display.setValue(this.display.value + direction)
this.setValue(direction < 0 ? this.getProp('back') : this.getProp('forth'), {sync:true, send:true})
@@ -186,7 +183,7 @@ module.exports = class Encoder extends _widgets_base {
setValue(v,options={}) {
- if (this.getProp('snap') || (!this.getProp('snap') && !options.draginit)) {
+ if (this.getProp('snap') || (!this.getProp('snap') && !options.draginit)) {
var match = true
@@ -202,16 +199,16 @@ module.exports = class Encoder extends _widgets_base {
}
- if (options.sync && match) this.widget.trigger({type:'change',id:this.getProp('id'),widget:this, linkId:this.getProp('linkId'), options:options})
+ if (options.sync && match) this.changed(options)
if (options.send && match && !(!this.getProp('snap') && options.draginit)) this.sendValue()
- if (options.dragged || options.draginit) this.updateDisplay(options.draginit)
+ if (options.dragged || options.draginit) this.updateDisplay(options.draginit)
}
updateDisplay(init){
- if (this.getProp('snap')) {
+ if (this.getProp('snap')) {
this.display.setValue(this.knob.value)
return
}
@@ -250,4 +247,27 @@ module.exports = class Encoder extends _widgets_base {
}
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of [this.knob, this.display]) {
+ w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.knob.onRemove()
+ this.display.onRemove()
+ super.onRemove()
+ }
+
}
diff --git a/src/client/app/widgets/sliders/fader.js b/src/client/app/widgets/sliders/fader.js
new file mode 100644
index 00000000..575b8d0a
--- /dev/null
+++ b/src/client/app/widgets/sliders/fader.js
@@ -0,0 +1,355 @@
+var {clip} = require('../utils'),
+ Slider = require('./slider'),
+ parser = require('../../parser'),
+ html = require('nanohtml')
+
+module.exports = class Fader extends Slider {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _fader:'fader',
+
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display the fader horizontally'},
+ alignRight: {type: 'boolean', value: false, help: 'Set to `true` to invert the pip\'s and fader\'s position'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ input: {type: 'boolean', value: true, help: 'Set to `false` to hide the built-in input'},
+ meter: {type: 'boolean', value: false, help: [
+ 'Set to true to display a vu-meter next in the fader',
+ '- the meter\'s `id` will be the same as the widget\'s with `/meter` appended to it',
+ '- the meter\'s `id` will be the same as the widget\'s with `/meter` appended to it'
+ ]},
+ compact: {type: 'boolean', value: false, help: 'Set to `true` to display a compact alternative for the widget. Disables default mouse/touch focusing on the value display.'},
+ dashed: {type: 'boolean', value: false, help: 'Set to `true` to display a dashed gauge'},
+ snap: {type: 'boolean', value: false, help: 'By default, dragging the widget will modify it\'s value starting from its last value. Setting this to `true` will make it snap directly to the mouse/touch position'},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
+ doubleTap: {type: 'boolean', value: false, help: [
+ 'Set to `true` to make the fader reset to its `default` value when receiving a double tap.',
+ 'Can also be an osc address, in which case the widget will just send an osc message (`/ `)'
+ ]},
+ range: {type: 'object', value: {min:0,max:1}, help: [
+ 'Defines the breakpoints of the fader\'s scale:',
+ '- keys can be percentages and/or `min` / `max`',
+ '- values can be `number` or `object` if a custom label is needed',
+ 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
+ ]},
+ steps: {type: 'string|number|array', value: '', help: [
+ 'Restricts the widget\'s value:',
+ '- `auto`: use values defined in `range`',
+ '- `number`: define a number of evenly spaced steps',
+ '- `array`: use arbitrary values',
+ ]},
+ logScale: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale'},
+ unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the fader\'s gauge'},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+ meterAddress: {type: 'string', value:'', help: 'OSC address for the built-in meter'},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-gauge: color;`',
+ '- `--color-knob: color;`',
+ '- `--color-pips: color;`',
+ '- `--gauge-opacity: number;`'
+ ]}
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.widget.classList.add('fader')
+ this.margin = 22
+
+
+ if (this.getProp('horizontal')) {
+ this.widget.classList.add('horizontal')
+ this.container.classList.add('horizontal')
+ }
+
+ if (this.getProp('compact')) {
+ this.widget.classList.add('compact')
+ this.margin = 0
+ if (this.getProp('input')) {
+ this.widget.addEventListener('fast-right-click', (e)=>{
+ if (e.detail.button == 2 && !EDITING) {
+ // Mouse only
+ this.input.focus()
+ }
+ })
+ }
+ }
+
+ if (this.getProp('alignRight') && !this.getProp('horizontal')) {
+ this.widget.classList.add('align-right')
+ }
+
+ if (this.getProp('meter')) {
+ var data = {
+ type:'meter',
+ id: this.getProp('id') + '/meter',
+ label:false,
+ horizontal:this.getProp('horizontal'),
+ range:this.getProp('range'),
+ logScale:this.getProp('logScale'),
+ address:this.getProp('meterAddress') || this.getProp('address') + '/meter',
+ preArgs:this.getProp('preArgs'),
+ color:this.getProp('color'),
+ pips:false,
+ dashed:true
+ }
+ var meter = parser.parse({
+ data: data,
+ parentNode: this.wrapper,
+ parent: this
+ })
+
+ meter.container.classList.add('not-editable')
+ this.children.push(meter)
+ this.widget.classList.add('has-meter')
+ }
+
+ if (this.getProp('pips')) {
+
+ this.widget.classList.add('has-pips')
+
+
+ var pipTexts = {}
+ for (var k in this.rangeKeys) {
+ pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
+ }
+
+ var pips = html`
`
+ for (var i=0;i<=100;i++) {
+ if (pipTexts[i]==undefined) continue
+
+ var pos = this.getProp('horizontal')?'left':'bottom'
+
+ pips.appendChild(html`
+
+ ${Math.abs(pipTexts[i])>=1000?pipTexts[i]/1000+'k':pipTexts[i]}
+
+ `)
+
+ }
+
+ this.wrapper.appendChild(pips)
+
+ }
+
+
+ }
+
+ draginitHandle(e) {
+
+ super.draginitHandle(...arguments)
+
+ this.percent = clip(this.percent,[0,100])
+
+ if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
+
+ this.percent = this.getProp('horizontal')?
+ (e.offsetX - this.margin * PXSCALE) / (this.width - (this.margin * PXSCALE * 2)) * 100:
+ (this.height - e.offsetY - this.margin * PXSCALE) / (this.height - (this.margin * PXSCALE * 2)) * 100
+
+ // this.percent = clip(this.percent,[0,100])
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ dragHandle(e, data) {
+
+ super.dragHandle(...arguments)
+
+ this.percent = this.getProp('horizontal')?
+ this.percent + ( e.movementX/(this.width - this.margin * PXSCALE * 2)) * 100 / e.inertia:
+ this.percent + (-e.movementY/(this.height - this.margin * PXSCALE * 2)) * 100 / e.inertia
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ percentToCoord(percent) {
+
+ if (this.getProp('horizontal')) {
+ return clip(percent / 100,[0,1]) * (this.width - 2 * PXSCALE * this.margin) + this.margin * PXSCALE
+ } else {
+ return (this.height - this.margin * PXSCALE) - clip(percent / 100, [0,1]) * (this.height - 2 * PXSCALE * this.margin)
+ }
+
+ }
+
+ resizeHandle(event) {
+
+ var ratio = CANVAS_SCALING * this.scaling
+
+ if (this.getProp('compact') && this.getProp('horizontal')) {
+ event.height = 1 / ratio
+ }
+
+ super.resizeHandle(event)
+
+ if (this.getProp('horizontal')){
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.rotate(-Math.PI/2)
+ this.ctx.translate(-this.height * ratio, 0)
+
+ if (ratio != 1) this.ctx.scale(ratio, ratio)
+ }
+
+ if (this.getProp('gradient')) {
+
+ var colors = this.getProp('gradient')
+
+ if (
+ (Array.isArray(colors) && colors.length > 1) ||
+ (typeof colors === 'object' && Object.keys(colors).length > 1)
+ ) {
+
+ var grad = this.ctx.createLinearGradient(0, this.getProp('horizontal') ? 0 : this.height, 0, this.getProp('horizontal') ? this.width : 0)
+
+ try {
+ if (Array.isArray(colors)) {
+
+ for (var i in colors) {
+ grad.addColorStop(i / (colors.length - 1), colors[i])
+ }
+ this.colors.gradient = grad
+
+ } else {
+
+ for (var k in colors) {
+ if (!isNaN(k)) {
+ grad.addColorStop(clip(k, [0, 1]), colors[k])
+ }
+ }
+ this.colors.gradient = grad
+
+ }
+ } catch(err) {
+ this.errors.gradient = err
+ }
+
+ }
+
+ }
+
+
+ }
+
+
+ draw() {
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width
+
+ var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ d = Math.round(this.percentToCoord(percent)),
+ o = Math.round(this.percentToCoord(this.valueToPercent(this.originValue))),
+ m = Math.round(this.getProp('horizontal') ? this.height / 2 : this.width / 2)
+
+ var dashed = this.getProp('dashed')
+
+ this.clear()
+
+ if (this.getProp('compact')) {
+
+ this.ctx.globalAlpha = this.colors.gaugeOpacity || (dashed ? .3 : .2) + 0.2 * Math.abs(d-o) / (d `)'
+ ]},
+ range: {type: 'object', value: {min:0,max:1}, help: [
+ 'Defines the breakpoints of the fader\'s scale:',
+ '- keys can be percentages and/or `min` / `max`',
+ '- values can be `number` or `object` if a custom label is needed',
+ 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
+ ]},
+ steps: {type: 'string|number|array', value: '', help: [
+ 'Restricts the widget\'s value:',
+ '- `auto`: use values defined in `range`',
+ '- `number`: define a number of evenly spaced steps',
+ '- `array`: use arbitrary values',
+ ]},
+ logScale: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale'},
+ unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
+ origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the knob\'s gauge'},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-gauge: color;`',
+ '- `--color-knob: color;`',
+ '- `--color-pips: color;`'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.widget.classList.add('knob')
+
+ this.widget.classList.add('compact')
+
+ this.lastOffsetX = 0
+ this.lastOffsetY = 0
+ this.minDimension = 0
+
+ this.maxAngle = this.getProp('angle')
+
+ // calculate lost height factor
+ var a = (1 - Math.sin((Math.max(this.maxAngle,247.5) - 180) / 2 * Math.PI / 180)) / 3
+ this.lostHeightFactor = a / 4
+
+ }
+
+ draginitHandle(e) {
+
+ this.percent = clip(this.percent,[0,100])
+
+ this.lastOffsetX = e.offsetX
+ this.lastOffsetY = e.offsetY
+
+ if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
+
+ this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ dragHandle(e) {
+
+ if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) {
+
+ this.percent = -100 * (e.movementY / e.inertia) / this.height + this.percent
+
+ } else {
+
+ this.lastOffsetX = this.lastOffsetX + e.movementX / e.inertia
+ this.lastOffsetY = this.lastOffsetY + e.movementY / e.inertia
+ this.percent = this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY))
+ }
+
+ this.percent = this.percent,[0,100]
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ coordsToAngle(x,y) {
+
+ var xToCenter = x - this.width /2,
+ yToCenter = y - this.height / 2,
+ angle = Math.atan2(-yToCenter, -xToCenter) * 180 / Math.PI + 90
+
+ return angle<0?360+angle:angle
+
+ }
+
+ angleToPercent(angle) {
+
+ return clip(angle - (360 - this.maxAngle) / 2, [0, this.maxAngle]) / this.maxAngle * 100
+
+ }
+
+ percentToAngle(percent) {
+
+ percent = clip(percent, [0, 100])
+
+ return 2 * Math.PI * percent / 100 * (this.maxAngle / 360) // angle relative to maxAngle
+ + Math.PI / 2 // quarter circle offset
+ + Math.PI * (1 - this.maxAngle / 360) // centering offset depending on maxAngle
+
+ }
+
+ resizeHandle() {
+
+ super.resizeHandle(...arguments)
+
+ this.minDimension = Math.min(this.width, this.height)
+
+ this.wrapper.style.top = (this.minDimension) * this.lostHeightFactor - (this.getProp('label') === false ? 0 : this.gaugeWidth / 4) + 'px'
+
+ }
+
+ draw() {
+
+ var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ o = this.percentToAngle(this.valueToPercent(this.originValue)),
+ d = this.percentToAngle(percent),
+ min = this.percentToAngle(0),
+ max = this.percentToAngle(100),
+ dashed = this.getProp('dashed'),
+ pips = this.getProp('pips'),
+ gaugeWidth = Math.max(7 * PXSCALE, this.minDimension / 20),
+ gaugeRadius = this.minDimension / 2 - gaugeWidth / 2 - 2 * PXSCALE,
+ knobRadius = gaugeRadius - gaugeWidth,
+ rad = PXSCALE / gaugeRadius / 2
+
+
+ this.ctx.clearRect(0,0,this.width,this.height)
+
+ this.ctx.globalAlpha = 1
+
+ this.ctx.strokeStyle = this.colors.light
+ this.ctx.lineWidth = gaugeWidth
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min - 4 * rad - (pips ? 3 * rad : 0), max + 4 * rad + (pips ? 3 * rad : 0))
+ this.ctx.stroke()
+
+ this.ctx.strokeStyle = this.colors.bg
+ this.ctx.lineWidth = gaugeWidth - 2 * PXSCALE
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min - 2 * rad, max + 2 * rad)
+ this.ctx.stroke()
+
+ if (dashed) this.ctx.setLineDash([1.5 * PXSCALE, 1.5 * PXSCALE])
+
+ this.ctx.strokeStyle = this.colors.track
+ this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
+ this.ctx.stroke()
+
+ this.ctx.globalAlpha = pips ? 0.5 : 0.7
+ this.ctx.strokeStyle = this.colors.gauge
+ this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
+ this.ctx.beginPath()
+
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, o, d, o > d)
+ this.ctx.stroke()
+
+ if (dashed) this.ctx.setLineDash([])
+
+
+ if (pips) {
+
+ this.ctx.globalAlpha = 1
+ this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
+
+ for (var pip of this.rangeKeys.concat(this.valueToPercent(this.originValue))) {
+
+ let a = this.percentToAngle(pip)
+
+ this.ctx.lineWidth = gaugeWidth - 2 * PXSCALE
+ this.ctx.strokeStyle = this.colors.bg
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, a - 5 * rad, a + 5 * rad)
+ this.ctx.stroke()
+
+ this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
+ this.ctx.strokeStyle = this.colors.pips
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, a - 2 * rad, a + 2 * rad)
+ this.ctx.stroke()
+
+ }
+
+ }
+
+ // knob
+
+ this.ctx.lineWidth = PXSCALE
+
+ this.ctx.fillStyle = this.colors.raised
+ this.ctx.beginPath()
+ this.ctx.globalAlpha = 1
+ this.ctx.arc(this.width / 2, this.height / 2, knobRadius, 0, Math.PI * 2)
+ this.ctx.fill()
+ this.ctx.strokeStyle = this.colors.bg
+ this.ctx.stroke()
+
+ this.ctx.beginPath()
+ this.ctx.globalAlpha = 1
+ this.ctx.arc(this.width / 2, this.height / 2, knobRadius - PXSCALE * 1.5, 0, Math.PI * 2)
+ this.ctx.strokeStyle = this.colors.light
+ this.ctx.stroke()
+
+ var g = this.ctx.createLinearGradient(this.width / 2, this.height / 2 - knobRadius / 2,this.width / 2, this.height / 2 + knobRadius / 2)
+ g.addColorStop(0.5, 'transparent')
+ g.addColorStop(0, this.colors.light || 'transparent')
+
+ this.ctx.strokeStyle = g
+ this.ctx.stroke()
+
+ // cursor
+ this.ctx.globalAlpha = 1
+
+ let r1 = knobRadius - PXSCALE,
+ r2 = knobRadius / 4,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+
+ this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
+ this.ctx.strokeStyle = this.colors.knob
+ this.ctx.stroke()
+
+ }
+
+}
diff --git a/src/client/app/widgets/sliders/range.js b/src/client/app/widgets/sliders/range.js
new file mode 100644
index 00000000..a75b5d89
--- /dev/null
+++ b/src/client/app/widgets/sliders/range.js
@@ -0,0 +1,457 @@
+var {clip} = require('../utils'),
+ Widget = require('../common/widget'),
+ Fader = require('./fader'),
+ Input = require('../inputs/input'),
+ touchstate = require('../mixins/touch_state'),
+ html = require('nanohtml')
+
+var faderDefaults = Fader.defaults()._props()
+
+var RangeFader = class RangeFader extends Fader {
+
+ constructor(options) {
+
+ super(options)
+ this.cancelDraw = options.cancelDraw
+
+ }
+
+ sendValue() {}
+
+ draginitHandle() {
+
+ this.percent = clip(this.percent,[
+ this.valueToPercent(this.rangeValsMin),
+ this.valueToPercent(this.rangeValsMax)
+ ])
+
+ super.draginitHandle(...arguments)
+ }
+
+ draw() {
+
+ if (this.cancelDraw || !this.parent.faders) return
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width
+
+ var d = Math.round(this.percentToCoord(this.valueToPercent(this.parent.faders[this.getProp('horizontal')?0:1].value))),
+ d2 = Math.round(this.percentToCoord(this.valueToPercent(this.parent.faders[this.getProp('horizontal')?1:0].value))),
+ m = Math.round(this.getProp('horizontal') ? this.height / 2 : this.width / 2)
+
+ var dashed = this.getProp('dashed')
+
+ this.clear()
+
+ if (this.getProp('compact')) {
+
+ this.ctx.globalAlpha = this.colors.gaugeOpacity || (dashed ? .3 : .2) + 0.2 * Math.abs(d-d2) / height
+ this.ctx.strokeStyle = this.colors.gauge
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, d2)
+ this.ctx.lineTo(m, d)
+ this.ctx.lineWidth = width + 2 * PXSCALE
+ if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
+ this.ctx.stroke()
+ if (dashed) this.ctx.setLineDash([])
+
+ this.ctx.globalAlpha = 1
+ this.ctx.beginPath()
+ this.ctx.fillStyle = this.colors.knob
+ this.ctx.rect(0, Math.min(d, height - PXSCALE), width, PXSCALE)
+ this.ctx.rect(0, Math.min(d2, height - PXSCALE), width, PXSCALE)
+ this.ctx.fill()
+
+ this.clearRect = [0, 0, width, height]
+
+ } else {
+
+ this.ctx.lineWidth = 6 * PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.colors.light
+ this.ctx.moveTo(m, this.margin * PXSCALE - 2 * PXSCALE)
+ this.ctx.lineTo(m, height - this.margin * PXSCALE + 2 * PXSCALE)
+ this.ctx.stroke()
+
+ this.ctx.lineWidth = 4 * PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.colors.bg
+ this.ctx.moveTo(m, this.margin * PXSCALE - 1 * PXSCALE)
+ this.ctx.lineTo(m, height - this.margin * PXSCALE + 1 * PXSCALE)
+ this.ctx.stroke()
+
+ this.ctx.lineWidth = 2 * PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.strokeStyle = this.colors.track
+ this.ctx.moveTo(m, this.margin * PXSCALE)
+ this.ctx.lineTo(m, height - this.margin * PXSCALE)
+ this.ctx.stroke()
+
+ this.ctx.beginPath()
+ this.ctx.globalAlpha = 0.7
+ this.ctx.strokeStyle = this.colors.gauge
+ this.ctx.moveTo(m, d2)
+ this.ctx.lineTo(m, d)
+ if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
+ this.ctx.stroke()
+ if (dashed) this.ctx.setLineDash([])
+
+ this.ctx.globalAlpha = 1
+
+ // high knob bg
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 9 * PXSCALE, d - 14 * PXSCALE, 18 * PXSCALE, 16 * PXSCALE)
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.colors.bg
+ this.ctx.fill()
+
+ // low knob bg
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 9 * PXSCALE, d2 - PXSCALE, 18 * PXSCALE, 16 * PXSCALE)
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.colors.bg
+ this.ctx.fill()
+
+ // high knob
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 8 * PXSCALE, d - 13 * PXSCALE, 16 * PXSCALE, 14 * PXSCALE)
+ this.ctx.fillStyle = this.colors.raised
+ this.ctx.fill()
+ this.ctx.lineWidth = PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 7.5 * PXSCALE, d - 12.5 * PXSCALE, 15 * PXSCALE, 13.5 * PXSCALE)
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.strokeStyle = this.colors.light
+ this.ctx.stroke()
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 8 * PXSCALE, d - 13 * PXSCALE, 16 * PXSCALE, PXSCALE)
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.colors.light
+ this.ctx.fill()
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 4 * PXSCALE, d, 8 * PXSCALE, PXSCALE)
+ this.ctx.fillStyle = this.colors.knob
+ this.ctx.fill()
+
+ // low knob
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 8 * PXSCALE, d2, 16 * PXSCALE, 14 * PXSCALE)
+ this.ctx.fillStyle = this.colors.raised
+ this.ctx.fill()
+ this.ctx.lineWidth = PXSCALE
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 7.5 * PXSCALE, d2, 15 * PXSCALE, 13.5 * PXSCALE)
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.strokeStyle = this.colors.light
+ this.ctx.stroke()
+
+ this.ctx.beginPath()
+ this.ctx.rect(m - 4 * PXSCALE, d2, 8 * PXSCALE, PXSCALE)
+ this.ctx.fillStyle = this.colors.knob
+ this.ctx.fill()
+
+
+
+ this.clearRect = [width / 2 - 11 * PXSCALE, 0, 22 * PXSCALE, height]
+ }
+ }
+
+}
+
+
+class Range extends Widget {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _range:'range',
+
+ range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
+ horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
+ alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
+ input: {type: 'boolean', value: true, help: 'See fader\'s `input`'},
+ compact: {type: 'boolean', value: false, help: 'See fader\'s `compact`'},
+ pips: {type: 'boolean', value: true, help: 'See fader\'s `pips`'},
+ snap: {type: 'boolean', value: false, help: 'See fader\'s `snap`'},
+ spring: {type: 'boolean', value: false, help: 'See fader\'s `spring`'},
+ logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
+
+ }, [], {
+
+ touchAddress: {type: 'string', value: '', help: 'See fader\'s `touchAddress`'},
+ split: {type: 'boolean|object', value: false, help: [
+ 'Set to `true` to send separate osc messages for `low` and `high` handles. The `address` will be the same as the widget\'s with `/low` or `/high` appended to it',
+ 'Can be set as an object to specify a different `address` : `[\'/osc_address_low\', \'/osc_address_high\']`',
+ 'Note: the widget will only respond to its original osc address, not to the splitted version'
+ ]},
+ css: {type: 'string', value: '', help: [
+ 'Available CSS variables:',
+ '- `--color-gauge: color;`',
+ '- `--color-knob: color;`',
+ '- `--color-pips: color;`',
+ '- `--gauge-opacity: number;`'
+ ]}
+
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ `})
+
+ this.wrapper = DOM.get(this.widget, '.wrapper')[0]
+
+ this.faders = [
+ new RangeFader({props:{
+ ...faderDefaults,
+ compact:this.getProp('compact'),
+ pips:false,
+ alignRight:false,
+ horizontal:this.getProp('horizontal'),
+ height:'100%',
+ width:'100%',
+ default:this.getProp('default').length === 2 ? this.getProp('default')[0] : this.getProp('range').min,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ range:this.getProp('range'),
+ origin:'auto',
+ precision:this.getProp('precision'),
+ logScale:this.getProp('logScale'),
+ input:false
+ }, cancelDraw: true, parent: this}),
+ new RangeFader({props:{
+ ...faderDefaults,
+ compact:this.getProp('compact'),
+ pips:this.getProp('pips'),
+ alignRight:this.getProp('alignRight'),
+ horizontal:this.getProp('horizontal'),
+ height:'100%',
+ width:'100%',
+ default:this.getProp('default').length === 2 ? this.getProp('default')[1] : this.getProp('range').max,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ range:this.getProp('range'),
+ origin:'auto',
+ precision:this.getProp('precision'),
+ logScale:this.getProp('logScale'),
+ input:false
+ }, cancelDraw: false, parent: this})
+ ]
+
+ this.wrapper.appendChild(this.faders[0].widget)
+ this.wrapper.appendChild(this.faders[1].widget)
+
+ this.on('change',(e)=>{
+
+ if (e.widget == this) return
+
+ e.stopPropagation = true
+
+ var v = [
+ this.faders[0].getValue(),
+ this.faders[1].getValue()
+ ]
+
+ this.setValue(v, e.options)
+
+ })
+
+ this.touchMap = {}
+
+ touchstate(this, {element: this.wrapper, multitouch: true})
+
+ this.on('draginit',(e)=>{
+
+ var id
+
+ if (!this.touchMap[e.pointerId]) {
+
+ var ndiff, diff = -1
+
+ for (var i in this.faders) {
+
+ if (Object.values(this.touchMap).indexOf(i) != -1) continue
+
+ var coord = this.faders[i].percentToCoord(this.faders[i].valueToPercent(this.faders[i].value)) - (this.getProp('horizontal') ? -1 : 1) * (i == 0 ? -20 : 20)
+
+ ndiff = this.getProp('horizontal')?
+ Math.abs(e.offsetX - coord) :
+ Math.abs(e.offsetY - coord)
+
+ if (diff == -1 || ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+
+ }
+
+ this.touchMap[e.pointerId] = id
+
+
+ } else if (e.traversing) {
+
+ id = this.touchMap[e.pointerId]
+
+ }
+
+ if (!id) return
+
+ e.stopPropagation = true
+ this.faders[id].trigger('draginit', e)
+
+ }, {element: this.wrapper, multitouch: true})
+
+ this.on('drag',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+ if (e.shiftKey) {
+ this.faders[0].trigger('drag', e)
+ this.faders[1].trigger('drag', e)
+ } else {
+ this.faders[i].trigger('drag', e)
+ }
+
+ }, {element: this.wrapper, multitouch: true})
+
+ this.on('dragend',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+ e.stopPropagation = true
+ this.faders[i].trigger('dragend', e)
+ delete this.touchMap[e.pointerId]
+
+ }, {element: this.wrapper, multitouch: true})
+
+ if (this.getProp('input')) {
+
+ this.input = new Input({
+ props:{...Input.defaults()._props(),
+ precision:this.getProp('precision'),
+ unit:this.getProp('unit'),
+ vertical: this.getProp('compact') && !this.getProp('horizontal')
+ },
+ parent:this, parentNode:this.widget,
+ })
+ this.widget.appendChild(this.input.widget)
+ this.input.on('change', (e)=>{
+ e.stopPropagation = true
+ this.setValue(this.input.getValue(), {sync:true, send:true})
+ this.showValue()
+ })
+
+ }
+
+
+ if (this.getProp('horizontal')) {
+ this.widget.classList.add('horizontal')
+ this.container.classList.add('horizontal')
+ }
+ if (this.getProp('alignRight') && !this.getProp('horizontal')) {
+ this.widget.classList.add('align-right')
+ }
+ if (this.getProp('compact')) {
+ this.widget.classList.add('compact')
+ }
+ if (this.getProp('pips')) {
+ this.widget.classList.add('has-pips')
+ }
+
+ this.setValue([
+ this.faders[0].rangeValsMin,
+ this.faders[1].rangeValsMax
+ ])
+
+ }
+
+ setValue(v, options={}) {
+ if (!v || !v.length || v.length!=2) return
+
+
+ this.faders[0].rangeValsMax = v[1]
+ this.faders[1].rangeValsMin = v[0]
+
+ if (!options.dragged) {
+ this.faders[0].setValue(v[0])
+ this.faders[1].setValue(v[1])
+ }
+
+ this.value = [
+ this.faders[0].getValue(),
+ this.faders[1].getValue()
+ ]
+
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.faders[1].batchDraw()
+
+ this.showValue()
+
+
+ }
+
+ showValue() {
+
+ if (this.getProp('input')) this.input.setValue(this.value)
+
+ }
+
+ getSplit() {
+
+ return this.getProp('split')?
+ typeof this.getProp('split') == 'object' && this.getProp('split').length == 2 ?
+ this.getProp('split')
+ : [this.getProp('address') + '/low', this.getProp('address') + '/high']
+ : false
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of this.faders) {
+ w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.faders[0].onRemove()
+ this.faders[1].onRemove()
+ if (this.input) this.input.onRemove()
+ super.onRemove()
+ }
+
+}
+
+
+Range.dynamicProps = Range.prototype.constructor.dynamicProps.filter(n => n !== 'precision')
+
+module.exports = Range
diff --git a/src/client/app/widgets/sliders/slider.js b/src/client/app/widgets/sliders/slider.js
new file mode 100644
index 00000000..ef49fd0e
--- /dev/null
+++ b/src/client/app/widgets/sliders/slider.js
@@ -0,0 +1,284 @@
+var {clip, mapToScale} = require('../utils'),
+ Canvas = require('../common/canvas'),
+ touchstate = require('../mixins/touch_state'),
+ doubletab = require('../mixins/double_tap'),
+ Input = require('../inputs/input'),
+ html = require('nanohtml')
+
+class Slider extends Canvas {
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+ `})
+
+ this.wrapper = DOM.get(this.widget, '.wrapper')[0]
+
+ this.value = undefined
+ this.percent = 0
+
+ this.unit = this.getProp('unit') ? ' ' + this.getProp('unit') : ''
+
+
+ this.rangeKeys = []
+ this.rangeVals = []
+ this.rangeLabels = []
+
+ for (var k in this.getProp('range')) {
+ var key = k=='min'?0:k=='max'?100:parseInt(k),
+ val = typeof this.getProp('range')[k] == 'object'?
+ this.getProp('range')[k][Object.keys(this.getProp('range')[k])[0]]:
+ this.getProp('range')[k],
+ label = typeof this.getProp('range')[k] == 'object'?
+ Object.keys(this.getProp('range')[k])[0]:
+ val
+
+ this.rangeKeys.push(key)
+ this.rangeVals.push(val)
+ this.rangeLabels.push(label)
+ }
+ this.rangeValsMax = Math.max(...this.rangeVals),
+ this.rangeValsMin = Math.min(...this.rangeVals)
+
+ this.originValue = this.getProp('origin')=='auto'?
+ this.rangeValsMin:
+ clip(this.getProp('origin'), [this.rangeValsMin,this.rangeValsMax])
+
+ this.springValue = this.getProp('default') !== '' ? this.getProp('default') : this.originValue
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubletab(this.widget, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ })
+
+ } else {
+
+ doubletab(this.widget, ()=>{
+ this.setValue(this.springValue,{sync:true, send:true, fromLocal:true})
+ })
+
+ }
+
+ }
+
+
+ this.wrapper.addEventListener('mousewheel',this.mousewheelHandleProxy.bind(this))
+
+ this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.wrapper})
+ this.on('drag', this.dragHandleProxy.bind(this), {element:this.wrapper})
+ this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.wrapper})
+
+ touchstate(this, {element: this.wrapper})
+
+
+ if (this.getProp('input')) {
+
+ this.input = new Input({
+ props:{
+ ...Input.defaults()._props(),
+ precision:this.getProp('precision'),
+ unit:this.getProp('unit'),
+ vertical: this.getProp('type') == 'fader' && this.getProp('compact') && !this.getProp('horizontal')
+ },
+ parent:this, parentNode:this.widget
+ })
+
+ this.widget.appendChild(this.input.widget)
+ this.input.on('change', (e)=>{
+ e.stopPropagation = true
+ this.setValue(this.input.getValue(), {sync:true, send:true})
+ this.showValue()
+ })
+
+ }
+
+ this.setSteps()
+
+ this.setValue(this.springValue)
+
+ }
+
+ mousewheelHandleProxy() {
+
+ this.mousewheelHandle(...arguments)
+
+ }
+
+ draginitHandleProxy() {
+
+ this.draginitHandle(...arguments)
+
+ }
+
+ dragHandleProxy() {
+
+ this.dragHandle(...arguments)
+
+ }
+
+ dragendHandleProxy() {
+
+ this.dragendHandle(...arguments)
+
+ }
+
+ mousewheelHandle(e) {
+
+ if (e.wheelDeltaX) return
+
+ e.preventDefault()
+ e.stopPropagation()
+
+ var direction = e.wheelDelta / Math.abs(e.wheelDelta),
+ increment = e.ctrlKey?0.25:1
+
+ this.percent = clip(this.percent + Math.max(increment,10/Math.pow(10,this.precision + 1)) * direction, [0,100])
+
+ this.setValue(this.percentToValue(this.percent), {sync:true,send:true,dragged:true})
+
+ }
+
+ draginitHandle(e, data, traversing) {
+
+ }
+
+ dragHandle(e, data, traversing) {
+
+ }
+
+ dragendHandle(e, data, traversing) {
+
+ if (this.getProp('spring')) {
+ this.setValue(this.springValue,{sync:true,send:true,fromLocal:true})
+ }
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ super.cacheCanvasStyle(style)
+
+ this.colors.gauge = style.getPropertyValue('--color-gauge') || this.colors.custom
+ this.colors.knob = style.getPropertyValue('--color-knob') || this.colors.custom
+ this.colors.pips = style.getPropertyValue('--color-pips') || this.colors.custom
+ this.colors.gaugeOpacity = style.getPropertyValue('--gauge-opacity')
+
+
+ }
+
+
+ percentToValue(percent) {
+
+ var h = clip(percent,[0,100])
+ for (var i=0;i= this.rangeKeys[i]) {
+ return mapToScale(h,[this.rangeKeys[i],this.rangeKeys[i+1]],[this.rangeVals[i],this.rangeVals[i+1]],false,this.getProp('logScale'))
+ }
+ }
+
+ }
+
+ valueToPercent(value) {
+
+ for (var i=0;i this.rangeVals[i] && value <= this.rangeVals[i+1] && value >= this.rangeVals[i]) ||
+ (this.rangeVals[i+1] < this.rangeVals[i] && value >= this.rangeVals[i+1] && value <= this.rangeVals[i])
+ ) {
+ return mapToScale(value,[this.rangeVals[i],this.rangeVals[i+1]],[this.rangeKeys[i],this.rangeKeys[i+1]],false,this.getProp('logScale'),true)
+ }
+ }
+
+ }
+
+ setValue(v,options={}) {
+
+ if (typeof v != 'number') return
+ if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
+
+ var value = clip(v,[this.rangeValsMin,this.rangeValsMax])
+
+ if ((options.dragged || options.fromLocal) && this.value.toFixed(this.precision) == value.toFixed(this.precision)) options.send = false
+
+ this.value = value
+
+ if (this.getProp('steps')) {
+
+ var diff = this.steps.map(x => Math.abs(x - this.value)),
+ index = diff.indexOf(Math.min(...diff)),
+ val = this.steps[index]
+
+ if (!isNaN(val)) this.value = clip(val, [this.rangeValsMin,this.rangeValsMax])
+
+ }
+
+ if (!options.dragged) this.percent = this.valueToPercent(this.value)
+
+ if (!this.noDraw) this.batchDraw()
+
+ this.showValue()
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+ showValue() {
+
+ if (this.getProp('input')) this.input.setValue(this.value)
+
+ }
+
+ setSteps() {
+
+ if (this.getProp('steps')) {
+ var steps = this.getProp('steps')
+ this.steps = Array.isArray(steps) ?
+ steps : typeof steps === 'number' ?
+ Array(steps).fill(0).map((x, i) => i / (steps - 1) * (this.rangeValsMax - this.rangeValsMin) + this.rangeValsMin)
+ : this.rangeVals
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ if (this.input) this.input.onPropChanged('color')
+ return
+ case 'steps':
+ this.setSteps()
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ if (this.input) this.input.onRemove()
+ super.onRemove()
+ }
+
+}
+
+Slider.dynamicProps = Slider.prototype.constructor.dynamicProps
+ .filter(n => n !== 'precision')
+ .concat([
+ 'steps'
+ ])
+
+module.exports = Slider
diff --git a/src/browser/js/app/widgets/switchers/_switchers_base.js b/src/client/app/widgets/switchers/_switchers_base.js
similarity index 69%
rename from src/browser/js/app/widgets/switchers/_switchers_base.js
rename to src/client/app/widgets/switchers/_switchers_base.js
index 5c065ac3..e5563715 100644
--- a/src/browser/js/app/widgets/switchers/_switchers_base.js
+++ b/src/client/app/widgets/switchers/_switchers_base.js
@@ -1,11 +1,10 @@
-var _widgets_base = require('../common/_widgets_base'),
+var Widget = require('../common/widget'),
widgetManager = require('../../managers/widgets'),
osc = require('../../osc')
+module.exports = class _switchers_base extends Widget {
-module.exports = class _switchers_base extends _widgets_base {
-
- constructor(options) {
+ constructor(options) {
super(options)
@@ -19,7 +18,7 @@ module.exports = class _switchers_base extends _widgets_base {
}
- $('body').on(`change.${this.hash}`,this.syncHandler.bind(this))
+ widgetManager.on('change', this.syncHandler.bind(this), {context: this})
}
@@ -36,14 +35,6 @@ module.exports = class _switchers_base extends _widgets_base {
}
-
- onRemove() {
-
- $('body').off(`change.${this.hash}`)
- super.onRemove()
-
- }
-
isWatching(id, widget) {
if (this.linkedWidgets.indexOf(id) != -1) return true
@@ -54,7 +45,7 @@ module.exports = class _switchers_base extends _widgets_base {
for (var i in widgets) {
- if (widgets[i].widget[0].contains(widget.widget[0])) return true
+ if (widgets[i].contains(widget) || widgets[i] === widget) return true
}
@@ -91,20 +82,23 @@ module.exports = class _switchers_base extends _widgets_base {
}
- applyState(state, options) {
+ applyState(state, options) {
+
+ // extra sync routine to ensure linked widgets' props update before osc is sent
+ if (options.sync) this.changed({...options, send:false, sync:false})
+ //
+
for (var id in state) {
var value = state[id],
widgets = widgetManager.getWidgetById(id)
- if (widgets.length) {
- for (var i=widgets.length-1;i>=0;i--) {
- if (widgets[i].setValue) {
- widgets[i].setValue(value,{sync:options.sync, send:options.send})
- }
+ for (var i = widgets.length - 1; i >= 0; i--) {
+ if (widgets[i].setValue) {
+ widgets[i].setValue(value,{sync:options.sync, send:options.send})
}
}
}
- if (options.sync) this.widget.trigger({type:'change',id:this.getProp('id'),widget:this, linkId:this.getProp('linkId'), options:options})
+ if (options.sync) this.changed(options)
if (options.send) this.sendValue()
}
diff --git a/src/browser/js/app/widgets/switchers/crossfader.js b/src/client/app/widgets/switchers/crossfader.js
similarity index 50%
rename from src/browser/js/app/widgets/switchers/crossfader.js
rename to src/client/app/widgets/switchers/crossfader.js
index ed3fbdbd..d51558df 100644
--- a/src/browser/js/app/widgets/switchers/crossfader.js
+++ b/src/client/app/widgets/switchers/crossfader.js
@@ -1,20 +1,27 @@
var Switcher = require('./switcher'),
+ Widget = require('../common/widget'),
Fader = require('../sliders/fader'),
- {mapToScale, clip} = require('../utils')
+ {mapToScale} = require('../utils')
-var faderDefaults = Fader.defaults()
+var faderDefaults = Fader.defaults()._props()
module.exports = class Crossfader extends Switcher {
static defaults(){
- var o = super.defaults()
- o.type = 'crossfader'
- delete o.values
+ return Widget.defaults({
- return o
+ _crossfader: 'crossfader',
+ linkedWidgets: {type: 'string|array', value: '', help: [
+ '- `String`: a widget\'s `id` whose state changes will be stored',
+ '- `Array`: a list of widget `id` string'
+ ]},
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display values horizontally'}
+
+ })
+
}
constructor(options) {
@@ -26,30 +33,40 @@ module.exports = class Crossfader extends Switcher {
this.fader = new Fader({props:{
...faderDefaults,
horizontal: this.getProp('horizontal'),
- range: {min:{'A':0}, '50%':{" ":0.5},max:{'B':1}}
- }})
+ range: {min:{'A':0}, '50%':{' ':0.5},max:{'B':1}},
+ input: false
+ }, parent: this})
this.fader.sendValue = ()=>{}
- this.widget.append($('
').append(this.fader.widget))
+ this.widget.appendChild(this.fader.widget)
- this.fader.widget.on('change', (e)=>{
+ if (this.getProp('horizontal')) {
+ this.widget.classList.add('horizontal')
+ } else {
+ this.widget.classList.add('vertical')
- e.stopPropagation()
+ }
+
+ this.fader.on('change', (e)=>{
+
+ e.stopPropagation = true
this.setValue(this.fader.getValue(), e.options)
})
+ this.value._fader = 0
+
}
setValue(v, options={}) {
- var v = v <= 0 || v == 'A' ?
- 'A' :
- v >= 1 || v == 'B' ?
- 'B' :
- v
+ v = v <= 0 || v == 'A' ?
+ 'A' :
+ v >= 1 || v == 'B' ?
+ 'B' :
+ v
super.setValue(v, options)
@@ -93,7 +110,7 @@ module.exports = class Crossfader extends Switcher {
if (!isNaN(s['A'][i][k])) {
- a[i][k] = mapToScale(v, [0,1], [s['A'][i][k], s['B'][i][k]], false)
+ a[i][k] = mapToScale(v, [0,1], [s['A'][i][k], s['B'][i][k]], false)
}
@@ -101,7 +118,7 @@ module.exports = class Crossfader extends Switcher {
} else if (!isNaN(s['A'][i])) {
- a[i] = mapToScale(v, [0,1], [s['A'][i], s['B'][i]], false)
+ a[i] = mapToScale(v, [0,1], [s['A'][i], s['B'][i]], false)
}
}
@@ -111,4 +128,25 @@ module.exports = class Crossfader extends Switcher {
}
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of [this.fader]) {
+ w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.fader.onRemove()
+ super.onRemove()
+ }
+
}
diff --git a/src/client/app/widgets/switchers/switcher.js b/src/client/app/widgets/switchers/switcher.js
new file mode 100644
index 00000000..87a84613
--- /dev/null
+++ b/src/client/app/widgets/switchers/switcher.js
@@ -0,0 +1,88 @@
+var _switchers_base = require('./_switchers_base'),
+ Switch = require('../buttons/switch'),
+ html = require('nanohtml')
+
+var switchDefaults = Switch.defaults()._props()
+
+module.exports = class Switcher extends _switchers_base {
+
+ static defaults() {
+
+ return super.defaults({
+
+ _switcher: 'switcher',
+
+ linkedWidgets: {type: 'string|array', value: '', help: [
+ '- `String`: a widget\'s `id` whose state changes will be stored',
+ '- `Array`: a list of widget `id` string'
+ ]},
+ horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display values horizontally'},
+ values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
+ 'Each item represents a bank that stores the values from the widgets listed in `linkedWidgets`',
+ '- `Array` of possible values to switch between : `[1,2,3]`',
+ '- `Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ ]}
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
`})
+
+ if (this.getProp('horizontal')) this.widget.classList.add('horizontal')
+
+ this.switch = new Switch({props:{
+ ...switchDefaults,
+ label:false,
+ values:this.getProp('values'),
+ value: this.getProp('value'),
+ horizontal:this.getProp('horizontal')
+ }, parent: this})
+
+ this.switch.sendValue = ()=>{}
+
+ this.widget.appendChild(this.switch.widget)
+
+ this.switch.on('change', (e)=>{
+
+ e.stopPropagation = true
+ e.options.fromSelf = true
+
+ this.setValue(this.switch.getValue(), e.options)
+
+ })
+
+
+ }
+
+ setValue(v, options={}) {
+
+ super.setValue(v, options)
+
+ if (!options.fromSelf) this.switch.setValue(this.value._selected)
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'color':
+ for (var w of [this.switch]) {
+ w.onPropChanged('color')
+ }
+ return
+
+ }
+
+ }
+
+ onRemove() {
+ this.switch.onRemove()
+ super.onRemove()
+ }
+
+}
diff --git a/src/client/app/widgets/utils.js b/src/client/app/widgets/utils.js
new file mode 100644
index 00000000..990d541b
--- /dev/null
+++ b/src/client/app/widgets/utils.js
@@ -0,0 +1,109 @@
+module.exports = {
+
+ clip: function(value,range) {
+
+ value = parseFloat(value)
+
+ if (isNaN(value)) value = range[0]
+ return Math.max(Math.min(range[0],range[1]),Math.min(value,Math.max(range[0],range[1])))
+
+ },
+
+ // map a value from a scale to another input and output must be range arrays
+ mapToScale: function(value,rangeIn,rangeOut,precision,log,revertlog) {
+
+ value = module.exports.clip(value,[rangeIn[0],rangeIn[1]])
+
+ value = log ?
+ revertlog ?
+ (Math.pow(10,((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])))/9-1/9) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
+ :Math.log10(((value-rangeIn[0])/(rangeIn[1]-rangeIn[0]))*9+1) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
+ :((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
+
+ value = Math.max(Math.min(rangeOut[0],rangeOut[1]),Math.min(value,Math.max(rangeOut[0],rangeOut[1])))
+
+ if (precision !== false) value = parseFloat(value.toFixed(precision))
+
+
+ return value
+
+ },
+
+ hsbToRgb: function(hsb) {
+ var rgb = {}
+ var h = hsb.h
+ var s = hsb.s*255/100
+ var v = hsb.b*255/100
+ if(s == 0) {
+ rgb.r = rgb.g = rgb.b = v
+ } else {
+ var t1 = v
+ var t2 = (255-s)*v/255
+ var t3 = (t1-t2)*(h%60)/60
+ if(h==360) h = 0
+ if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
+ else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
+ else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
+ else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
+ else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
+ else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
+ else {rgb.r=0; rgb.g=0; rgb.b=0}
+ }
+ return rgb
+ },
+
+ rgbToHsb: function(rgb) {
+ var hsb = {h: 0, s: 0, b: 0}
+ var min = Math.min(rgb.r, rgb.g, rgb.b)
+ var max = Math.max(rgb.r, rgb.g, rgb.b)
+ var delta = max - min
+ hsb.b = max
+ hsb.s = max != 0 ? 255 * delta / max : 0
+ if (hsb.s != 0) {
+ if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
+ else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
+ else hsb.h = 4 + (rgb.r - rgb.g) / delta
+ } else hsb.h = 0
+ hsb.h *= 60
+ if (hsb.h < 0) hsb.h += 360
+ hsb.s *= 100/255
+ hsb.b *= 100/255
+ return hsb
+ },
+
+ math: (()=>{
+ var math = require('mathjs/dist/math.min.js').create({
+ matrix: 'Array'
+ })
+ math.import({
+ unpack: function(a) { return Array.isArray(a) ? a.toString() : a },
+ indexOf: function(a, x) { return a.indexOf(x) },
+ pad: function(x, padding) {
+ var str = String(x),
+ [int, dec] = str.split('.')
+ while (int.length < padding) {
+ int = '0' + int
+ }
+ return dec ? int + '.' + dec : int
+ },
+ length: function(x) { return x.length },
+ values: function(x) { return Object.values(x) },
+ keys: function(x) { return Object.keys(x) },
+ extend: function(x, y) { return Object.assign(x, y) },
+ timestamp: function() { return Date.now() },
+ // basic relationnal to keep alphabetical string comparison (v4 change)
+ equal: function(a, b) { return a == b },
+ unequal: function(a, b) { return a != b },
+ smaller: function(a, b) { return a < b },
+ larger: function(a, b) { return a > b },
+ smallerEq: function(a, b) { return a <= b },
+ largerEq: function(a, b) { return a >= b }
+ }, {override:true})
+
+ // set math's parser array index base to zero
+ math.expression.mathWithTransform = Object.assign({}, math)
+
+ return math
+ })()
+
+}
diff --git a/src/client/index.js b/src/client/index.js
new file mode 100644
index 00000000..04b9c6af
--- /dev/null
+++ b/src/client/index.js
@@ -0,0 +1,26 @@
+require('./app/stacktrace')
+require('./app/globals')
+
+var {loading} = require('./app/ui/utils'),
+ locales = require('./app/locales')
+
+document.addEventListener('DOMContentLoaded', function(event) {
+
+ DOM.init()
+
+ LOADING = loading(locales('loading_server'))
+
+ setTimeout(()=>{
+
+ var ipc = require('./app/ipc/')
+
+ ipc.init()
+
+ require('./app/ui/init')
+
+ ipc.send('ready', {backupId: ARGV.backupId})
+
+
+ }, 100)
+
+})
diff --git a/src/client/libs/jquery.touch.js b/src/client/libs/jquery.touch.js
new file mode 100644
index 00000000..d8f533d4
--- /dev/null
+++ b/src/client/libs/jquery.touch.js
@@ -0,0 +1,183 @@
+/*!
+ * jQuery UI Touch Punch 0.2.3
+ *
+ * Copyright 2011–2014, Dave Furfero
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ *
+ * Depends:
+ * jquery.ui.widget.js
+ * jquery.ui.mouse.js
+ */
+(function ($) {
+
+ // Detect touch support
+ $.support.touch = 'ontouchend' in document;
+
+ // Ignore browsers without touch support
+ if (!$.support.touch) {
+ return;
+ }
+
+ var mouseProto = $.ui.mouse.prototype,
+ _mouseInit = mouseProto._mouseInit,
+ _mouseDestroy = mouseProto._mouseDestroy,
+ touchHandled;
+
+ /**
+ * Simulate a mouse event based on a corresponding touch event
+ * @param {Object} event A touch event
+ * @param {String} simulatedType The corresponding mouse event
+ */
+ function simulateMouseEvent (event, simulatedType) {
+
+ // Ignore multi-touch events
+ if (event.originalEvent.touches.length > 1) {
+ return;
+ }
+
+ event.preventDefault();
+
+ var touch = event.originalEvent.changedTouches[0],
+ simulatedEvent = document.createEvent('MouseEvents');
+
+ // Initialize the simulated mouse event using the touch event's coordinates
+ simulatedEvent.initMouseEvent(
+ simulatedType, // type
+ true, // bubbles
+ true, // cancelable
+ window, // view
+ 1, // detail
+ touch.screenX, // screenX
+ touch.screenY, // screenY
+ touch.clientX, // clientX
+ touch.clientY, // clientY
+ false, // ctrlKey
+ false, // altKey
+ false, // shiftKey
+ false, // metaKey
+ 0, // button
+ null // relatedTarget
+ );
+
+ // osc: add a flag to prevent fast-click
+ simulatedEvent.touchPunch = true
+
+ // Dispatch the simulated event to the target element
+ event.target.dispatchEvent(simulatedEvent);
+ }
+
+ /**
+ * Handle the jQuery UI widget's touchstart events
+ * @param {Object} event The widget element's touchstart event
+ */
+ mouseProto._touchStart = function (event) {
+
+ var self = this;
+
+ // Ignore the event if another widget is already being handled
+ if (touchHandled || !self._mouseCapture(event.originalEvent.changedTouches[0])) {
+ return;
+ }
+
+ // Set the flag to prevent other widgets from inheriting the touch event
+ touchHandled = true;
+
+ // Track movement to determine if interaction was a click
+ self._touchMoved = false;
+
+ // Simulate the mouseover event
+ simulateMouseEvent(event, 'mouseover');
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+
+ // Simulate the mousedown event
+ simulateMouseEvent(event, 'mousedown');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchmove events
+ * @param {Object} event The document's touchmove event
+ */
+ mouseProto._touchMove = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Interaction was not a click
+ this._touchMoved = true;
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchend events
+ * @param {Object} event The document's touchend event
+ */
+ mouseProto._touchEnd = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Simulate the mouseup event
+ simulateMouseEvent(event, 'mouseup');
+
+ // Simulate the mouseout event
+ simulateMouseEvent(event, 'mouseout');
+
+ // If the touch interaction did not move, it should trigger a click
+ if (!this._touchMoved) {
+
+ // Simulate the click event
+ simulateMouseEvent(event, 'click');
+ }
+
+ // Unset the flag to allow other widgets to inherit the touch event
+ touchHandled = false;
+ };
+
+ /**
+ * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
+ * This method extends the widget with bound touch event handlers that
+ * translate touch events to mouse events and pass them to the widget's
+ * original mouse event handling methods.
+ */
+ mouseProto._mouseInit = function () {
+
+ var self = this;
+
+ // Delegate the touch handlers to the widget's element
+ self.element.bind({
+ touchstart: $.proxy(self, '_touchStart'),
+ touchmove: $.proxy(self, '_touchMove'),
+ touchend: $.proxy(self, '_touchEnd')
+ });
+
+ // Call the original $.ui.mouse init method
+ _mouseInit.call(self);
+ };
+
+ /**
+ * Remove the touch event handlers
+ */
+ mouseProto._mouseDestroy = function () {
+
+ var self = this;
+
+ // Delegate the touch handlers to the widget's element
+ self.element.unbind({
+ touchstart: $.proxy(self, '_touchStart'),
+ touchmove: $.proxy(self, '_touchMove'),
+ touchend: $.proxy(self, '_touchEnd')
+ });
+
+ // Call the original $.ui.mouse destroy method
+ _mouseDestroy.call(self);
+ };
+
+})($);
diff --git a/src/browser/js/libs/jquery.ui.js b/src/client/libs/jquery.ui.js
similarity index 98%
rename from src/browser/js/libs/jquery.ui.js
rename to src/client/libs/jquery.ui.js
index 2fdd10a6..8ba8cd1d 100644
--- a/src/browser/js/libs/jquery.ui.js
+++ b/src/client/libs/jquery.ui.js
@@ -6,15 +6,3 @@
(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t($)})(function(t){t.ui=t.ui||{},t.ui.version="1.12.0";var e=0,i=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},l=e.split(".")[0];e=e.split(".")[1];var h=l+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][h.toLowerCase()]=function(e){return!!t.data(e,h)},t[l]=t[l]||{},n=t[l][e],o=t[l][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:l,widgetName:e,widgetFullName:h}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var s,n,o=i.call(arguments,1),a=0,r=o.length;r>a;a++)for(s in o[a])n=o[a][s],o[a].hasOwnProperty(s)&&void 0!==n&&(e[s]=t.isPlainObject(n)?t.isPlainObject(e[s])?t.widget.extend({},e[s],n):t.widget.extend({},n):n);return e},t.widget.bridge=function(e,s){var n=s.prototype.widgetFullName||e;t.fn[e]=function(o){var a="string"==typeof o,r=i.call(arguments,1),l=this;return a?this.each(function(){var i,s=t.data(this,n);return"instance"===o?(l=s,!1):s?t.isFunction(s[o])&&"_"!==o.charAt(0)?(i=s[o].apply(s,r),i!==s&&void 0!==i?(l=i&&i.jquery?l.pushStack(i.get()):i,!1):void 0):t.error("no such method '"+o+"' for "+e+" widget instance"):t.error("cannot call methods on "+e+" prior to initialization; "+"attempted to call method '"+o+"'")}):(r.length&&(o=t.widget.extend.apply(null,[o].concat(r))),this.each(function(){var e=t.data(this,n);e?(e.option(o||{}),e._init&&e._init()):t.data(this,n,new s(o,this))})),l}},t.Widget=function(){},t.Widget._childConstructors=[],t.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"",options:{classes:{},disabled:!1,create:null},_createWidget:function(i,s){s=t(s||this.defaultElement||this)[0],this.element=t(s),this.uuid=e++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=t(),this.hoverable=t(),this.focusable=t(),this.classesElementLookup={},s!==this&&(t.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(t){t.target===s&&this.destroy()}}),this.document=t(s.style?s.ownerDocument:s.document||s),this.window=t(this.document[0].defaultView||this.document[0].parentWindow)),this.options=t.widget.extend({},this.options,this._getCreateOptions(),i),this._create(),this.options.disabled&&this._setOptionDisabled(this.options.disabled),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:function(){return{}},_getCreateEventData:t.noop,_create:t.noop,_init:t.noop,destroy:function(){var e=this;this._destroy(),t.each(this.classesElementLookup,function(t,i){e._removeClass(i,t)}),this.element.off(this.eventNamespace).removeData(this.widgetFullName),this.widget().off(this.eventNamespace).removeAttr("aria-disabled"),this.bindings.off(this.eventNamespace)},_destroy:t.noop,widget:function(){return this.element},option:function(e,i){var s,n,o,a=e;if(0===arguments.length)return t.widget.extend({},this.options);if("string"==typeof e)if(a={},s=e.split("."),e=s.shift(),s.length){for(n=a[e]=t.widget.extend({},this.options[e]),o=0;s.length-1>o;o++)n[s[o]]=n[s[o]]||{},n=n[s[o]];if(e=s.pop(),1===arguments.length)return void 0===n[e]?null:n[e];n[e]=i}else{if(1===arguments.length)return void 0===this.options[e]?null:this.options[e];a[e]=i}return this._setOptions(a),this},_setOptions:function(t){var e;for(e in t)this._setOption(e,t[e]);return this},_setOption:function(t,e){return"classes"===t&&this._setOptionClasses(e),this.options[t]=e,"disabled"===t&&this._setOptionDisabled(e),this},_setOptionClasses:function(e){var i,s,n;for(i in e)n=this.classesElementLookup[i],e[i]!==this.options.classes[i]&&n&&n.length&&(s=t(n.get()),this._removeClass(n,i),s.addClass(this._classes({element:s,keys:i,classes:e,add:!0})))},_setOptionDisabled:function(t){this._toggleClass(this.widget(),this.widgetFullName+"-disabled",null,!!t),t&&(this._removeClass(this.hoverable,null,"ui-state-hover"),this._removeClass(this.focusable,null,"ui-state-focus"))},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_classes:function(e){function i(i,o){var a,r;for(r=0;i.length>r;r++)a=n.classesElementLookup[i[r]]||t(),a=e.add?t(t.unique(a.get().concat(e.element.get()))):t(a.not(e.element).get()),n.classesElementLookup[i[r]]=a,s.push(i[r]),o&&e.classes[i[r]]&&s.push(e.classes[i[r]])}var s=[],n=this;return e=t.extend({element:this.element,classes:this.options.classes||{}},e),e.keys&&i(e.keys.match(/\S+/g)||[],!0),e.extra&&i(e.extra.match(/\S+/g)||[]),s.join(" ")},_removeClass:function(t,e,i){return this._toggleClass(t,e,i,!1)},_addClass:function(t,e,i){return this._toggleClass(t,e,i,!0)},_toggleClass:function(t,e,i,s){s="boolean"==typeof s?s:i;var n="string"==typeof t||null===t,o={extra:n?e:i,keys:n?t:e,element:n?this.element:t,add:s};return o.element.toggleClass(this._classes(o),s),this},_on:function(e,i,s){var n,o=this;"boolean"!=typeof e&&(s=i,i=e,e=!1),s?(i=n=t(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),t.each(s,function(s,a){function r(){return e||o.options.disabled!==!0&&!t(this).hasClass("ui-state-disabled")?("string"==typeof a?o[a]:a).apply(o,arguments):void 0}"string"!=typeof a&&(r.guid=a.guid=a.guid||r.guid||t.guid++);var l=s.match(/^([\w:-]*)\s*(.*)$/),h=l[1]+o.eventNamespace,c=l[2];c?n.on(h,c,r):i.on(h,r)})},_off:function(e,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.off(i).off(i),this.bindings=t(this.bindings.not(e).get()),this.focusable=t(this.focusable.not(e).get()),this.hoverable=t(this.hoverable.not(e).get())},_delay:function(t,e){function i(){return("string"==typeof t?s[t]:t).apply(s,arguments)}var s=this;return setTimeout(i,e||0)},_hoverable:function(e){this.hoverable=this.hoverable.add(e),this._on(e,{mouseenter:function(e){this._addClass(t(e.currentTarget),null,"ui-state-hover")},mouseleave:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-hover")}})},_focusable:function(e){this.focusable=this.focusable.add(e),this._on(e,{focusin:function(e){this._addClass(t(e.currentTarget),null,"ui-state-focus")},focusout:function(e){this._removeClass(t(e.currentTarget),null,"ui-state-focus")}})},_trigger:function(e,i,s){var n,o,a=this.options[e];if(s=s||{},i=t.Event(i),i.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase(),i.target=this.element[0],o=i.originalEvent)for(n in o)n in i||(i[n]=o[n]);return this.element.trigger(i,s),!(t.isFunction(a)&&a.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},t.each({show:"fadeIn",hide:"fadeOut"},function(e,i){t.Widget.prototype["_"+e]=function(s,n,o){"string"==typeof n&&(n={effect:n});var a,r=n?n===!0||"number"==typeof n?i:n.effect||i:e;n=n||{},"number"==typeof n&&(n={duration:n}),a=!t.isEmptyObject(n),n.complete=o,n.delay&&s.delay(n.delay),a&&t.effects&&t.effects.effect[r]?s[e](n):r!==e&&s[r]?s[r](n.duration,n.easing,o):s.queue(function(i){t(this)[e](),o&&o.call(s[0]),i()})}}),t.widget,t.extend(t.expr[":"],{data:t.expr.createPseudo?t.expr.createPseudo(function(e){return function(i){return!!t.data(i,e)}}):function(e,i,s){return!!t.data(e,s[3])}}),t.fn.extend({disableSelection:function(){var t="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.on(t+".ui-disableSelection",function(t){t.preventDefault()})}}(),enableSelection:function(){return this.off(".ui-disableSelection")}}),t.fn.scrollParent=function(e){var i=this.css("position"),s="absolute"===i,n=e?/(auto|scroll|hidden)/:/(auto|scroll)/,o=this.parents().filter(function(){var e=t(this);return s&&"static"===e.css("position")?!1:n.test(e.css("overflow")+e.css("overflow-y")+e.css("overflow-x"))}).eq(0);return"fixed"!==i&&o.length?o:t(this[0].ownerDocument||document)},t.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase());var s=!1;t(document).on("mouseup",function(){s=!1}),t.widget("ui.mouse",{version:"1.12.0",options:{cancel:"input, textarea, button, select, option",distance:1,delay:0},_mouseInit:function(){var e=this;this.element.on("mousedown."+this.widgetName,function(t){return e._mouseDown(t)}).on("click."+this.widgetName,function(i){return!0===t.data(i.target,e.widgetName+".preventClickEvent")?(t.removeData(i.target,e.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.off("."+this.widgetName),this._mouseMoveDelegate&&this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(e){if(!s){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(e),this._mouseDownEvent=e;var i=this,n=1===e.which,o="string"==typeof this.options.cancel&&e.target.nodeName?t(e.target).closest(this.options.cancel).length:!1;return n&&!o&&this._mouseCapture(e)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(e)!==!1,!this._mouseStarted)?(e.preventDefault(),!0):(!0===t.data(e.target,this.widgetName+".preventClickEvent")&&t.removeData(e.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(t){return i._mouseMove(t)},this._mouseUpDelegate=function(t){return i._mouseUp(t)},this.document.on("mousemove."+this.widgetName,this._mouseMoveDelegate).on("mouseup."+this.widgetName,this._mouseUpDelegate),e.preventDefault(),s=!0,!0)):!0}},_mouseMove:function(e){if(this._mouseMoved){if(t.ui.ie&&(!document.documentMode||9>document.documentMode)&&!e.button)return this._mouseUp(e);if(!e.which)if(e.originalEvent.altKey||e.originalEvent.ctrlKey||e.originalEvent.metaKey||e.originalEvent.shiftKey)this.ignoreMissingWhich=!0;else if(!this.ignoreMissingWhich)return this._mouseUp(e)}return(e.which||e.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(e),e.preventDefault()):(this._mouseDistanceMet(e)&&this._mouseDelayMet(e)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,e)!==!1,this._mouseStarted?this._mouseDrag(e):this._mouseUp(e)),!this._mouseStarted)},_mouseUp:function(e){this.document.off("mousemove."+this.widgetName,this._mouseMoveDelegate).off("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,e.target===this._mouseDownEvent.target&&t.data(e.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(e)),this._mouseDelayTimer&&(clearTimeout(this._mouseDelayTimer),delete this._mouseDelayTimer),this.ignoreMissingWhich=!1,s=!1,e.preventDefault()},_mouseDistanceMet:function(t){return Math.max(Math.abs(this._mouseDownEvent.pageX-t.pageX),Math.abs(this._mouseDownEvent.pageY-t.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),t.ui.plugin={add:function(e,i,s){var n,o=t.ui[e].prototype;for(n in s)o.plugins[n]=o.plugins[n]||[],o.plugins[n].push([i,s[n]])},call:function(t,e,i,s){var n,o=t.plugins[e];if(o&&(s||t.element[0].parentNode&&11!==t.element[0].parentNode.nodeType))for(n=0;o.length>n;n++)t.options[o[n][0]]&&o[n][1].apply(t.element,i)}},t.ui.safeActiveElement=function(t){var e;try{e=t.activeElement}catch(i){e=t.body}return e||(e=t.body),e.nodeName||(e=t.body),e},t.ui.safeBlur=function(e){e&&"body"!==e.nodeName.toLowerCase()&&t(e).trigger("blur")},t.widget("ui.draggable",t.ui.mouse,{version:"1.12.0",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"===this.options.helper&&this._setPositionRelative(),this.options.addClasses&&this._addClass("ui-draggable"),this._setHandleClassName(),this._mouseInit()},_setOption:function(t,e){this._super(t,e),"handle"===t&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(e){var i=this.options;return this._blurActiveElement(e),this.helper||i.disabled||t(e.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(e),this.handle?(this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(e){this.iframeBlocks=this.document.find(e).map(function(){var e=t(this);return t("
").css("position","absolute").appendTo(e.parent()).outerWidth(e.outerWidth()).outerHeight(e.outerHeight()).offset(e.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(e){var i=t.ui.safeActiveElement(this.document[0]),s=t(e.target);this._getHandle(e)&&s.closest(i).length||t.ui.safeBlur(i)},_mouseStart:function(e){var i=this.options;return this.helper=this._createHelper(e),this._addClass(this.helper,"ui-draggable-dragging"),this._cacheHelperProportions(),t.ui.ddmanager&&(t.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===t(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(e),this.originalPosition=this.position=this._generatePosition(e,!1),this.originalPageX=e.pageX,this.originalPageY=e.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",e)===!1?(this._clear(),!1):(this._cacheHelperProportions(),t.ui.ddmanager&&!i.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this._mouseDrag(e,!0),t.ui.ddmanager&&t.ui.ddmanager.dragStart(this,e),!0)},_refreshOffsets:function(t){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:t.pageX-this.offset.left,top:t.pageY-this.offset.top}},_mouseDrag:function(e,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(e,!0),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",e,s)===!1)return this._mouseUp(new t.Event("mouseup",e)),!1;this.position=s.position}return this.helper[0].style.left=this.position.left+"px",this.helper[0].style.top=this.position.top+"px",t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),!1},_mouseStop:function(e){var i=this,s=!1;return t.ui.ddmanager&&!this.options.dropBehaviour&&(s=t.ui.ddmanager.drop(this,e)),this.dropped&&(s=this.dropped,this.dropped=!1),"invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||t.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?t(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",e)!==!1&&i._clear()}):this._trigger("stop",e)!==!1&&this._clear(),!1},_mouseUp:function(e){return this._unblockFrames(),t.ui.ddmanager&&t.ui.ddmanager.dragStop(this,e),this.handleElement.is(e.target)&&this.element.trigger("focus"),t.ui.mouse.prototype._mouseUp.call(this,e)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp(new t.Event("mouseup",{target:this.element[0]})):this._clear(),this},_getHandle:function(e){return this.options.handle?!!t(e.target).closest(this.element.find(this.options.handle)).length:!0},_setHandleClassName:function(){this.handleElement=this.options.handle?this.element.find(this.options.handle):this.element,this._addClass(this.handleElement,"ui-draggable-handle")},_removeHandleClassName:function(){this._removeClass(this.handleElement,"ui-draggable-handle")},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper),n=s?t(i.helper.apply(this.element[0],[e])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_isRootNode:function(t){return/(html|body)/i.test(t.tagName)||t===this.document[0]},_getParentOffset:function(){var e=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"!==this.cssPosition)return{top:0,left:0};var t=this.element.position(),e=this._isRootNode(this.scrollParent[0]);return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+(e?0:this.scrollParent.scrollTop()),left:t.left-(parseInt(this.helper.css("left"),10)||0)+(e?0:this.scrollParent.scrollLeft())}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),l=t.pageX,h=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left
i[2]&&(l=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(h=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((h-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,h=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((l-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,l=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(l=this.originalPageX),"x"===a.axis&&(h=this.originalPageY)),{top:h-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:l-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,t.each(s.sortables,function(){var t=this;t.isOver?(t.isOver=0,s.cancelHelperRemoval=!0,t.cancelHelperRemoval=!1,t._storedCSS={position:t.placeholder.css("position"),top:t.placeholder.css("top"),left:t.placeholder.css("left")},t._mouseStop(e),t.options.helper=t.options._helper):(t.cancelHelperRemoval=!0,t._trigger("deactivate",e,n))})},drag:function(e,i,s){t.each(s.sortables,function(){var n=!1,o=this;o.positionAbs=s.positionAbs,o.helperProportions=s.helperProportions,o.offset.click=s.offset.click,o._intersectsWith(o.containerCache)&&(n=!0,t.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==o&&this._intersectsWith(this.containerCache)&&t.contains(o.element[0],this.element[0])&&(n=!1),n})),n?(o.isOver||(o.isOver=1,s._parent=i.helper.parent(),o.currentItem=i.helper.appendTo(o.element).data("ui-sortable-item",!0),o.options._helper=o.options.helper,o.options.helper=function(){return i.helper[0]},e.target=o.currentItem[0],o._mouseCapture(e,!0),o._mouseStart(e,!0,!0),o.offset.click.top=s.offset.click.top,o.offset.click.left=s.offset.click.left,o.offset.parent.left-=s.offset.parent.left-o.offset.parent.left,o.offset.parent.top-=s.offset.parent.top-o.offset.parent.top,s._trigger("toSortable",e),s.dropped=o.element,t.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,o.fromOutside=s),o.currentItem&&(o._mouseDrag(e),i.position=o.position)):o.isOver&&(o.isOver=0,o.cancelHelperRemoval=!0,o.options._revert=o.options.revert,o.options.revert=!1,o._trigger("out",e,o._uiHash(o)),o._mouseStop(e,!0),o.options.revert=o.options._revert,o.options.helper=o.options._helper,o.placeholder&&o.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(e),i.position=s._generatePosition(e,!0),s._trigger("fromSortable",e),s.dropped=!1,t.each(s.sortables,function(){this.refreshPositions()}))})}}),t.ui.plugin.add("draggable","cursor",{start:function(e,i,s){var n=t("body"),o=s.options;n.css("cursor")&&(o._cursor=n.css("cursor")),n.css("cursor",o.cursor)},stop:function(e,i,s){var n=s.options;n._cursor&&t("body").css("cursor",n._cursor)}}),t.ui.plugin.add("draggable","opacity",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("opacity")&&(o._opacity=n.css("opacity")),n.css("opacity",o.opacity)},stop:function(e,i,s){var n=s.options;n._opacity&&t(i.helper).css("opacity",n._opacity)}}),t.ui.plugin.add("draggable","scroll",{start:function(t,e,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(e,i,s){var n=s.options,o=!1,a=s.scrollParentNotHidden[0],r=s.document[0];a!==r&&"HTML"!==a.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+a.offsetHeight-e.pageY=0;d--)l=s.snapElements[d].left-s.margins.left,h=l+s.snapElements[d].width,c=s.snapElements[d].top-s.margins.top,u=c+s.snapElements[d].height,l-g>_||m>h+g||c-g>b||v>u+g||!t.contains(s.snapElements[d].item.ownerDocument,s.snapElements[d].item)?(s.snapElements[d].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=!1):("inner"!==f.snapMode&&(n=g>=Math.abs(c-b),o=g>=Math.abs(u-v),a=g>=Math.abs(l-_),r=g>=Math.abs(h-m),n&&(i.position.top=s._convertPositionTo("relative",{top:c-s.helperProportions.height,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left)),p=n||o||a||r,"outer"!==f.snapMode&&(n=g>=Math.abs(c-v),o=g>=Math.abs(u-b),a=g>=Math.abs(l-m),r=g>=Math.abs(h-_),n&&(i.position.top=s._convertPositionTo("relative",{top:c,left:0}).top),o&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left)),!s.snapElements[d].snapping&&(n||o||a||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,e,t.extend(s._uiHash(),{snapItem:s.snapElements[d].item})),s.snapElements[d].snapping=n||o||a||r||p)}}),t.ui.plugin.add("draggable","stack",{start:function(e,i,s){var n,o=s.options,a=t.makeArray(t(o.stack)).sort(function(e,i){return(parseInt(t(e).css("zIndex"),10)||0)-(parseInt(t(i).css("zIndex"),10)||0)});a.length&&(n=parseInt(t(a[0]).css("zIndex"),10)||0,t(a).each(function(e){t(this).css("zIndex",n+e)}),this.css("zIndex",n+a.length))}}),t.ui.plugin.add("draggable","zIndex",{start:function(e,i,s){var n=t(i.helper),o=s.options;n.css("zIndex")&&(o._zIndex=n.css("zIndex")),n.css("zIndex",o.zIndex)},stop:function(e,i,s){var n=s.options;n._zIndex&&t(i.helper).css("zIndex",n._zIndex)}}),t.ui.draggable,t.widget("ui.resizable",t.ui.mouse,{version:"1.12.0",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,classes:{"ui-resizable-se":"ui-icon ui-icon-gripsmall-diagonal-se"},containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(t){return parseFloat(t)||0},_isNumber:function(t){return!isNaN(parseFloat(t))},_hasScroll:function(e,i){if("hidden"===t(e).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return e[s]>0?!0:(e[s]=1,n=e[s]>0,e[s]=0,n)},_create:function(){var e,i=this.options,s=this;this._addClass("ui-resizable"),t.extend(this,{_aspectRatio:!!i.aspectRatio,aspectRatio:i.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:i.helper||i.ghost||i.animate?i.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(t("
").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.resizable("instance")),this.elementIsWrapper=!0,e={marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom"),marginLeft:this.originalElement.css("marginLeft")},this.element.css(e),this.originalElement.css("margin",0),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css(e),this._proportionallyResize()),this._setupHandles(),i.autoHide&&t(this.element).on("mouseenter",function(){i.disabled||(s._removeClass("ui-resizable-autohide"),s._handles.show())
}).on("mouseleave",function(){i.disabled||s.resizing||(s._addClass("ui-resizable-autohide"),s._handles.hide())}),this._mouseInit()},_destroy:function(){this._mouseDestroy();var e,i=function(e){t(e).removeData("resizable").removeData("ui-resizable").off(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),e=this.element,this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")}).insertAfter(e),e.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_setOption:function(t,e){switch(this._super(t,e),t){case"handles":this._removeHandles(),this._setupHandles();break;default:}},_setupHandles:function(){var e,i,s,n,o,a=this.options,r=this;if(this.handles=a.handles||(t(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se"),this._handles=t(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),s=this.handles.split(","),this.handles={},i=0;s.length>i;i++)e=t.trim(s[i]),n="ui-resizable-"+e,o=t(""),this._addClass(o,"ui-resizable-handle "+n),o.css({zIndex:a.zIndex}),this.handles[e]=".ui-resizable-"+e,this.element.append(o);this._renderAxis=function(e){var i,s,n,o;e=e||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=t(this.handles[i]),this._on(this.handles[i],{mousedown:r._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=t(this.handles[i],this.element),o=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),e.css(n,o),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.on("mouseover",function(){r.resizing||(this.className&&(o=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),r.axis=o&&o[1]?o[1]:"se")}),a.autoHide&&(this._handles.hide(),this._addClass("ui-resizable-autohide"))},_removeHandles:function(){this._handles.remove()},_mouseCapture:function(e){var i,s,n=!1;for(i in this.handles)s=t(this.handles[i])[0],(s===e.target||t.contains(s,e.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(e){var i,s,n,o=this.options,a=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),o.containment&&(i+=t(o.containment).scrollLeft()||0,s+=t(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:e.pageX,top:e.pageY},this.aspectRatio="number"==typeof o.aspectRatio?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=t(".ui-resizable-"+this.axis).css("cursor"),t("body").css("cursor","auto"===n?this.axis+"-resize":n),this._addClass("ui-resizable-resizing"),this._propagate("start",e),!0},_mouseDrag:function(e){var i,s,n=this.originalMousePosition,o=this.axis,a=e.pageX-n.left||0,r=e.pageY-n.top||0,l=this._change[o];return this._updatePrevProperties(),l?(i=l.apply(this,[e,a,r]),this._updateVirtualBoundaries(e.shiftKey),(this._aspectRatio||e.shiftKey)&&(i=this._updateRatio(i,e)),i=this._respectSize(i,e),this._updateCache(i),this._propagate("resize",e),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),t.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",e,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(e){this.resizing=!1;var i,s,n,o,a,r,l,h=this.options,c=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:c.sizeDiff.height,o=s?0:c.sizeDiff.width,a={width:c.helper.width()-o,height:c.helper.height()-n},r=parseFloat(c.element.css("left"))+(c.position.left-c.originalPosition.left)||null,l=parseFloat(c.element.css("top"))+(c.position.top-c.originalPosition.top)||null,h.animate||this.element.css(t.extend(a,{top:l,left:r})),c.helper.height(c.size.height),c.helper.width(c.size.width),this._helper&&!h.animate&&this._proportionallyResize()),t("body").css("cursor","auto"),this._removeClass("ui-resizable-resizing"),this._propagate("stop",e),this._helper&&this.helper.remove(),!1},_updatePrevProperties:function(){this.prevPosition={top:this.position.top,left:this.position.left},this.prevSize={width:this.size.width,height:this.size.height}},_applyChanges:function(){var t={};return this.position.top!==this.prevPosition.top&&(t.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(t.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(t.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(t.height=this.size.height+"px"),this.helper.css(t),t},_updateVirtualBoundaries:function(t){var e,i,s,n,o,a=this.options;o={minWidth:this._isNumber(a.minWidth)?a.minWidth:0,maxWidth:this._isNumber(a.maxWidth)?a.maxWidth:1/0,minHeight:this._isNumber(a.minHeight)?a.minHeight:0,maxHeight:this._isNumber(a.maxHeight)?a.maxHeight:1/0},(this._aspectRatio||t)&&(e=o.minHeight*this.aspectRatio,s=o.minWidth/this.aspectRatio,i=o.maxHeight*this.aspectRatio,n=o.maxWidth/this.aspectRatio,e>o.minWidth&&(o.minWidth=e),s>o.minHeight&&(o.minHeight=s),o.maxWidth>i&&(o.maxWidth=i),o.maxHeight>n&&(o.maxHeight=n)),this._vBoundaries=o},_updateCache:function(t){this.offset=this.helper.offset(),this._isNumber(t.left)&&(this.position.left=t.left),this._isNumber(t.top)&&(this.position.top=t.top),this._isNumber(t.height)&&(this.size.height=t.height),this._isNumber(t.width)&&(this.size.width=t.width)},_updateRatio:function(t){var e=this.position,i=this.size,s=this.axis;return this._isNumber(t.height)?t.width=t.height*this.aspectRatio:this._isNumber(t.width)&&(t.height=t.width/this.aspectRatio),"sw"===s&&(t.left=e.left+(i.width-t.width),t.top=null),"nw"===s&&(t.top=e.top+(i.height-t.height),t.left=e.left+(i.width-t.width)),t},_respectSize:function(t){var e=this._vBoundaries,i=this.axis,s=this._isNumber(t.width)&&e.maxWidth&&e.maxWidth
t.width,a=this._isNumber(t.height)&&e.minHeight&&e.minHeight>t.height,r=this.originalPosition.left+this.originalSize.width,l=this.originalPosition.top+this.originalSize.height,h=/sw|nw|w/.test(i),c=/nw|ne|n/.test(i);return o&&(t.width=e.minWidth),a&&(t.height=e.minHeight),s&&(t.width=e.maxWidth),n&&(t.height=e.maxHeight),o&&h&&(t.left=r-e.minWidth),s&&h&&(t.left=r-e.maxWidth),a&&c&&(t.top=l-e.minHeight),n&&c&&(t.top=l-e.maxHeight),t.width||t.height||t.left||!t.top?t.width||t.height||t.top||!t.left||(t.left=null):t.top=null,t},_getPaddingPlusBorderDimensions:function(t){for(var e=0,i=[],s=[t.css("borderTopWidth"),t.css("borderRightWidth"),t.css("borderBottomWidth"),t.css("borderLeftWidth")],n=[t.css("paddingTop"),t.css("paddingRight"),t.css("paddingBottom"),t.css("paddingLeft")];4>e;e++)i[e]=parseFloat(s[e])||0,i[e]+=parseFloat(n[e])||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var t,e=0,i=this.helper||this.element;this._proportionallyResizeElements.length>e;e++)t=this._proportionallyResizeElements[e],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(t)),t.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var e=this.element,i=this.options;this.elementOffset=e.offset(),this._helper?(this.helper=this.helper||t("
"),this._addClass(this.helper,this._helper),this.helper.css({width:this.element.outerWidth(),height:this.element.outerHeight(),position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(t,e){return{width:this.originalSize.width+e}},w:function(t,e){var i=this.originalSize,s=this.originalPosition;return{left:s.left+e,width:i.width-e}},n:function(t,e,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(t,e,i){return{height:this.originalSize.height+i}},se:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},sw:function(e,i,s){return t.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[e,i,s]))},ne:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[e,i,s]))},nw:function(e,i,s){return t.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[e,i,s]))}},_propagate:function(e,i){t.ui.plugin.call(this,e,[i,this.ui()]),"resize"!==e&&this._trigger(e,i,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),t.ui.plugin.add("resizable","animate",{stop:function(e){var i=t(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,o=n.length&&/textarea/i.test(n[0].nodeName),a=o&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=o?0:i.sizeDiff.width,l={width:i.size.width-r,height:i.size.height-a},h=parseFloat(i.element.css("left"))+(i.position.left-i.originalPosition.left)||null,c=parseFloat(i.element.css("top"))+(i.position.top-i.originalPosition.top)||null;i.element.animate(t.extend(l,c&&h?{top:c,left:h}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseFloat(i.element.css("width")),height:parseFloat(i.element.css("height")),top:parseFloat(i.element.css("top")),left:parseFloat(i.element.css("left"))};n&&n.length&&t(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",e)}})}}),t.ui.plugin.add("resizable","containment",{start:function(){var e,i,s,n,o,a,r,l=t(this).resizable("instance"),h=l.options,c=l.element,u=h.containment,d=u instanceof t?u.get(0):/parent/.test(u)?c.parent().get(0):u;d&&(l.containerElement=t(d),/document/.test(u)||u===document?(l.containerOffset={left:0,top:0},l.containerPosition={left:0,top:0},l.parentData={element:t(document),left:0,top:0,width:t(document).width(),height:t(document).height()||document.body.parentNode.scrollHeight}):(e=t(d),i=[],t(["Top","Right","Left","Bottom"]).each(function(t,s){i[t]=l._num(e.css("padding"+s))}),l.containerOffset=e.offset(),l.containerPosition=e.position(),l.containerSize={height:e.innerHeight()-i[3],width:e.innerWidth()-i[1]},s=l.containerOffset,n=l.containerSize.height,o=l.containerSize.width,a=l._hasScroll(d,"left")?d.scrollWidth:o,r=l._hasScroll(d)?d.scrollHeight:n,l.parentData={element:d,left:s.left,top:s.top,width:a,height:r}))},resize:function(e){var i,s,n,o,a=t(this).resizable("instance"),r=a.options,l=a.containerOffset,h=a.position,c=a._aspectRatio||e.shiftKey,u={top:0,left:0},d=a.containerElement,p=!0;d[0]!==document&&/static/.test(d.css("position"))&&(u=l),h.left<(a._helper?l.left:0)&&(a.size.width=a.size.width+(a._helper?a.position.left-l.left:a.position.left-u.left),c&&(a.size.height=a.size.width/a.aspectRatio,p=!1),a.position.left=r.helper?l.left:0),h.top<(a._helper?l.top:0)&&(a.size.height=a.size.height+(a._helper?a.position.top-l.top:a.position.top),c&&(a.size.width=a.size.height*a.aspectRatio,p=!1),a.position.top=a._helper?l.top:0),n=a.containerElement.get(0)===a.element.parent().get(0),o=/relative|absolute/.test(a.containerElement.css("position")),n&&o?(a.offset.left=a.parentData.left+a.position.left,a.offset.top=a.parentData.top+a.position.top):(a.offset.left=a.element.offset().left,a.offset.top=a.element.offset().top),i=Math.abs(a.sizeDiff.width+(a._helper?a.offset.left-u.left:a.offset.left-l.left)),s=Math.abs(a.sizeDiff.height+(a._helper?a.offset.top-u.top:a.offset.top-l.top)),i+a.size.width>=a.parentData.width&&(a.size.width=a.parentData.width-i,c&&(a.size.height=a.size.width/a.aspectRatio,p=!1)),s+a.size.height>=a.parentData.height&&(a.size.height=a.parentData.height-s,c&&(a.size.width=a.size.height*a.aspectRatio,p=!1)),p||(a.position.left=a.prevPosition.left,a.position.top=a.prevPosition.top,a.size.width=a.prevSize.width,a.size.height=a.prevSize.height)},stop:function(){var e=t(this).resizable("instance"),i=e.options,s=e.containerOffset,n=e.containerPosition,o=e.containerElement,a=t(e.helper),r=a.offset(),l=a.outerWidth()-e.sizeDiff.width,h=a.outerHeight()-e.sizeDiff.height;e._helper&&!i.animate&&/relative/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:l,height:h}),e._helper&&!i.animate&&/static/.test(o.css("position"))&&t(this).css({left:r.left-n.left-s.left,width:l,height:h})}}),t.ui.plugin.add("resizable","alsoResize",{start:function(){var e=t(this).resizable("instance"),i=e.options;t(i.alsoResize).each(function(){var e=t(this);e.data("ui-resizable-alsoresize",{width:parseFloat(e.width()),height:parseFloat(e.height()),left:parseFloat(e.css("left")),top:parseFloat(e.css("top"))})})},resize:function(e,i){var s=t(this).resizable("instance"),n=s.options,o=s.originalSize,a=s.originalPosition,r={height:s.size.height-o.height||0,width:s.size.width-o.width||0,top:s.position.top-a.top||0,left:s.position.left-a.left||0};t(n.alsoResize).each(function(){var e=t(this),s=t(this).data("ui-resizable-alsoresize"),n={},o=e.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];t.each(o,function(t,e){var i=(s[e]||0)+(r[e]||0);i&&i>=0&&(n[e]=i||null)}),e.css(n)})},stop:function(){t(this).removeData("ui-resizable-alsoresize")}}),t.ui.plugin.add("resizable","ghost",{start:function(){var e=t(this).resizable("instance"),i=e.size;e.ghost=e.originalElement.clone(),e.ghost.css({opacity:.25,display:"block",position:"relative",height:i.height,width:i.width,margin:0,left:0,top:0}),e._addClass(e.ghost,"ui-resizable-ghost"),t.uiBackCompat!==!1&&"string"==typeof e.options.ghost&&e.ghost.addClass(this.options.ghost),e.ghost.appendTo(e.helper)},resize:function(){var e=t(this).resizable("instance");e.ghost&&e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})},stop:function(){var e=t(this).resizable("instance");e.ghost&&e.helper&&e.helper.get(0).removeChild(e.ghost.get(0))}}),t.ui.plugin.add("resizable","grid",{resize:function(){var e,i=t(this).resizable("instance"),s=i.options,n=i.size,o=i.originalSize,a=i.originalPosition,r=i.axis,l="number"==typeof s.grid?[s.grid,s.grid]:s.grid,h=l[0]||1,c=l[1]||1,u=Math.round((n.width-o.width)/h)*h,d=Math.round((n.height-o.height)/c)*c,p=o.width+u,f=o.height+d,g=s.maxWidth&&p>s.maxWidth,m=s.maxHeight&&f>s.maxHeight,_=s.minWidth&&s.minWidth>p,v=s.minHeight&&s.minHeight>f;s.grid=l,_&&(p+=h),v&&(f+=c),g&&(p-=h),m&&(f-=c),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=a.top-d):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=a.left-u):((0>=f-c||0>=p-h)&&(e=i._getPaddingPlusBorderDimensions(this)),f-c>0?(i.size.height=f,i.position.top=a.top-d):(f=c-e.height,i.size.height=f,i.position.top=a.top+o.height-f),p-h>0?(i.size.width=p,i.position.left=a.left-u):(p=h-e.width,i.size.width=p,i.position.left=a.left+o.width-p))}}),t.ui.resizable,t.widget("ui.sortable",t.ui.mouse,{version:"1.12.0",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(t,e,i){return t>=e&&e+i>t},_isFloating:function(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))},_create:function(){this.containerCache={},this._addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(t,e){this._super(t,e),"handle"===t&&this._setHandleClassName()},_setHandleClassName:function(){var e=this;this._removeClass(this.element.find(".ui-sortable-handle"),"ui-sortable-handle"),t.each(this.items,function(){e._addClass(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item,"ui-sortable-handle")})},_destroy:function(){this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(e,i){var s=null,n=!1,o=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,o.widgetName+"-item")===o?(s=t(this),!1):void 0}),t.data(e.target,o.widgetName+"-item")===o&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,o,a=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,a.cursorAt&&this._adjustOffsetFromHelper(a.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),a.containment&&this._setContainment(),a.cursor&&"auto"!==a.cursor&&(o=this.document.find("body"),this.storedCursor=o.css("cursor"),o.css("cursor",a.cursor),this.storedStylesheet=t("").appendTo(o)),a.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",a.opacity)),a.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",a.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!a.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this._addClass(this.helper,"ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,o,a=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY=0;i--)if(s=this.items[i],n=s.item[0],o=this._intersectsWithPointer(s),o&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===o?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===o?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),o=this.options.axis,a={};o&&"x"!==o||(a.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),o&&"y"!==o||(a.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(a,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?(this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,o=t.left,a=o+t.width,r=t.top,l=r+t.height,h=this.offset.click.top,c=this.offset.click.left,u="x"===this.options.axis||s+h>r&&l>s+h,d="y"===this.options.axis||e+c>o&&a>e+c,p=u&&d;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?p:e+this.helperProportions.width/2>o&&a>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&l>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var e,i,s="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),n="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),o=s&&n;return o?(e=this._getDragVerticalDirection(),i=this._getDragHorizontalDirection(),this.floating?"right"===i||"down"===e?2:1:e&&("down"===e?2:1)):!1},_intersectsWithSides:function(t){var e=this._isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&e||"up"===s&&!e)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){function i(){r.push(this)}var s,n,o,a,r=[],l=[],h=this._connectWith();if(h&&e)for(s=h.length-1;s>=0;s--)for(o=t(h[s],this.document[0]),n=o.length-1;n>=0;n--)a=t.data(o[n],this.widgetFullName),a&&a!==this&&!a.options.disabled&&l.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(l.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=l.length-1;s>=0;s--)l[s][0].each(i);return t(r)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,o,a,r,l,h,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i],this.document[0]),s=n.length-1;s>=0;s--)o=t.data(n[s],this.widgetFullName),o&&o!==this&&!o.options.disabled&&(u.push([t.isFunction(o.options.items)?o.options.items.call(o.element[0],e,{item:this.currentItem}):t(o.options.items,o.element),o]),this.containers.push(o));for(i=u.length-1;i>=0;i--)for(a=u[i][1],r=u[i][0],s=0,h=r.length;h>s;s++)l=t(r[s]),l.data(this.widgetName+"-item",a),c.push({item:l,instance:a,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,o;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),o=n.offset(),s.left=o.left,s.top=o.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)o=this.containers[i].element.offset(),this.containers[i].containerCache.left=o.left,this.containers[i].containerCache.top=o.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t("<"+s+">",e.document[0]);return e._addClass(n,"ui-sortable-placeholder",i||e.currentItem[0].className)._removeClass(n,"ui-sortable-helper"),"tbody"===s?e._createTrPlaceholder(e.currentItem.find("tr").eq(0),t("",e.document[0]).appendTo(n)):"tr"===s?e._createTrPlaceholder(e.currentItem,n):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_createTrPlaceholder:function(e,i){var s=this;e.children().each(function(){t(" ",s.document[0]).attr("colspan",t(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(e){var i,s,n,o,a,r,l,h,c,u,d=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!t.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(d&&t.contains(this.containers[i].element[0],d.element[0]))continue;d=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",e,this._uiHash(this)),this.containers[i].containerCache.over=0);if(d)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,o=null,c=d.floating||this._isFloating(this.currentItem),a=c?"left":"top",r=c?"width":"height",u=c?"pageX":"pageY",s=this.items.length-1;s>=0;s--)t.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(l=this.items[s].item.offset()[a],h=!1,e[u]-l>this.items[s][r]/2&&(h=!0),n>Math.abs(e[u]-l)&&(n=Math.abs(e[u]-l),o=this.items[s],this.direction=h?"up":"down"));if(!o&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",e,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;o?this._rearrange(e,o,null,!0):this._rearrange(e,null,this.containers[p].element,!0),this._trigger("change",e,this._uiHash()),this.containers[p]._trigger("change",e,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",e,this._uiHash(this)),this.containers[p].containerCache.over=1
}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.height()||document.body.parentNode.scrollHeight:this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():o?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():o?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,o=e.pageX,a=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,l=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.leftthis.containment[2]&&(o=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(a=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((a-this.originalPageY)/n.grid[1])*n.grid[1],a=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((o-this.originalPageX)/n.grid[0])*n.grid[0],o=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:a-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():l?0:r.scrollTop()),left:o-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():l?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})});
-
-/*!
- * jQuery UI Touch Punch 0.2.3
- *
- * Copyright 2011–2014, Dave Furfero
- * Dual licensed under the MIT or GPL Version 2 licenses.
- *
- * Depends:
- * jquery.ui.widget.js
- * jquery.ui.mouse.js
- */
-!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.on({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.off({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}($);
diff --git a/src/launcher/index.js b/src/launcher/index.js
new file mode 100644
index 00000000..fa66f1b0
--- /dev/null
+++ b/src/launcher/index.js
@@ -0,0 +1,305 @@
+var {remote, ipcRenderer, shell} = eval('require(\'electron\')'),
+ {dialog, Menu, MenuItem, app} = remote.require('electron'),
+ menu = new Menu(),
+ settings = remote.getGlobal('settings'),
+ packageInfos = remote.require('./package.json'),
+ packageVersion = packageInfos.version,
+ packageUrl = packageInfos.repository.url,
+ argv_remote = settings.read('argv'),
+ ansiHTML = require('ansi-html'),
+ argv = {},
+ $ = require('jquery/dist/jquery.slim.min.js')
+
+for (i in argv_remote) {
+ argv[i] = argv_remote[i]
+}
+
+$(document).ready(()=>{
+
+ var form = $(`
+