Merge branch 'master' into v1

This commit is contained in:
bordun 2020-02-23 16:36:10 +01:00
commit 3ad7915b8f
103 changed files with 94 additions and 59 deletions

View file

@ -0,0 +1,115 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils'),
html = require('nanohtml'),
raw = require('nanohtml/raw')
class Dropdown extends Widget {
static description() {
return 'Native dropdown menu.'
}
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`<div class="select"></div>`})
this.select = this.widget.appendChild(html`<select class="no-keybinding"></select>`)
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`<option value=""></option>`)
this.values = []
for (var k in values) {
this.values.push(values[k])
this.select.appendChild(html`
<option value="${i}">
${raw(iconify(parseFloat(k) != k ? k : values[k]))}
</option>
`)
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

View file

@ -0,0 +1,325 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils'),
doubletab = require('../mixins/double_tap'),
html = require('nanohtml'),
raw = require('nanohtml/raw')
class Menu extends Widget {
static description() {
return 'Drag and drop menu with a circular or grid layout.'
}
static defaults() {
return super.defaults({
_menu:'menu',
size: {type: 'number|array', value: 200, help: [
'- If `layout` is `circular`: diameter (in px)',
'- Else: square size or `[width, height]` array',
]},
layout: {type: 'string', value: 'circular', choices: ['circular', 'horizontal', 'vertical', 'grid'], help: [
'Defines whether the menu\'s layout should be rendered in a circle or in a box'
]},
columns: {type: 'number', value: '', help: [
'If `layout` is `grid`, defines the number of columns'
]},
toggle: {type: 'boolean', value: false, help: 'Set to `true` to make the menu stay opened after mouse/touch release'},
doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the menu require a double tap to be opened instead of a single tap'},
values: {type: 'array|object', value: [1, 2, 3], 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',
]},
weights: {type: 'array', value: '', help: [
'`Array` of `number` defining the weights of each value in `values`',
'Ignored when `grid` is `true`'
]}
})
}
constructor(options) {
super({...options, html: html`
<inner>
</inner>
`})
this.menu = html`<menu></menu>`
this.opened = false
this.values = []
this.stringValues = []
this.selected = -1
this.value = undefined
this.parseValues()
this.parentScroll = [0,0]
if (this.getProp('doubleTap')) {
doubletab(this.widget, (e)=>{
if (this.opened) return
this.open(e)
})
this.on('draginit',(e)=>{
if (this.opened && this.getProp('toggle')) {
this.selectValue(e)
this.submitValue()
}
}, {element: this.widget})
} else {
this.on('draginit',(e)=>{
if (this.opened && this.getProp('toggle')) {
this.selectValue(e)
this.submitValue()
} else if (!this.opened) {
this.open(e)
}
}, {element: this.widget})
}
if (!this.getProp('toggle')) {
this.on('drag',(e)=>{
this.selectValue(e, true)
}, {element: this.widget})
this.on('dragend',()=>{
if (!this.opened) return
this.submitValue()
}, {element: this.widget})
} else {
this.toggleCloseHandler = (e)=>{
if (!this.opened || this.menu.contains(e.target)) return
this.close()
}
document.addEventListener('fast-click', this.toggleCloseHandler)
}
this.setMode()
this.setSize()
}
open(e) {
if (this.opened) return
this.opened = true
this.container.classList.add('on')
this.widget.appendChild(this.menu)
}
close() {
if (!this.opened) return
this.opened = false
DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
this.container.classList.remove('on')
this.widget.removeChild(this.menu)
}
selectValue(e, drag) {
// touch hover fix
var node = drag && e.isTouch ? document.elementFromPoint(e.clientX, e.clientY)
: e.target
if (node === this.menu || !this.menu.contains(node)) {
DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
this.selected = -1
} else if (!node.classList.contains('active')) {
DOM.each(this.menu, '.active', (el)=>{el.classList.remove('active')})
node.classList.add('active')
this.selected = DOM.index(node)
}
}
submitValue(e) {
this.close()
if (this.selected > -1) {
this.setValue(this.values[this.selected], {send: true, sync: true})
}
}
parseValues() {
var nval = 0,
i = 0,
circular = this.getProp('layout') === 'circular',
values = this.getProp('values'),
weights = this.getProp('weights'),
totalWeight
if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
values = values !== '' ? [values] : []
}
this.values = []
if (this.opened) this.widget.removeChild(this.menu)
this.menu.innerHTML = ''
nval = Array.isArray(values) ? values.length : Object.keys(values).length
weights = Array.isArray(weights) ? weights.slice(0, nval) : Array(nval).fill(1)
if (weights.length < nval) weights = weights.concat(Array(nval - weights.length).fill(1))
totalWeight = weights.reduce((a, b) => a + b, 0)
var ac = 0
for (let k in values) {
let angle = Math.min(360 * weights[i] / totalWeight, 120),
skew = 90 - angle
this.values.push(values[k])
if (typeof values[k] == 'object') {
this.stringValues.push(JSON.stringify(values[k]))
} else {
this.stringValues.push(0)
}
this.menu.appendChild(html`
<div class="item" style="${circular ? `transform: rotate(${ac}deg) skew(${skew}deg)` : `flex: ${weights[i]}`}">
<div style="${circular ? `transform: skew(${-skew}deg) rotate(${-90 + angle / 2}deg)` : ''}"><span style="${circular ? `transform: rotate(${-ac + 90 - angle / 2}deg)` : ''}">${raw(iconify(parseFloat(k) != k ? k : values[k]))}</span></div>
</div>
`)
i++
ac+=angle
}
this.setValue(this.value)
if (this.opened) this.widget.appendChild(this.menu)
}
setMode() {
var layout = this.getProp('layout')
this.container.classList.toggle('box', layout !== 'circular')
this.container.classList.toggle('circular', layout === 'circular')
this.container.classList.toggle('grid', layout === 'grid')
this.container.classList.toggle('vertical', layout === 'vertical')
this.container.style.setProperty('--grid-columns', this.getProp('columns') === '' ? parseInt(this.values.length / 2) : parseInt(this.getProp('columns')))
}
setSize() {
var size = this.getProp('size')
if (Array.isArray(size)) {
this.container.style.setProperty('--size', parseInt(size[0]) + 'rem')
this.container.style.setProperty('--size-box-w', parseInt(size[0]) + 'rem')
this.container.style.setProperty('--size-box-h', parseInt(size[1]) + 'rem')
} else {
this.container.style.setProperty('--size', parseInt(size) + 'rem')
this.container.style.setProperty('--size-box-w', parseInt(size) + 'rem')
this.container.style.setProperty('--size-box-h', parseInt(size) + 'rem')
}
}
setValue(v,options={}) {
var i = this.values.indexOf(v)
if (i > -1) {
this.value = this.values[i]
this.selected = i
}
DOM.each(this.menu, '.on', (el)=>{el.classList.remove('on')})
if (i > -1) DOM.get(this.menu, '.item')[i].classList.add('on')
this.widget.textContent = this.stringValues[i] || this.value
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
onPropChanged(propName, options, oldPropValue) {
var ret = super.onPropChanged(...arguments)
switch (propName) {
case 'size':
this.setSize()
return
case 'layout':
this.parseValues()
this.setMode()
return
case 'columns':
this.setMode()
return
case 'values':
this.parseValues()
return
}
return ret
}
onRemove() {
if (this.getProp('toggle')) {
document.removeEventListener('fast-click', this.toggleCloseHandler)
}
super.onRemove()
}
}
Menu.dynamicProps = Menu.prototype.constructor.dynamicProps.concat(
'size',
'layout',
'columns',
'values'
)
module.exports = Menu

View file

@ -0,0 +1,129 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils'),
html = require('nanohtml'),
raw = require('nanohtml/raw')
module.exports = class Switch extends Widget {
static description() {
return 'Value selector button.'
}
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',
]},
mode: {type: 'string', value: 'tap', choices: ['tap', 'slide', 'click'], help: [
'Interraction mode:',
'- `tap`: activates when the pointer is down but prevents further scrolling',
'- `slide`: same as `tap` but allows sliding between values',
'- `click`: activates upon click only and allows further scrolling',
]},
})
}
constructor(options) {
super({...options, html: html`<inner></inner>`})
if (this.getProp('horizontal')) this.container.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`
<value> ${raw(iconify(label))}</value>
`)
}
this.value = undefined
var dragCallback = (e, touchFix)=>{
var index = 0,
node = e.target
if (touchFix && e.isTouch) {
// special traversing touch fix
node = document.elementFromPoint(e.clientX, e.clientY)
}
if (node === this.widget || !this.widget.contains(node)) return
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})
}
if (this.getProp('mode') === 'tap' || this.getProp('mode') === 'slide') {
this.on('draginit', dragCallback , {element: this.widget})
this.on('drag', (e)=>{
if (this.getProp('mode') === 'slide' || e.traversing) dragCallback(e, true)
} , {element: this.widget})
} else {
this.widget.addEventListener('click', dragCallback)
}
}
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)
}
}}

View file

@ -0,0 +1,158 @@
var Widget = require('../common/widget'),
doubletab = require('../mixins/double_tap'),
html = require('nanohtml')
class Toggle extends Widget {
static description() {
return 'On / off button.'
}
static defaults() {
return super.defaults({
_toggle: 'toggle',
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)'
]},
mode: {type: 'string', value: 'toggle', choices: ['toggle', 'push', 'tap'], help: [
'Interraction mode:',
'- `toggle` (classic on/off switch)',
'- `push` (press & release)',
'- `tap` (no release)'
]},
doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the button require a double tap to be pushed instead of a single tap'},
})
}
constructor(options) {
super({...options, html: html`<inner></inner>`})
this.state = 0
this.active = false
if (this.getProp('led')) this.container.classList.add('led')
var tap = this.getProp('mode') === 'tap',
push = this.getProp('mode') === 'push' || tap
if (push) {
if (this.getProp('doubleTap')) {
doubletab(this.container, ()=>{
this.setValue(this.getProp('on'), {sync: true, send: true})
})
} else {
this.on('draginit',()=>{
if (this.active) return
this.active = true
this.setValue(this.getProp('on'), {sync: true, send: true})
}, {element: this.container})
}
this.on('dragend',()=>{
this.active = false
this.setValue(this.getProp('off'), {sync: true, send: !tap})
}, {element: this.container})
} else {
if (this.getProp('doubleTap')) {
doubletab(this.container, ()=>{
this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true})
})
} else {
this.on('draginit',()=>{
if (this.active) return
this.active = true
this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true})
}, {element: this.container})
this.on('dragend',()=>{
this.active = false
}, {element: this.container})
}
}
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.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.container.classList.remove('on')
this.state = 0
this.value = this.getProp('off')
if (options.send) this.sendValue()
}
if (options.sync) this.changed(options)
}
onRemove() {
if (this.active && this.getProp('mode') === 'push') this.setValue(this.getProp('off'), {sync: true, send: true})
super.onRemove()
}
}
Toggle.dynamicProps = Toggle.prototype.constructor.dynamicProps.concat(
'on',
'off',
'norelease'
)
module.exports = Toggle

View file

@ -0,0 +1,242 @@
var Widget = require('./widget'),
resize = require('../../events/resize')
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.container, 'canvas')[0]
this.ctx = this.canvas.getContext('2d',{
desynchronized: true,
lowLatency: true,
alpha: true,
preserveDrawingBuffer: true // avoid flickering
})
this.height = undefined
this.width = undefined
this.scaling = 1
this.clearRect = []
this.visible = false
this.colors = {}
this.cssVars = {}
this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
this.ctx.arc = (x, y, r, s, e, c)=>{
this.ctx.__proto__.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
this.batchDraw()
}
cacheCanvasStyle(style){
style = style || window.getComputedStyle(this.canvas)
this.cssVars.padding = parseFloat(style.getPropertyValue('--widget-padding')) * PXSCALE // rem unit
this.cssVars.colorWidget = style.getPropertyValue('--color-widget')
this.cssVars.colorFill = style.getPropertyValue('--color-fill')
this.cssVars.colorStroke = style.getPropertyValue('--color-stroke')
this.cssVars.colorForeground = style.getPropertyValue('--color-foreground')
this.cssVars.alphaStroke = parseFloat(style.getPropertyValue('--alpha-stroke'))
this.cssVars.alphaFillOff = parseFloat(style.getPropertyValue('--alpha-fill-off'))
this.cssVars.alphaFillOn = parseFloat(style.getPropertyValue('--alpha-fill-on'))
this.colors.custom = style.getPropertyValue('--color-custom')
this.colors.track = style.getPropertyValue('--color-track')
this.colors.text = style.getPropertyValue('--color-text')
this.colors.textFade = style.getPropertyValue('--color-text-fade')
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)
} else if (typeof this.clearRect[0] == 'object') {
for (let i in this.clearRect) {
this.ctx.clearRect(...this.clearRect[i])
}
} else {
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 'css':
case 'colorWidget':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
case 'alphaFillOff':
case 'alphaFillOn':
setTimeout(()=>{
this.cacheCanvasStyle()
this.batchDraw()
},10)
return
case 'padding':
resize.check(this.widget)
}
return ret
}
onRemove() {
this.off('resize')
super.onRemove()
}
}
Canvas.dynamicProps = Canvas.prototype.constructor.dynamicProps.concat(
'on',
'off'
)
module.exports = Canvas

View file

@ -0,0 +1,75 @@
var Widget = require('./widget')
var Container = (Class=Widget)=> class extends Class {
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

View file

@ -0,0 +1,70 @@
var osc = require('../../osc')
module.exports = class OscReceiver {
constructor(options) {
var {address, value, parent, propName, usePreArgs} = options
try {
this.value = JSON.parse(value)
} catch (err) {
this.value = value
}
this.parent = parent
this.propNames = [propName]
this.usePreArgs = usePreArgs
this.bindedCallback = this.callback.bind(this)
this.prefix = ''
this.setAddress(address)
}
setAddress(address) {
if (this.address !== address) {
if (this.address) osc.off(this.prefix + this.address, this.bindedCallback, this.parent)
if (address) this.address = address
if (this.address[0] !== '/') {
this.prefix = this.parent.getProp('address') || this.parent.resolveProp('address', undefined, false, this)
if (this.prefix[this.prefix.length - 1] !== '/') this.prefix += '/'
}
osc.on(this.prefix + 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.usePreArgs ? (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)
}
}
}

View file

@ -0,0 +1,995 @@
var EventEmitter = require('../../events/event-emitter'),
osc = require('../../osc'),
nanoid = require('nanoid/generate'),
widgetManager = require('../../managers/widgets'),
{math, evaljs, urlParser} = 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'),
// ipc = require('../../ipc'),
updateWidget = ()=>{}
var oscReceiverState = {}
var OSCProps = [
'precision',
'address',
'preArgs',
'target',
'bypass'
]
var dummyDOM
DOM.ready(()=>{
dummyDOM = html`<div></div>`
})
setTimeout(()=>{
updateWidget = require('../../editor/data-workers').updateWidget
})
class Widget extends EventEmitter {
static description() {
return ''
}
static defaults(insert={}, except=[], push={}) {
var defaults = {
_widget:'widget',
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.' },
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 (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)'
]},
visible: {type: 'boolean', value: true, help: 'Set to `false` to hide the widget.'},
_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',
colorWidget: {type: 'string', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
colorStroke: {type: 'string', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
colorFill: {type: 'string', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
alphaStroke: {type: 'number', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
alphaFillOff: {type: 'number', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
alphaFillOn: {type: 'number', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
padding: {type: 'number', value: 'auto', help: 'Defines the widget\'s accent color (css variable `--custom-color`). Must be a valid CSS color. Set to "auto" to inherit from parent widget.'},
css: {type: 'string', value: '', help: 'CSS rules. See <a href="https://openstagecontrol.ammd.net/docs/css-tips/">documentation</a>.'},
_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 the advanced property syntax'},
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)'
]},
_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) {
if (!alterDefaults[m]) alterDefaults[m] = []
Object.assign(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
this.removed = false
this.mounted = false
this.createPropsCache()
if (this.getProp('id') == 'root' && !options.root) {
this.cachedProps.id = '_root'
this.errors.id = 'There can only be one root'
}
this.disabledProps = []
// this.mathjsDeprecationWarned = false
// cache precision
if (this.props.precision != undefined) {
this.precision = Math.min(20,Math.max(this.getProp('precision', undefined, false),0))
}
this.container = html`
<div class="widget ${options.props.type}-container" id="${this.hash}" data-widget="${this.hash}"></div>
`
this.label = html`<label></label>`
if (this.getProp('label') !== false) this.container.appendChild(this.label)
if (this.widget) this.container.appendChild(this.widget)
this.container._widget_instance = this
this.setContainerStyles()
}
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() {}
checkLinkedProps(propNames) {
// Dynamic props cache check
var linkedProps = []
Object.values(this.nestedLinkedProps).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(this.linkedProps).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(this.linkedPropsValue).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(this.oscReceivers).forEach(r => linkedProps = linkedProps.concat(r.propNames))
if (
// if prop/osc listeners have changed (@{} / OSC{})
// refresh the widget's props cache and update linked props bindings
propNames.map(x => this.props[x]).some(x => typeof x === 'string' && x.match(/OSC\{|@\{/))
|| propNames.some(n => linkedProps.includes(n))
) {
this.createPropsCache()
}
}
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 = {},
defaultScope = this.constructor.parsersContexts[propName] || {},
mathscope = context || {},
varnumber = 999
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, usePreArgs] = 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({
address: resolvedAddress,
value: value,
parent: this,
propName: propName,
usePreArgs: usePreArgs === 'false' ? false : true
})
if (oscReceiverState[address]) {
this.oscReceivers[address].value = oscReceiverState[address]
delete oscReceiverState[address]
}
} else {
this.oscReceivers[address].setAddress(resolvedAddress)
this.oscReceivers[address].addProp(propName)
this.oscReceivers[address].usePreArgs = usePreArgs === 'false' ? false : true
}
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: #\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}
//TODO: js one-liner
return ''
})
} catch (err) {
console.log((this.getProp('id') || this.props.id) + '.' + propName + ': #{} error:\n' + err)
}
try {
propValue = propValue.replace(/JS\{\{([\s\S]*)\}\}/g, (m, code)=>{
if (!this.parsers[code]) this.parsers[code] = evaljs(code, defaultScope)
let r = this.parsers[code](mathscope)
if (r === undefined) r = ''
return typeof r !== 'string' ? JSON.stringify(r) : r
})
} catch (err) {
var stackline = err.stack ? (err.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - 2) : ''
console.log((this.getProp('id') || this.props.id) + '.' + propName + ': JS{{}} error:\n' + err + line)
}
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')
}
if (widget && options) options.id = widget.getProp('id')
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)) {
if ((!widget || !this.contains(widget)) && widget !== this && !(widget === this && updatedProps.length === 1 && updatedProps[0] === 'value')) {
reCreate = true
break
}
} else {
this.cachedProps[propName] = propValue
changedProps.push({propName, oldPropValue})
}
}
}
if (reCreate) {
return this.reCreateWidget({reCreateOptions: options})
} else if (changedProps.length) {
if (options && options.fromEditor) {
this.checkLinkedProps(propNames)
}
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.send, id: options.id})
return
case 'top':
case 'left':
this.setContainerStyles(['geometry'])
return
case 'height':
case 'width':
this.setContainerStyles(['geometry'])
resize.check(this.container)
return
case 'visible':
this.setContainerStyles(['visibility'])
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 'colorWidget':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
case 'alphaFillOff':
case 'alphaFillOn':
case 'padding':
this.setContainerStyles(['color'])
return
case 'precision':
case 'address':
case 'preArgs':
case 'target':
case 'noSync':
if (propName === 'address') {
for (var k in this.oscReceivers) {
var receiver = this.oscReceivers[k]
if (receiver.prefix !== '') {
receiver.setAddress()
}
}
}
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', 'visibility']) {
if (styles.includes('visibility')) {
this.container.style.display = this.getProp('visible') ? '' : 'none'
}
if (styles.includes('geometry')) {
// geometry
var absolutePos = false
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) {
if (geometry === 'auto') geometry = ''
this.container.style[d] = geometry
if (d === 'width') this.container.style.minWidth = geometry
if (d === 'height') this.container.style.minHeight = geometry
absolutePos = absolutePos || geometry && (d === 'top' || d === 'left')
}
}
this.container.classList.toggle('absolute-position', absolutePos)
}
if (styles.includes('label')) {
// label
if (this.getProp('label') === false) {
this.container.classList.add('nolabel')
this.label.innerHTML = ''
} else {
this.container.classList.remove('nolabel')
var label = this.getProp('label') == 'auto'?
this.getProp('id'):
iconify(this.getProp('label'))
this.label.innerHTML = label
this.container.appendChild(this.label)
}
}
if (styles.includes('css')) {
// css
var css = String(this.getProp('css')),
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 m
extraCssClasses.push(c.replace(/"'/g,''))
return ''
})
// escpape windows absolute file paths
css = css.replace(/url\(([^)]*)\)/g, (m, url)=>{
var parser = urlParser(url)
if (!parser.protocol.match(/http|data/)) m = m.replace(':', '_:_')
m = m.replace(/\\/g, '\\\\')
return m
})
var prefix = '#' + this.hash,
scopedCss = scopeCss(css, prefix),
unScopedCss = ''
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`<style>${unScopedCss ? prefix + '{' + unScopedCss + '}\n' : ''}${scopedCss}</style>`,
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.container.childNodes[0] || null)
}
// 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-widget', this.getProp('colorWidget') != 'auto' ? this.getProp('colorWidget') : '')
this.container.style.setProperty('--color-fill', this.getProp('colorFill') != 'auto' ? this.getProp('colorFill') : '')
this.container.style.setProperty('--color-stroke', this.getProp('colorStroke') != 'auto' ? this.getProp('colorStroke') : '')
this.container.style.setProperty('--alpha-stroke', this.getProp('alphaStroke') != 'auto' ? parseFloat(this.getProp('alphaStroke')) : '')
this.container.style.setProperty('--alpha-fill-on', this.getProp('alphaFillOn') != 'auto' ? parseFloat(this.getProp('alphaFillOn')) : '')
this.container.style.setProperty('--alpha-fill-off', this.getProp('alphaFillOff') != 'auto' ? parseFloat(this.getProp('alphaFillOff')) : '')
this.container.style.setProperty('--widget-padding', this.getProp('padding') != 'auto' ? parseFloat(this.getProp('padding')) + 'rem' : '')
}
return style
}
reCreateWidget(options={}){
if (!this.removed) return updateWidget(this, options)
}
onRemove(){
this.removed = true
widgetManager.off(undefined, undefined, this)
this.removeOscReceivers()
}
}
Widget.parsersContexts = {}
Widget.dynamicProps = [
'visible',
'label',
'top',
'left',
'height',
'width',
'colorWidget',
'colorFill',
'colorStroke',
'alphaStroke',
'alphaFillOff',
'alphaFillOn',
'padding',
'css',
'value',
'precision',
'address',
'preArgs',
'target',
'bypass'
]
module.exports = Widget

View file

@ -0,0 +1,299 @@
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', 'editing']
class Clone extends Container() {
static description() {
return 'Widget replication with overridable properties.'
}
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`<div class="clone"></div>`})
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(e.options)
}
}, {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(options) {
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, options)
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

View file

@ -0,0 +1,248 @@
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')
class Modal extends Panel {
static description() {
return 'A toggle button that opens a popup panel. Cannot contain tabs directly.'
}
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'},
layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal'], help:''},
scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
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) {
super(options)
this.disabledProps = []
this.popup = html`
<div class="popup">
<div class="popup-wrapper">
<div class="popup-title closable"><span class="popup-label"></span><span class="closer">${raw(icon('times'))}</span></div>
<div class="popup-content widget panel-container not-editable contains-widgets"></div>
</div>
</div>
`
this.container.appendChild(this.popup)
this.popupContent = DOM.get(this.popup, '.popup-content')[0]
// 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`<div class="toggle"></div>`)
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
e.detail.preventOriginalEvent = true
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
this.labelChange = true
this.popupContent.classList.add('layout-' + this.getProp('layout'))
this.popupContent.style.setProperty('--widget-padding', this.getProp('padding') != 'auto' ? parseFloat(this.getProp('padding')) + 'rem' : '')
}
setValue(v, options={}) {
if (this.init === undefined) return
this.value = v ? 1 : 0
if (!this.init && this.value) {
this.popupContent.appendChild(this.widget)
this.init = true
}
if (this.value && this.labelChange) {
this.updatePopupLabel()
}
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.init) this.fixParents()
if (this.value) {
resize.check(this.widget, true)
}
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 && parent.getProp('type') !== 'modal') {
// 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' : ''
}
updatePopupLabel() {
if (!this.popup) return
var label = this.getProp('popupLabel') ? iconify(this.getProp('popupLabel')) : this.label.innerHTML
DOM.get(this.popup, '.popup-title .popup-label')[0].innerHTML = label
this.labelChange = false
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'popupLabel':
case 'label':
if (this.value) {
this.updatePopupLabel()
} else {
this.labelChange = true
}
return
}
}
setContainerStyles(styles = ['geometry', 'label', 'css', 'color', 'visibility']) {
super.setContainerStyles(styles)
if (styles.includes('color') && this.popupContent) {
this.popupContent.style.setProperty('--widget-padding', this.getProp('padding') != 'auto' ? parseFloat(this.getProp('padding')) + 'rem' : '')
}
}
}
Modal.dynamicProps = Modal.prototype.constructor.dynamicProps.concat(
'popupLabel'
)
module.exports = Modal

View file

@ -0,0 +1,268 @@
var Container = require('../common/container'),
widgetManager = require('../../managers/widgets'),
parser = require('../../parser'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
{enableTraversingGestures, disableTraversingGestures} = require('../../events/drag'),
setScrollbarColor = require('../../ui/scrollbar-color')
class Panel extends Container() {
static description() {
return 'Widgets or Tabs container.'
}
static defaults() {
return super.defaults({
_panel:'panel',
scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal'], help:''},
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: '@{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 widgeted tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
super({...options, html: html`<div class="panel"></div>`})
if (this.getProp('scroll') === false) this.container.classList.add('noscroll')
this.container.classList.add('layout-' + this.getProp('layout'))
if (this.getProp('tabs') && this.getProp('tabs').length) {
this.container.classList.add('contains-tabs')
} else {
this.container.classList.add('contains-widgets')
}
this.value = -1
this.tabs = []
if (this.getProp('tabs') && this.getProp('tabs').length) {
this.navigation = this.widget.appendChild(html`<div class="navigation"></div>`)
this.children = options.children || new Array(this.getProp('tabs').length)
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
this.widget.appendChild(this.children[i].container)
this.children[i].mounted = true
this.children[i].parent = this
this.children[i].parentNode = this.widget
} else {
parser.parse({
data: this.getProp('tabs')[i],
parentNode: this.widget,
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].mounted = true
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'
)
}
if (this.getProp('traversing')) this.setTraversing()
}
createNavigation() {
this.navigation.innerHTML = ''
this.tabs = []
DOM.each(this.widget, '> .widget', (tab)=>{
let widget = widgetManager.getWidgetByElement(tab),
style = ''
style += widget.getProp('colorWidget') === 'auto' ? '' : `--color-widget:${widget.getProp('colorWidget')};`
style += widget.getProp('colorFill') === 'auto' ? '' : `--color-fill:${widget.getProp('colorFill')};`
if (!widget.getProp('visible')) style += 'display:none;'
this.tabs.push(widget)
this.navigation.appendChild(html`
<div class="tablink" data-widget="${widget.hash}" style="${style}">
${widget.label.innerHTML}
</div>
`)
})
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, 'div', (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 'traversing':
this.setTraversing()
return
case 'colorWidget':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
case 'alphaFillOff':
case 'alphaFillOn':
for (var w of this.children) {
if (w) w.onPropChanged(propName)
}
return
}
}
setContainerStyles(styles = ['geometry', 'label', 'css', 'color', 'visibility']) {
super.setContainerStyles(styles)
if (styles.includes('color') && this.getProp('scroll')) {
setScrollbarColor(this.container)
}
}
setTraversing(update) {
var traversing = this.getProp('traversing')
disableTraversingGestures(this.widget)
if (traversing) {
enableTraversingGestures(this.widget, {smart: typeof traversing === 'string' && traversing.match(/smart|auto/)})
}
}
onRemove() {
this.off('resize')
super.onRemove()
}
}
Panel.dynamicProps = Panel.prototype.constructor.dynamicProps.concat(
'variables',
'traversing'
)
module.exports = Panel

View file

@ -0,0 +1,69 @@
var Panel = require('./panel'),
Widget = require('../common/widget'),
StaticProperties = require('../mixins/static_properties'),
{icon} = require('../../ui/utils'),
html = require('nanohtml'),
raw = require('nanohtml/raw')
class Root extends StaticProperties(Panel, {scroll: false, label: false, id: 'root'}) {
static description() {
return 'Main (unique) container'
}
static defaults() {
return Widget.defaults({
_panel:'panel',
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'},
}, ['label', '_geometry', 'left', 'top', 'width', 'height', 'scroll'], {
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 widgeted tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
options.root = true
super(options)
this.widget.classList.add('root')
DOM.each(this.widget, '> .navigation', (el)=>{
el.classList.add('main')
})
}
createNavigation() {
super.createNavigation()
this.navigation.appendChild(html`
<div class="tools not-editable">${raw(icon('expand'))}></div>
<div class="tools not-editable">${raw(icon('pen'))}></div>
<div class="tools not-editable">${raw(icon('ellipsis-v'))}></div>
`)
}
}
module.exports = Root

View file

@ -0,0 +1,85 @@
var Panel = require('./panel'),
Widget = require('../common/widget'),
StaticProperties = require('../mixins/static_properties'),
resize = require('../../events/resize')
module.exports = class Tab extends StaticProperties(Panel, {scroll: true}) {
static description() {
return 'Tabbed panel widget'
}
static defaults() {
return Widget.defaults({
_tab:'tab',
detached: {type: 'boolean', value: true, help: 'Set to `false` if the tab contains `frame` widgets that should not be reloaded when the tab opens'},
layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal'], help:''},
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: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
}, ['_geometry', 'left', 'top', 'width', 'height', 'scroll'], {
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 widgeted tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
super(options)
this.container.classList.add('show')
this.detached = false
}
hide() {
if (this.detached) return
if (this.getProp('detached')) this.container.removeChild(this.widget)
this.container.classList.remove('show')
this.detached = true
}
show() {
if (!this.detached) return
if (this.getProp('detached')) 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 'visible':
case 'label':
case 'colorWidget':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
case 'alphaFillOff':
case 'alphaFillOn':
if (this.parent.createNavigation) this.parent.createNavigation()
return
}
}
}

View file

@ -0,0 +1,82 @@
var Widget = require('../common/widget'),
html = require('nanohtml'),
{urlParser} = require('../utils'),
locales = require('../../locales'),
StaticProperties = require('../mixins/static_properties')
class Frame extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Embed a page in a frame (local network only).'
}
static defaults() {
return super.defaults({
_frame: 'frame',
border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
}, ['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`
<inner>
<iframe class="frame" src="" sandbox="allow-scripts"></iframe>
</inner>`
})
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, '.frame')[0]
this.errorText = html`<span>${locales('iframe_unauthorized')}<span>`
this.errorTextMounted = false
}
setValue(v, options={}) {
this.value = v
var parser = urlParser(this.value)
if (this.value && parser.isLocal()) {
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

View file

@ -0,0 +1,82 @@
var Widget = require('../common/widget'),
morph = require('nanomorph'),
html = require('nanohtml'),
sanitizeHtml = require('sanitize-html'),
StaticProperties = require('../mixins/static_properties')
var sanitizeOptions = {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']).filter(x=>x!=='iframe')
}
class Html extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Simple HTML parser.'
}
static defaults() {
return super.defaults({
_html:'html',
html: {type: 'string', value: '', help: [
'Allowed HTML tags:',
'&nbsp;&nbsp;h1-6, blockquote, p, a, ul, ol, nl, li,',
'&nbsp;&nbsp;b, i, strong, em, strike, code, hr, br, div,',
'&nbsp;&nbsp;table, thead, img, caption, tbody, tr, th, td, pre'
]},
border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
}, ['precision', 'bypass'], {})
}
constructor(options) {
super({...options, html: html`
<inner>
<div class="frame"></div>
</inner>
`})
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, '.frame')[0]
}
updateHtml(){
var newHtml = this.frame.cloneNode(false)
newHtml.innerHTML = sanitizeHtml(this.getProp('html'), sanitizeOptions)
morph(this.frame, newHtml)
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'html':
this.updateHtml()
return
}
}
}
Html.dynamicProps = Html.prototype.constructor.dynamicProps.concat(
'html'
)
module.exports = Html

View file

@ -0,0 +1,105 @@
var Widget = require('../common/widget'),
ipc = require('../../ipc'),
html = require('nanohtml'),
{urlParser} = require('../utils'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Load a image (url or base64-encoded).'
}
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-repeat', 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'
]}
}, ['precision', 'bypass'], {
value: {type: 'string', value: '', help: [
'- File `url` or `path` (relative to the session file location by default, falling back to absolute path)',
'- Base64 encoded image : `data:image/...`'
]}
})
}
constructor(options) {
super({...options, html: html`
<inner>
<div class="frame"></div>
</inner>
`})
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, '.frame')[0]
this.frame.style.setProperty('background-size', this.getProp('size'))
this.frame.style.setProperty('background-position', this.getProp('position'))
this.frame.style.setProperty('background-repeat', this.getProp('repeat'))
}
setValue(v, options={}) {
var s = v==null ? '' : '' + v,
cache_query = ''
if (!s.length) {
this.value = this.getProp('default')
} else if (s != 'reload') {
if (s.length > 1) this.value = s
}
if (typeof this.value === 'string' && this.value.length) {
if ((s === 'reload' || !this.getProp('cache')) && this.value.indexOf('base64') === -1) {
cache_query = (this.value.indexOf('?') != -1 ? '&' : '?') + Date.now()
}
}
var url = this.value,
parser = urlParser(url)
// escpape windows absolute file paths
if (!parser.protocol.match(/http|data/)) url = url.replace(':', '_:_')
url = url.replace(/\\/g, '\\\\')
if (url) {
this.frame.style.setProperty('background-image', `url("${url}${cache_query}")`)
} else {
this.frame.style.setProperty('background-image', '')
}
if (options.sync) this.changed(options)
}
onRemove() {
super.onRemove()
}
}

View file

@ -0,0 +1,110 @@
var Widget = require('../common/widget'),
morph = require('nanomorph'),
html = require('nanohtml'),
StaticProperties = require('../mixins/static_properties')
class Svg extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Svg parser.'
}
static defaults() {
return super.defaults({
_svg:'svg',
svg: {type: 'string', value: '', help: [
'Svg xml definition:',
'- will be wrapped in a `< svg />` element',
'- `<path>` commands support a special percent notation (`%x` and `%y`)'
]},
border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
}, ['precision', 'bypass'], {})
}
constructor(options) {
super({...options, html: html`
<inner>
<svg class="frame"></svg>
</inner>
`})
this.frame = DOM.get(this.widget, '.frame')[0]
this.height = undefined
this.width = undefined
this.on('resize', this.resizeHandleProxy.bind(this), {element: this.widget})
if (!this.getProp('border')) this.container.classList.add('noborder')
}
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 node = this.frame.cloneNode(false)
node.innerHTML = svg
morph(this.frame, 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

View file

@ -0,0 +1,246 @@
var {clip} = require('../utils'),
Plot = require('./plot')
module.exports = class Eq extends Plot {
static description() {
return 'Draws frequency response between from from an array of filter objects.'
}
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|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (base 10). Set to a `number` to define the logarithm\'s base.'},
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`)'},
}, ['precision', 'bypass'], {
value: {type: 'array', value: '', help: [
'Each item must be an object with the following properties',
'- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak" or "notch")',
'- `freq`: number (filter\'s resonant frequency)',
'- `q`: number (Q factor)',
'- `gain`: number',
'- `on`: boolean',
]}
})
}
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 = calcBiquad({type:'peak',freq:1,gain:0,q:1},!this.getProp('logScaleX'), this.resolution)
} else {
filterResponse = calcBiquad(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)
}
}
}
//
// calcBiquad
//
// Dec 14, 2010 njr
// original @ Nigel Redmon
function calcBiquad(options,linear,resolution) {
var {type, freq, q, gain} = options,
Fs = 44100,
a0,a1,a2,b1,b2,norm,
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':
norm = 1 / (1 + K / q + K * K)
a0 = K * K * norm
a1 = 2 * a0
a2 = a0
b1 = 2 * (K * K - 1) * norm
b2 = (1 - K / q + K * K) * norm
break
case 'highpass':
norm = 1 / (1 + K / q + K * K)
a0 = 1 * norm
a1 = -2 * a0
a2 = a0
b1 = 2 * (K * K - 1) * norm
b2 = (1 - K / q + K * K) * norm
break
case 'bandpass':
norm = 1 / (1 + K / q + K * K)
a0 = K / q * norm
a1 = 0
a2 = -a0
b1 = 2 * (K * K - 1) * norm
b2 = (1 - K / q + K * K) * norm
break
case 'notch':
norm = 1 / (1 + K / q + K * K)
a0 = (1 + K * K) * norm
a1 = 2 * (K * K - 1) * norm
a2 = a0
b1 = a1
b2 = (1 - K / q + K * K) * norm
break
case 'peak':
if (gain >= 0) {
norm = 1 / (1 + 1/q * K + K * K)
a0 = (1 + V/q * K + K * K) * norm
a1 = 2 * (K * K - 1) * norm
a2 = (1 - V/q * K + K * K) * norm
b1 = a1
b2 = (1 - 1/q * K + K * K) * norm
}
else {
norm = 1 / (1 + V/q * K + K * K)
a0 = (1 + 1/q * K + K * K) * norm
a1 = 2 * (K * K - 1) * norm
a2 = (1 - 1/q * K + K * K) * norm
b1 = a1
b2 = (1 - V/q * K + K * K) * norm
}
break
case 'lowshelf':
if (gain >= 0) {
norm = 1 / (1 + Math.SQRT2 * K + K * K)
a0 = (1 + Math.sqrt(2*V) * K + V * K * K) * norm
a1 = 2 * (V * K * K - 1) * norm
a2 = (1 - Math.sqrt(2*V) * K + V * K * K) * norm
b1 = 2 * (K * K - 1) * norm
b2 = (1 - Math.SQRT2 * K + K * K) * norm
}
else {
norm = 1 / (1 + Math.sqrt(2*V) * K + V * K * K)
a0 = (1 + Math.SQRT2 * K + K * K) * norm
a1 = 2 * (K * K - 1) * norm
a2 = (1 - Math.SQRT2 * K + K * K) * norm
b1 = 2 * (V * K * K - 1) * norm
b2 = (1 - Math.sqrt(2*V) * K + V * K * K) * norm
}
break
case 'highshelf':
if (gain >= 0) {
norm = 1 / (1 + Math.SQRT2 * K + K * K)
a0 = (V + Math.sqrt(2*V) * K + K * K) * norm
a1 = 2 * (K * K - V) * norm
a2 = (V - Math.sqrt(2*V) * K + K * K) * norm
b1 = 2 * (K * K - 1) * norm
b2 = (1 - Math.SQRT2 * K + K * K) * norm
}
else {
norm = 1 / (V + Math.sqrt(2*V) * K + K * K)
a0 = (1 + Math.SQRT2 * K + K * K) * norm
a1 = 2 * (K * K - 1) * norm
a2 = (1 - Math.SQRT2 * K + K * K) * norm
b1 = 2 * (K * K - V) * norm
b2 = (V - Math.sqrt(2*V) * K + K * K) * norm
}
break
}
var magPlot = []
for (var i = 0; i < len; i++) {
var w, phi, y
if (linear)
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
phi = Math.pow(Math.sin(w/2), 2)
y = Math.log(Math.pow(a0+a1+a2, 2) - 4*(a0*a1 + 4*a0*a2 + a1*a2)*phi + 16*a0*a2*phi*phi) - Math.log(Math.pow(1+b1+b2, 2) - 4*(b1 + 4*b2 + b1*b2)*phi + 16*b2*phi*phi)
y = y * 10 / Math.LN10
if (y == -Infinity) y = -200
if (linear)
magPlot.push([i / (len - 1) * Fs / 2, y])
else
magPlot.push([i / (len - 1) * Fs / 2, y])
if (i == 0)
minVal = maxVal = y
else if (y < minVal)
minVal = y
else if (y > maxVal)
maxVal = y
}
return magPlot
}

View file

@ -0,0 +1,246 @@
var {mapToScale} = require('../utils'),
Canvas = require('../common/canvas'),
html = require('nanohtml'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Plot extends StaticProperties(Canvas, {bypass: true}) {
static description() {
return 'XY coordinates plot.'
}
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|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (base 10). Set to a `number` to define the logarithm\'s base.'},
logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
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'},
}, ['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) {
super({...options, html: html`
<inner>
<canvas></canvas>
</inner>
`})
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
}
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.textFade
var margin = this.cssVars.padding
if (margin < this.fontSize * 1.5) return
if (this.pips.x) {
this.ctx.textAlign = 'center'
this.ctx.fillText(this.pips.x.min, margin, this.height - margin / 2)
this.ctx.fillText(this.pips.x.max, this.width - margin, this.height - margin / 2)
}
if (this.pips.y) {
this.ctx.textAlign = 'right'
this.ctx.fillText(this.pips.y.min, margin / 2 + this.fontSize / 2, this.height - margin)
this.ctx.fillText(this.pips.y.max, margin / 2 + this.fontSize / 2, margin)
}
}
draw_line() {
var points = [],
padding = this.cssVars.padding + PXSCALE,
x, y
for (let i in this.value) {
if (this.value[i].length) {
points.push(mapToScale(this.value[i][0], [this.rangeX.min, this.rangeX.max], [padding, this.width - padding], 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 {
let nx = mapToScale(i, [0, this.value.length - 1], [padding, this.width - padding], 0, this.logScaleX, true),
ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], 0, this. logScaleY, true)
if (x !== nx || y !== ny) {
points.push(nx)
points.push(ny)
x = nx
y = ny
}
}
}
if (points.length < 4) return points
this.ctx.beginPath()
if (this.getProp('smooth')) {
this.ctx.curve(points, this.smooth, Math.round(this.width/(points.length/2 - 1)))
} else {
this.ctx.moveTo(points[0], points[1])
let i
for (i = 2; i < points.length - 2; i += 2) {
this.ctx.lineTo(points[i], points[i + 1])
}
this.ctx.lineTo(points[i], points[i + 1])
}
this.ctx.globalAlpha = 1
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.strokeStyle = this.cssVars.colorWidget
this.ctx.stroke()
if (this.getProp('origin') !== false) {
var origin = mapToScale(this.getProp('origin'), [this.rangeY.min, this.rangeY.max], [this.height - padding, padding], 0, this.getProp('logScaleY'), true)
this.ctx.globalAlpha = this.cssVars.alphaFillOn
this.ctx.fillStyle = this.cssVars.colorFill
this.ctx.lineTo(this.width - padding, origin)
this.ctx.lineTo(padding, origin)
this.ctx.closePath()
this.ctx.fill()
}
return points
}
draw_dots(points) {
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.cssVars.colorWidget
this.ctx.strokeStyle = this.cssVars.colorForeground
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') !== false ? 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)
}
}
}

View file

@ -0,0 +1,122 @@
var {clip} = require('../utils'),
Widget = require('../common/widget'),
Plot = require('./plot'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dots: false, smooth: false}) {
static description() {
return 'Display its value over time.'
}
static defaults() {
return Widget.defaults({
_visualizer:'visualizer',
duration: {type: 'number', value: 1, help: 'Defines visualization duration in seconds'},
rangeY: {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'},
logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
}, ['precision', 'bypass'], {})
}
constructor(options) {
super(options)
this.fps = CANVAS_FRAMERATE
this.length = Math.round(clip(this.fps * this.getProp('duration'), [8, 4096]))
this.value = new Array(this.length).fill(this.rangeY.min)
this.cancel = false
this.looping = false
this.clock = 0
this.lastUpdate = 0
this.watchDuration = 1000 * this.getProp('duration')
this.ticks = 0
}
startLoop() {
this.clock = Date.now()
if (!this.looping) {
this.lastUpdate = Date.now()
this.looping = true
this.ticks = 0
this.loop()
}
}
loop() {
var t = Date.now()
if (t -this.clock >= this.watchDuration) {
this.looping = false
}
this.ticks += (t - this.lastUpdate) / (1000/this.fps)
if (Math.floor(this.ticks) > 0) {
this.shiftData(Math.floor(this.ticks))
this.ticks -= Math.floor(this.ticks)
this.batchDraw()
}
this.lastUpdate = t
if (!this.looping) return
setTimeout(()=>{
this.loop()
}, (1000/this.fps))
}
shiftData(n) {
for (var i=0; i<n; i++) {
this.value.push(this.value[this.length - 1])
this.value.splice(0,1)
}
}
getValue() {
return this.value[this.length - 1]
}
setValue(v, options={}) {
if (Array.isArray(v) && v.length == this.length) {
this.value = v
this.startLoop()
if (options.sync) this.changed(options)
} else if (typeof(v) == 'number'){
this.value[this.length - 1] = v
this.startLoop()
if (options.sync) this.changed(options)
}
}
}

View file

@ -0,0 +1,81 @@
module.exports.widgets = {
// tabs
tab: require('./containers/tab'),
root: require('./containers/root'),
// sliders
fader: require('./sliders/fader'),
knob: require('./sliders/knob'),
encoder: require('./sliders/encoder'),
range: require('./sliders/range'),
// buttons
toggle: require('./buttons/toggle'),
switch: require('./buttons/switch'),
dropdown: require('./buttons/dropdown'), // redo as menu derivate ?
menu: require('./buttons/menu'), // redo using canvas
// pads
xy: require('./pads/xy'),
rgb: require('./pads/rgb'),
multixy: require('./pads/multixy'),
canvas: require('./pads/canvas'), // implement...
// matrices
matrix: require('./matrices/matrix'),
keyboard: require('./matrices/keyboard'),
patchbay: require('./matrices/patchbay').PatchBay,
patchbaynode: require('./matrices/patchbay').PatchBayNode,
// indicators
led: require('./indicators/led'),
text: require('./indicators/text'),
// graphs
plot: require('./graphs/plot'),
eq: require('./graphs/eq'),
visualizer: require('./graphs/visualizer'),
// frames
image: require('./frames/image'),
svg: require('./frames/svg'),
html: require('./frames/html'),
frame: require('./frames/frame'),
// containers
panel: require('./containers/panel'),
modal: require('./containers/modal'),
clone: require('./containers/clone'),
// state switchers
switcher: require('./switchers/switcher'),
crossfader: require('./switchers/crossfader'),
state: require('./switchers/state'),
// inputs
input: require('./inputs/input'),
keys: require('./inputs/keys'),
script: require('./inputs/script'),
gyroscope: require('./inputs/gyroscope'),
file: require('./inputs/file'),
}
module.exports.categories = {
'Buttons':['toggle', 'switch', 'dropdown', 'menu'],
'Containers':['panel', 'modal', 'clone'],
'Frames':['frame', 'svg', 'html', 'image'],
'Graphs':['plot','eq','visualizer'],
'Indicators':['led', 'text'],
'Inputs':['input', 'keys', 'script', 'gyroscope', 'file'],
'Matrices':['matrix', 'keyboard', 'patchbay'],
'Pads':['xy','rgb','multixy', 'canvas'],
'Sliders':['fader','knob', 'encoder', 'range'],
'Switchers':['state', 'switcher','crossfader'],
}
var defaults = {}
for (var k in module.exports.widgets) {
defaults[k] = module.exports.widgets[k].defaults()
}
module.exports.defaults = defaults

View file

@ -0,0 +1,102 @@
var {mapToScale, clip} = require('../utils'),
Widget = require('../common/widget'),
html = require('nanohtml'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Led extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Intensity display.'
}
static defaults() {
return super.defaults({
_led:'led',
mode: {type: 'string', value: 'intensity', choices: ['intensity', 'color'], help: [
''
]},
range: {type: 'object', value: {min:0,max:1}, help: 'Value to led intensity mapping range'},
logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale (base 10). Set to a `number` to define the logarithm\'s base.'},
borderRadius: {type: 'string', value: '', help: 'Css border-radius property.'},
}, ['precision', 'bypass'], {
value: {type: 'number|array|string', value: '', help: [
'- `Number`: if `mode` is set to `intensity`',
'- `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) {
super({...options, html: html`<inner></inner>`})
this.setValueIntensity(this.getProp('mode') === 'intensity' ? this.getProp('range').min : 1)
var bR = this.getProp('borderRadius')
if (parseInt(bR) == bR) bR += 'rem'
this.container.style.setProperty('--border-radius', bR)
}
setValue(v, options={}) {
var ret = this.getProp('mode') === 'intensity' ? this.setValueIntensity(v) : this.setValueColor(v)
if (options.sync && ret !== false) this.changed(options)
}
setValueIntensity(v) {
if (typeof v != 'number') return false
this.value = v
this.container.style.setProperty('--opacity', mapToScale(v,[this.getProp('range').min,this.getProp('range').max],[0,1],false,this.getProp('logScale'),true))
}
setValueColor(v) {
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 false
}
this.value = v
this.container .style.setProperty('--color-led', c)
}
}

View file

@ -0,0 +1,71 @@
var {iconify} = require('../../ui/utils'),
Widget = require('../common/widget'),
html = require('nanohtml'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Text extends StaticProperties(Widget, {bypass: true}) {
static description() {
return 'Display text.'
}
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: 'center', choices: ['center', 'left', 'right'], help: 'Css text-align property.'},
}, ['precision', 'bypass'], {})
}
constructor(options) {
super({...options, html: html`<inner></inner>`})
this.text = this.widget.appendChild(html`<div></div>`)
if (this.getProp('vertical')) this.text.classList.add('vertical')
if (this.getProp('align') === 'left') this.text.classList.add('left')
if (this.getProp('align') === 'right') this.text.classList.add('right')
if (this.getProp('wrap')) this.text.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
var s = String(this.value)
if (s.indexOf('^') > -1) {
this.text.innerHTML = iconify(s.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g,'<br/>'))
} else {
this.text.textContent = s.replace(/\n/g,'\r\n')
}
if (options.sync) this.changed(options)
}
}

View file

@ -0,0 +1,80 @@
var Widget = require('../common/widget'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
{remoteBrowse, icon} = require('../../ui/utils')
module.exports = class File extends Widget {
static description() {
return 'File/Folder selector (server-side).'
}
static defaults() {
return super.defaults({
_input:'input',
directory: {type: 'string', value: 'auto', help: 'Default browsing directory'},
extension: {type: 'string', value: '*', help: 'Only display files with this extension'},
hidePath: {type: 'boolean', value: false, help: 'Set to `true` to only display the filename (the whole path will still be used as value)'},
allowDir: {type: 'boolean', value: false, help: 'Allow selecting a folder (by pressing "open" when no file is selected)'}
})
}
constructor(options) {
super({...options, html: html`
<div class="file btn">${raw(icon('folder-open'))}<span></span></div>
`})
this.text = DOM.get(this.widget, 'span')[0]
this.widget.addEventListener('fast-click', (e)=>{
if (e.capturedByEditor === true) return
remoteBrowse({
extension: this.getProp('extension').replace(/^\.?(.*)$/, '$1'),
directory: this.getProp('directory') === 'auto' ? undefined : this.getProp('directory'),
loadDir: this.getProp('allowDir')
}, (path)=>{
this.setValue(path.join(path[0][0] === '/' ? '/' : '\\'), {
sync: true,
send: true
})
})
})
}
setValue(v, options={}) {
this.value = v
var sep = v[0] === '/' ? '/' : '\\'
if (this.getProp('hidePath')) {
if (v[v.length - 1] === sep) {
this.text.textContent = v.substr(0, v.length - 1).split(sep).pop() + sep
} else {
this.text.textContent = v.split(sep).pop()
}
} else {
this.text.textContent = v
}
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}

View file

@ -0,0 +1,125 @@
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 description() {
return 'Device motion/orientation sensor.'
}
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`
<div class="gyroscope">
${raw(icon('compass'))}
</div>
`})
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

View file

@ -0,0 +1,168 @@
var Canvas = require('../common/canvas'),
{deepCopy} = require('../../utils'),
html = require('nanohtml')
module.exports = class Input extends Canvas {
static description() {
return 'Text input.'
}
static defaults() {
return super.defaults({
_input:'input',
align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], 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'},
asYouType: {type: 'boolean', value: false, help: 'Set to `true` to make the input send its value at each keystroke'}
})
}
constructor(options) {
super({...options, html: html`
<inner>
<canvas></canvas>
</inner>
`})
this.value = ''
this.stringValue = ''
this.focused = false
this.tabKeyBlur = 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`<input class="no-keybinding"></input>`
this.input.addEventListener('blur', (e)=>{
this.blur(this.tabKeyBlur)
this.tabKeyBlur = false
})
var asYouType = this.getProp('asYouType')
this.input.addEventListener('keydown', (e)=>{
if (e.keyCode === 13) this.blur() // enter
else if (e.keyCode === 27) this.blur(false) // esc
else if (e.keyCode === 9) this.tabKeyBlur = true // tab
else if (asYouType) {
setTimeout(()=>{
this.inputChange()
})
}
})
} 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()
this.input.setSelectionRange(0, this.input.value.length)
}
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.width,
height = this.height
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
}
}

View file

@ -0,0 +1,157 @@
var Widget = require('../common/widget'),
{icon} = require('../../ui/utils'),
keyboardJS = require('keyboardjs'),
html = require('nanohtml'),
raw = require('nanohtml/raw')
class Keys extends Widget {
static description() {
return 'Keyboard binding.'
}
static defaults() {
return super.defaults({
_keys:'keys',
binding: {type: 'string|array', value: '', help: 'Key combo `string` or `array` of strings (see <a href="https://github.com/RobertWHurst/KeyboardJS">KeyboardJS</a> documentation)'},
keydown: {type: 'string', value: '', help: [
'This property is evaluated each time the key combo is pressed and defines the widget\'s own value. Formulas are given extras variables in this context:',
'- `key`: pressed key name (usefull for handling multiple keys with a single keys widget, lowercased when referencing a character key)',
'- `code`: pressed key code name (<a href="https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code#Code_values">full list</a>)',
'- `ctrl`: control key state',
'- `alt`: alt key state',
'- `shift`: shift key state',
'- `meta`: 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: null})
if (this.getProp('binding')) {
this.keyDownHandler = this.keyDown.bind(this)
this.keyUpHandler = this.keyUp.bind(this)
keyboardJS.withContext('global', ()=>{
keyboardJS.bind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
})
}
}
onRemove() {
super.onRemove()
if (this.getProp('binding')) {
keyboardJS.withContext('global', ()=>{
keyboardJS.unbind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
})
}
}
keyDown(e) {
if (e.target && (e.target.tagName === 'INPUT' || e.target.tabName === 'TEXTAREA' || e.target.tabName === 'SELECT')) return
if (!this.getProp('repeat') && e) e.preventRepeat()
e.preventDefault()
if (this.getProp('keydown') !== '') {
var context = {
key: e.key,
code: e.code,
ctrl: e.ctrlKey,
shift: e.shiftKey,
alt: e.altKey,
meta: e.metaKey
}
if (context.key.length === 1) {
context.key = context.key.toLowerCase()
}
this.setValue(this.resolveProp('keydown', undefined, false, false, false, context), {sync: true, send: true})
}
}
keyUp(e) {
if (e.target && e.target.classList.contains('no-keybinding')) return
e.preventDefault()
if (this.getProp('keyup') !== '') {
var context = {
key: e.key,
code: e.code,
ctrl: e.ctrlKey,
shift: e.shiftKey,
alt: e.altKey,
meta: e.metaKey
}
if (context.key.length === 1) {
context.key = context.key.toLowerCase()
}
this.setValue(this.resolveProp('keyup', undefined, false, false, false, context), {sync: true, send: true})
}
}
setValue(v, options = {}) {
this.value = v
// if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}
Keys.parsersContexts.keydown = Keys.parsersContexts.keyup = {
key: 'x',
code: 'x',
ctrl: false,
alt: false,
shift: false,
meta: false
}
Keys.dynamicProps = Keys.prototype.constructor.dynamicProps.concat(
'keydown',
'keyup',
'repeat'
)
module.exports = Keys

View file

@ -0,0 +1,179 @@
var Widget = require('../common/widget'),
widgetManager = require('../../managers/widgets'),
{icon} = require('../../ui/utils'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
{urlParser} = require('../utils')
class Script extends Widget {
static description() {
return 'Evaluates a script each time it receives a value.'
}
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`: value received by the widget',
'- `id`: id of the widget that triggered the script',
'- `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',
'- `get(id)`: function for getting a widget\'s value (dynamic equivalent of @{id})',
'- `getProp(id, property)`: function for getting a widget\'s property value ((dynamic equivalent of @{id.property})',
'- `httpGet(url, callback)`: function for making http requests (asynchronous "GET" request and local urls only)',
'',
'* Note: `value` or `linkId` properties can be used to receive other widgets\' values. The `value` property must actually change to trigger the execution, where linked widgets via `linkId` can submit the same value over and over and trigger the execution',
]}
})
}
constructor(options) {
super({...options, html: html`
<div class="script">
${raw(icon('code'))}
</div>
`})
this.scriptLock = false
}
static scriptSet(id, value, options) {
if (id == options.id) options.sync = false
var widgets = widgetManager.getWidgetById(id)
for (var i = widgets.length - 1; i >= 0; i--) {
return widgets[i].setValue(value, options)
}
}
static scriptGet(id) {
var widgets = widgetManager.getWidgetById(id)
for (var i = widgets.length - 1; i >= 0; i--) {
if (widgets[i].getValue) {
var v = widgets[i].getValue()
if (v !== undefined) return v
}
}
}
static scriptGetProp(id, prop) {
var widgets = widgetManager.getWidgetById(id)
for (var i = widgets.length - 1; i >= 0; i--) {
var v = widgets[i].getProp(prop)
if (v !== undefined) return v
}
}
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={} ) {
if (this.scriptLock) return
var context = {
value: v,
id: options.id,
send: options.send ? this.scriptSend.bind(this) : ()=>{},
set: (id, value)=>{Script.scriptSet(id, value, options)},
get: (id)=>{return Script.scriptGet(id)},
getProp: (id, prop)=>{return Script.scriptGetProp(id, prop)},
httpGet: (url, callback)=>{
var parser = urlParser(url),
err = (e)=>{console.error(e)}
if (!parser.isLocal()) return err('httpGet error (' + url + '): non-local url')
var xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = (e)=>{
if (xhr.readyState === 4 && xhr.status === 200 && callback) {
callback(xhr.responseText)
}
}
xhr.onerror = (e)=>err('httpGet error (' + url + '): ' + xhr.statusText)
xhr.send(null)
}
}
var condition = this.resolveProp('condition', undefined, false, false, false, {value: v})
if (condition) {
this.scriptLock = true
this.resolveProp('script', undefined, false, false, false, context)
this.scriptLock = false
}
// if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}
Script.parsersContexts.condition = {
value: ''
}
Script.parsersContexts.script = {
value: '',
id: '',
send: ()=>{},
set: ()=>{},
get: ()=>{},
getProp: ()=>{},
httpGet: ()=>{}
}
Script.dynamicProps = Script.prototype.constructor.dynamicProps.concat(
'condition',
'script'
)
module.exports = Script

View file

@ -0,0 +1,34 @@
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`<div class="matrix"></div>`})
this.value = []
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
}
}
}

View file

@ -0,0 +1,129 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
module.exports = class Keyboard extends _matrix_base {
static description() {
return 'Piano keyboard.'
}
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)'
]},
toggles: {type: 'boolean', value: false, help: 'Set to `true` to make keys bahave like toggle buttons'}
}, ['_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)
this.on('change',(e)=>{
if (e.widget === this) return
this.value[e.widget._index] = e.widget.getValue()
this.changed(e.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 = this.getProp('toggles') ? 'toggle' : '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')
}
}
}

View file

@ -0,0 +1,187 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser'),
{deepCopy} = require('../../utils')
class Matrix extends _matrix_base {
static description() {
return 'Generic matrix for creating rows/columns of widgets.'
}
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: `$`',
'Note: by default, the widgets inherit from the matrix\' `id` and osc properties (`id` and `address` are appended with `/$`)'
]}
}, [], {})
}
constructor(options) {
super(options)
this.on('change',(e)=>{
if (e.widget === this) return
if (this.getProp('widgetType') === 'clone') {
if (e.widget.parent.parent !== this) return
this.value[e.widget.parent._index] = e.widget.getValue()
} else {
if (e.widget.parent !== this) return
this.value[e.widget._index] = e.widget.getValue()
}
this.changed(e.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')
this.start = parseInt(this.getProp('start'))
if (parser.widgets[this.getProp('widgetType')]) {
for (let i = 0; i < this.getProp('matrix')[0] * this.getProp('matrix')[1]; i++) {
var props = this.resolveProp('props', undefined, false, false, false, {'$':i + this.start})
var data = this.defaultProps(i + this.start)
if (typeof props === 'object' && props !== null) {
Object.assign(data, props)
}
var widget = parser.parse({
data: data,
parentNode: this.widget,
parent: this
})
widget._index = i
widget.container.classList.add('not-editable')
this.value[i] = widget.getValue()
}
} else {
this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
}
}
defaultProps(i) {
return {
type: this.getProp('widgetType'),
id: '@{parent.id}/' + i,
address: '@{parent.address}/' + i,
preArgs: '@{parent.preArgs}',
target: '@{parent.target}',
precision: '@{parent.precision}',
bypass: '@{parent.bypass}',
label: i,
top: 'auto',
left: 'auto',
height: 'auto',
width: 'auto'
}
}
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 + this.start})
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
data = {}
}
if (typeof oldPropValue === 'object' && oldPropValue !== null) {
// if an overridden default props is removed, set it back to default
let overriddenDefaults,
widgetDefaults
for (var k in oldPropValue) {
if (data[k] === undefined) {
if (Matrix.overriddenDefaults.indexOf(k) !== -1) {
overriddenDefaults = overriddenDefaults || this.defaultProps(i + this.start)
data[k] = overriddenDefaults[k]
} else {
widgetDefaults = widgetDefaults || parser.defaults[data.type || this.getProp('widgetType')]
data[k] = deepCopy(widgetDefaults[k])
}
}
}
}
Object.assign(this.children[i].props, data)
this.children[i].updateProps(Object.keys(data), this, options)
// this.children[i] might have been recreated
this.children[i].container.classList.add('not-editable')
}
return
}
}
}
Matrix.overriddenDefaults = [
'type', 'id', 'address', 'preArgs', 'target', 'precision', 'bypass',
'label', 'top', 'left', 'height', 'width'
]
Matrix.parsersContexts.props = {
$: 0
}
Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
'props'
)
module.exports = Matrix

View file

@ -0,0 +1,324 @@
var Widget = require('../common/widget'),
Canvas = require('../common/canvas'),
Container = require('../common/container'),
parser = require('../../parser'),
html = require('nanohtml')
class PatchBayNode extends Widget {
constructor(options) {
super({...options, html: html`
<div class="node">
</div>
`})
this.value = []
}
setValue(v, options={} ) {
this.value = Array.isArray(v) ? v : v ? [v] : []
var allowed = this.parent.getProp('outputs')
for (var i = this.value.length -1; i > -1; i--) {
if (allowed.indexOf(this.value[i]) === -1) {
this.value.splice(i, 1)
}
}
this.parent.batchDraw()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
toggleValue(v) {
var index = this.value.indexOf(v)
if (index > -1) {
this.value.splice(index, 1)
} else {
this.value.push(v)
}
this.setValue(this.value, {sync: true, send: true})
}
}
class PatchBay extends Container(Canvas) {
static description() {
return 'Connect inputs to outputs.'
}
static defaults() {
return super.defaults({
_patchbay:'patchbay',
inputs: {type: 'array|object', value: ['input_1', 'input_2'], help: [
'- `Array` of input names : `[\'input_1\', \'input_2\']`',
'- `Object` of `"label_1": "input_1"` 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',
'',
'Patchbay inputs can be connected to one or more outputs and will send messages of the following form when they are connected/disconnected: ',
'`/patchbay_address input_x output_x output_y etc`',
'If no output is connected to the input, the message will be `/patchbay_address input_x`',
'The inputs values can be consumed with the property inheritance syntax: `@{patchbay_id/input_1}` returns an array of output names connected to `input_1`'
]},
outputs: {type: 'array|object', value: ['output_1', 'output_2'], help: 'List of output values the inputs can connect to (see `inputs`).'},
}, [], {
css: {type: 'string', value: '', help: [
'The inputs/ouputs width can be adjusted by using the `.nodes` selector:',
'`.nodes { width: 25% }`',
]}
})
}
static normalizeArrayObject(obj) {
if (typeof obj !== 'object' || obj === null) {
return PatchBay.normalizeArrayObject([obj])
} else if (Array.isArray(obj)) {
var ret = {},
k, i
for (i = 0; i < obj.length; i++) {
k = typeof obj[i] === 'string' ? obj[i] : JSON.stringify(obj[i])
ret[k] = obj[i]
}
return ret
} else {
return obj
}
}
constructor(options) {
super({...options, html: html`
<div class="patchbay">
<div class="nodes inputs"></div>
<canvas></canvas>
<div class="nodes outputs"></div>
</div>
`})
this.inputs = PatchBay.normalizeArrayObject(this.getProp('inputs'))
this.outputs = PatchBay.normalizeArrayObject(this.getProp('outputs'))
this.inputsValues = Object.values(this.inputs)
this.outputsValues = Object.values(this.outputs)
this.inputsWidgets = []
this.inputNodes = []
this.outputNodes = []
for (let k in this.inputs) {
let w = parser.parse({
data: {
type: 'patchbaynode',
label: k,
id: this.getProp('id') + '/' + this.inputs[k],
address: '@{parent.address}',
target: '@{parent.target}',
preArgs: this.inputs[k],
bypass: '@{parent.bypass}',
},
parentNode: DOM.get(this.widget, '.inputs')[0],
parent: this
})
w.container.classList.add('not-editable')
this.inputsWidgets.push(w)
this.inputNodes.push(w.container)
}
var outputs = DOM.get(this.widget, '.outputs')[0]
for (let k in this.outputs) {
var node = html`
<div class="widget">
<div class="label">${k}</div>
</div>
`
outputs.appendChild(node)
this.outputNodes.push(node)
}
this.connecting = []
this.widget.addEventListener('fast-click', (e)=>{
this.toggleConnection(e.target)
e.stopPropagation()
})
this.mousePosition = []
this.on('drag', (e)=>{
if (!this.connecting.length) {
this.toggleConnection(e.target)
}
if (e.target === this.canvas) {
this.mousePosition = [e.offsetX, e.offsetY]
} else if (this.mousePosition.length) {
this.mousePosition[0] += e.movementX
this.mousePosition[1] += e.movementY
}
this.batchDraw()
}, {element: this.widget})
this.on('dragend', (e)=>{
if (this.mousePosition.length) {
this.mousePosition = []
this.toggleConnection(e.target)
}
}, {element: this.widget})
}
toggleConnection(node) {
var input = this.inputNodes.indexOf(node),
output = this.outputNodes.indexOf(node)
if (input > -1 && input !== this.connecting[0]) {
this.connecting[0] = input
} else if (output > -1 && output !== this.connecting[1]) {
this.connecting[1] = output
} else {
this.connecting = []
}
if (this.connecting[0] !== undefined && this.connecting[1] !== undefined) {
this.inputsWidgets[this.connecting[0]].toggleValue(this.outputsValues[this.connecting[1]])
this.connecting = []
} else {
this.batchDraw()
}
if (this.connecting.length) {
var cb = (e)=>{
this.toggleConnection()
document.removeEventListener('fast-click', cb)
}
document.addEventListener('fast-click', cb)
}
}
draw() {
this.clear()
var x1 = 0,
x2 = this.width,
y1, y2,
connections,
i, j
var lines = [],
strongLines = []
for (i = 0; i < this.inputsWidgets.length; i++) {
connections = this.inputsWidgets[i].getValue()
if (connections.length) {
y1 = this.height / this.inputsValues.length * (i + 0.5)
for (j = 0; j < connections.length; j++) {
if (this.outputsValues.indexOf(connections[j]) > -1) {
y2 = this.height / this.outputsValues.length * (this.outputsValues.indexOf(connections[j]) + 0.5)
var line = [[x1, y1], [this.width / 2, y1, this.width / 2, y2 ,x2, y2]]
if (this.connecting[0] === i || this.connecting[1] === this.outputsValues.indexOf(connections[j])) {
strongLines.push(line)
} else {
lines.push(line)
}
}
}
}
}
if (this.connecting.length) {
this.ctx.beginPath()
this.ctx.fillStyle = this.colors.custom
var side = this.connecting[0] !== undefined ? 0 : 1,
cx = side === 0 ? 0 : this.width,
cy = this.height / (side === 0 ? this.inputsValues : this.outputsValues).length * (this.connecting[side] + 0.5)
this.ctx.arc(cx, cy, 8 * PXSCALE, Math.PI * 2, false)
this.ctx.fill()
strongLines.push(null)
if (this.mousePosition.length) {
var [x3, y3] = this.mousePosition,
centerx = Math.abs(cx - x3) / 2,
bz1 = side ? cx - centerx : cx + centerx,
bz2 = side ? x3 + centerx : x3 - centerx
strongLines.push([[cx, cy], [bz1, cy, bz2, y3 ,x3, y3]])
}
}
this.ctx.strokeStyle = this.colors.custom
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.globalAlpha = strongLines.length ? 0.3 : 0.7
this.ctx.beginPath()
for (i in lines) {
this.ctx.moveTo(...lines[i][0])
this.ctx.bezierCurveTo(...lines[i][1])
}
this.ctx.stroke()
if (strongLines.length) {
this.ctx.globalAlpha = 0.7
this.ctx.beginPath()
for (i in strongLines) {
if (strongLines[i] === null) continue
this.ctx.moveTo(...strongLines[i][0])
this.ctx.bezierCurveTo(...strongLines[i][1])
}
this.ctx.stroke()
}
}
}
module.exports = {
PatchBay,
PatchBayNode
}

View file

@ -0,0 +1,43 @@
module.exports = (element, callback, options={})=>{
var lastTapTime = 0,
lastTapX,
lastTapY
element.addEventListener(options.click ? 'click' : 'fast-click', (event)=>{
if (event.capturedByEditor) return
var tapTime = Date.now(),
tapLength = tapTime - lastTapTime,
eventData = options.click ? event : event.detail
if (
tapLength < DOUBLE_TAP_TIME &&
Math.abs(lastTapX - eventData.pageX) < 20 &&
Math.abs(lastTapY - eventData.pageY) < 20 &&
(!options.click || event.pageX !== 0) // prevent fake click emitted with keyboard focus events
) {
// execute callback at next cycle to ensure draginit events are resolved first
setTimeout(()=>{
callback(event.detail)
}, 0)
lastTapTime = 0
// prevent touchend
if (!options.click) event.detail.preventOriginalEvent = true
} else {
lastTapTime = tapTime
lastTapX = eventData.pageX
lastTapY = eventData.pageY
}
})
}

View file

@ -0,0 +1,16 @@
let StaticProperties = (superclass, props) => class extends superclass {
createPropsCache() {
super.createPropsCache()
for (var k in props) {
this.cachedProps[k] = props[k]
}
}
}
module.exports = StaticProperties

View file

@ -0,0 +1,51 @@
module.exports = (self, options)=>{
var sendTouchState = self.getProp('touchAddress') && self.getProp('touchAddress').length
self.touched = 0
self.setValueTouchedQueue = undefined
self.on('draginit',(e)=>{
self.touched += 1
if (self.touched == 1 && sendTouchState)
self.sendValue({
address:self.getProp('touchAddress'),
v:1,
split:false
})
}, options)
self.on('dragend', (e)=>{
if (self.touched == 1) {
self.touched = 0
if (self.setValueTouchedQueue !== undefined) {
self.setValue(...self.setValueTouchedQueue)
self.setValueTouchedQueue = undefined
}
if (sendTouchState) {
self.sendValue({
address:self.getProp('touchAddress'),
v:0,
split:false
})
}
} else if (self.touched > 1){
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)
}
}

View file

@ -0,0 +1,16 @@
var Fader = require('../sliders/fader')
module.exports = class _fake_fader extends Fader {
constructor(options) {
super(options)
if (options.cancelDraw) this.batchDraw = ()=>{}
}
sendValue() {
// disabled
}
}

View file

@ -0,0 +1,172 @@
var Canvas = require('../common/canvas'),
html = require('nanohtml')
class CanvasWidget extends Canvas {
static description() {
return 'KANVA !'
}
static defaults() {
return super.defaults({
_canvas:'canvas',
valueLength: {type: 'number', value: 1, help: ' '},
multiTouch: {type: 'boolean', value: false, help: ' '},
sensitivity: {type: 'number', value: 1, help: ' '},
snap: {type: 'boolean', value: true, help: ' '},
coordsToValue: {type: 'script', value: '', help: ' '},
valueToCoords: {type: 'script', value: '', help: ' '},
draw: {type: 'script', value: '', help: ' '},
autoClear: {type: 'boolean', value: true, help: ' '},
}, [], {})
}
constructor(options) {
super({...options, html: html`
<div class="canvas">
<canvas></canvas>
</div>
`})
this.nextTouch = 0
this.value = 1
this.touchMap = {}
this.touchCoords = []
for (var i = 0; i < this.getProp('valueLength'); i++) {
this.touchCoords.push([0,0])
}
this.localContext = {}
this.on('draginit',(e)=>{
if (this.touchMap[e.pointerId] !== undefined) return
this.touchMap[e.pointerId] = this.nextTouch++
if (this.getProp('snap')) this.touchCoords[this.touchMap[e.pointerId]] = [e.offsetX, e.offsetY]
this.touchCallback(e)
}, {element: this.widget, multitouch: this.getProp('multiTouch')})
this.on('drag',(e)=>{
if (this.touchMap[e.pointerId] === undefined) return
console.log(this.touchMap[e.pointerId])
this.touchCoords[this.touchMap[e.pointerId]][0] += e.movementX / e.inertia * this.getProp('sensitivity')
this.touchCoords[this.touchMap[e.pointerId]][1] += e.movementY / e.inertia * this.getProp('sensitivity')
this.touchCallback(e)
}, {element: this.widget, multitouch: this.getProp('multiTouch')})
this.on('dragend',(e)=>{
if (this.touchMap[e.pointerId] === undefined) return
delete this.touchMap[e.pointerId]
this.nextTouch--
this.touchCallback(e)
}, {element: this.widget, multitouch: this.getProp('multiTouch')})
}
touchCallback() {
var value = this.resolveProp('coordsToValue', undefined, false, false, false, {
coords: this.touchCoords,
value: this.value,
width: this.width,
height: this.height,
local: this.localContext
})
if (value !== undefined) this.setValue(value, {send: true, sync: true, dragged: true})
}
setValue(v, options={}) {
if (v === null || v === undefined || ((v.length || 1) !== this.getProp('valueLength'))) return
this.value = v
if (!options.dragged) {
var coords = this.resolveProp('valueToCoords', undefined, false, false, false, {
coords: this.touchCoords,
value: this.value,
width: this.width,
height: this.height,
local: this.localContext
}) || this.touchCoords
this.touchCoords = coords === undefined ? this.touchCoords : coords
}
this.batchDraw()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
draw() {
if (this.getProp('autoClear')) this.clear()
this.resolveProp('draw', undefined, false, false, false, {
ctx: this.ctx,
coords: this.touchCoords,
value: this.value,
colors: this.colors,
width: this.width,
height: this.height,
})
if (this.getProp('autoClear')) this.clearRect = [0, 0, this.width, this.height]
}
}
CanvasWidget.parsersContexts.coordsToValue = CanvasWidget.parsersContexts.valueToCoords = {
coords: [[]],
value: [],
width: 100,
height: 100,
local: {}
}
CanvasWidget.parsersContexts.draw = {
value: [],
coords: [[]],
colors: {},
width: 100,
height: 100,
ctx: ()=>{}
}
CanvasWidget.dynamicProps = CanvasWidget.prototype.constructor.dynamicProps.concat([
'draw',
'sensitivity'
])
module.exports = CanvasWidget

View file

@ -0,0 +1,297 @@
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 description() {
return 'Multi-point XY 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|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (base 10). Set to a `number` to define the logarithm\'s base.'},
logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
}, [], {
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'
]},
})
}
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,
sensitivity: this.getProp('sensitivity'),
input:false
}, parent: this})
this.pads[i].canvas.classList.add('pad-' + i)
this.widget.append(this.pads[i].canvas)
}
this.value = []
this.padsCoords = []
this.touchMap = {}
touchstate(this, {element: this.widget, 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.widget, multitouch: true})
this.on('drag',(e)=>{
var i = this.touchMap[e.pointerId]
if (!i) return
this.pads[i].trigger('drag', e)
}, {element: this.widget, multitouch: true})
this.on('dragend',(e)=>{
var i = this.touchMap[e.pointerId]
if (!i) return
e.stopPropagation = true
this.pads[i].trigger('dragend', e)
delete this.touchMap[e.pointerId]
}, {element: this.widget, 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(event){
super.resizeHandle(event)
for (var k in this.pads) {
this.pads[k].width = this.width
this.pads[k].height = this.height
this.pads[k].padPadding = this.padPadding
}
this.updateHandlesPosition()
}
updateHandlesPosition() {
for (var i=0;i<this.npoints;i++) {
this.padsCoords[i] = [clip(this.pads[i].faders.x.percent,[0,100]) / 100 * (this.width - (this.pointSize * 2 + 2) * PXSCALE) + (this.pointSize + 1) * PXSCALE
,- clip(this.pads[i].faders.y.percent,[0,100]) / 100 * (this.height - (this.pointSize * 2 + 2) * PXSCALE) - (this.pointSize + 1) * PXSCALE]
}
}
draw() {
this.clear()
for (var i=0;i<this.npoints;i++) {
var margin = this.padPadding,
x = clip(this.pads[i].faders.x.percent,[0,100]) / 100 * (this.width - 2 * margin) + margin,
y = (100 - clip(this.pads[i].faders.y.percent,[0,100])) / 100 * (this.height - 2 * margin) + margin,
t = (this.labels ? this.getProp('points')[i] : i) + '',
length = this.fontSize * t.length
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.pads[i].colors.text
this.ctx.fillText(t, x + 0.5 * PXSCALE, y + PXSCALE)
this.clearRect[i] = [x - length / 2, y - this.fontSize / 2, length, this.fontSize + 2 * PXSCALE]
}
}
getValue() {
var v = []
for (var i=0;i<this.pads.length * 2;i=i+2) {
[v[i],v[i+1]] = this.pads[i/2].getValue()
}
return v
}
setValue(v, options={}) {
if (!v || !v.length || v.length!=this.npoints * 2) return
if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
for (let i=0;i<this.npoints;i++) {
if (!options.dragged) {
this.pads[i].setValue([v[i*2],v[i*2+1]])
}
}
this.updateHandlesPosition()
this.batchDraw()
for (let i=0;i<this.npoints * 2;i=i+2) {
[this.value[i],this.value[i+1]] = this.pads[i/2].getValue()
}
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
getSplit() {
return this.getProp('split')?
typeof this.getProp('split') == 'object' && this.getProp('split').length == 2 * this.npoints ?
this.getProp('split')
: (()=>{
var s={},
t
for (var i=0; i<this.npoints * 2;i=i+2) {
t = this.labels ? this.getProp('points')[i/2] : i/2
s[i]=this.getProp('address') + '/' + t + '/x'
s[i+1]=this.getProp('address') + '/' + t + '/y'
}
return s
})()
: false
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'colorWidget':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
case 'alphaFillOff':
case 'alphaFillOn':
for (var w of this.pads) {
w.onPropChanged(propName)
}
return
}
}
onRemove() {
for (var i in this.pads) {
this.pads[i].onRemove()
}
super.onRemove()
}
}

View file

@ -0,0 +1,33 @@
var Canvas = require('../common/canvas'),
html = require('nanohtml')
class Pad extends Canvas {
constructor(options) {
super({...options, html: html`
<inner>
<canvas></canvas>
</inner>
`})
this.canvas.style.setProperty('--pointSize', parseInt(this.getProp('pointSize')) + 'rem')
}
cacheCanvasStyle(style) {
style = style || window.getComputedStyle(this.canvas)
super.cacheCanvasStyle(style)
this.pointSize = parseFloat(style.getPropertyValue('--pointSize')) * PXSCALE
this.padPadding = (this.cssVars.padding + PXSCALE)
}
}
Pad.dynamicProps = Pad.prototype.constructor.dynamicProps.filter(n => n !== 'precision')
module.exports = Pad

View file

@ -0,0 +1,272 @@
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 description() {
return 'Color picker with optional alpha slider.'
}
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`<div class="hue-wrapper"></div>`)
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`<div class="alpha-wrapper"></div>`)
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], false)
}
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()
}
}

View file

@ -0,0 +1,305 @@
var Pad = require('./pad'),
Fader = require('./_fake_fader'),
doubletab = require('../mixins/double_tap'),
touchstate = require('../mixins/touch_state')
var faderDefaults = Fader.defaults()._props()
class XyFader extends Fader {
draw(){}
batchDraw(){}
}
module.exports = class Xy extends Pad {
static description() {
return 'Two-dimensional slider.'
}
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|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (base 10). Set to a `number` to define the logarithm\'s base.'},
logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm\'s base.'},
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: `/<doubleTap> <preArgs>`'
]},
sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
}, [], {
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'
]},
})
}
constructor(options) {
super(options)
this.faders = {
x: new XyFader({props:{
...faderDefaults,
id:0,
horizontal:true,
default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
snap:this.getProp('snap'),
range:this.getProp('rangeX'),
precision:this.getProp('precision'),
logScale:this.getProp('logScaleX'),
sensitivity: this.getProp('sensitivity'),
}, parent: this}),
y: new XyFader({props:{
...faderDefaults,
id:1,
horizontal:false,
default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
snap:this.getProp('snap'),
range:this.getProp('rangeY'),
precision:this.getProp('precision'),
logScale:this.getProp('logScaleY'),
sensitivity: this.getProp('sensitivity'),
}, parent: this}),
}
this.on('change',(e)=>{
if (e.widget == this) return
e.stopPropagation = true
})
touchstate(this, {element: this.canvas})
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.canvas})
this.on('drag',(e)=>{
this.faders.x.trigger('drag', e)
this.faders.y.trigger('drag', e)
this.dragHandle()
}, {element: this.canvas})
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.getSpringValue(),this.faders.y.getSpringValue()],{sync:true,send:true})
} else {
this.batchDraw()
}
}, {element: this.canvas})
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.faders.x.setValue(this.faders.x.getSpringValue(), {sync: false, send:false, dragged:true})
this.faders.y.setValue(this.faders.y.getSpringValue(), {sync: false, send:false, dragged:true})
this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true, send:true})
})
}
}
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()
}
}
resizeHandle(event){
super.resizeHandle(event)
for (var k in this.faders) {
this.faders[k].width = this.width
this.faders[k].height = this.height
this.faders[k].gaugePadding = this.padPadding
}
}
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()
}
draw() {
var pointSize = this.pointSize,
margin = this.padPadding,
x = this.faders.x.percentToCoord(this.faders.x.percent),
y = this.faders.y.percentToCoord(this.faders.y.percent)
this.clear()
this.ctx.fillStyle = this.cssVars.colorFill
this.ctx.globalAlpha = this.cssVars.alphaFillOn
this.ctx.beginPath()
this.ctx.arc(x, y, pointSize - 3 * PXSCALE, Math.PI * 2, false)
this.ctx.fill()
var pipsDrawn = false
if (this.getProp('pips')) {
var pipTexts = margin >= this.fontSize * 1.5
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.textFade
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.globalAlpha = 1
this.ctx.beginPath()
for (let i in this.faders.x.rangeKeys) {
let pip = this.faders.x.rangeKeys[i],
px = Math.round(0.5 * this.faders.x.percentToCoord(pip)) * 2
if (parseInt(px) === px) px -= 0.5
if (pipTexts) {
this.ctx.textAlign = 'center'
let label = this.faders.x.rangeLabels[i]
this.ctx.fillText(label, px, this.height - margin / 2)
pipsDrawn = true
}
if (pip == 0 || pip == 100) continue
this.ctx.moveTo(px, margin)
this.ctx.lineTo(px, this.height - margin)
pipsDrawn = true
}
for (let i in this.faders.y.rangeKeys) {
let pip = this.faders.y.rangeKeys[i],
py = Math.round(0.5 * this.faders.y.percentToCoord(pip)) * 2
if (parseInt(py) === py) py -= 0.5
if (pipTexts) {
this.ctx.textAlign = 'right'
let label = this.faders.y.rangeLabels[i]
this.ctx.fillText(label, margin / 2 + this.fontSize / 2, py)
pipsDrawn = true
}
if (pip == 0 || pip == 100) continue
this.ctx.moveTo(margin, py)
this.ctx.lineTo(this.width - margin, py)
pipsDrawn = true
}
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.stroke()
}
if (!pipsDrawn) this.clearRect = [x - this.pointSize - 2 * PXSCALE, y - this.pointSize - 2 * PXSCALE, (this.pointSize + PXSCALE) * 4, (this.pointSize + PXSCALE) * 4]
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.globalAlpha = this.active ? 1 : 0.75
this.ctx.lineWidth = 1.5 * PXSCALE
this.ctx.beginPath()
this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
this.ctx.stroke()
}
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
}
onRemove() {
this.faders.x.onRemove()
this.faders.y.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,20 @@
var {mapToScale} = require('../utils'),
Widget = require('../common/widget'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Script extends StaticProperties(Widget, {visible: false}) {
constructor(options) {
super(options)
// compile script
}
runScript() {
}
}

View file

@ -0,0 +1,260 @@
var {clip} = require('../utils'),
Knob = require('./knob'),
Widget = require('../common/widget'),
doubletab = require('../mixins/double_tap'),
html = require('nanohtml'),
StaticProperties = require('../mixins/static_properties')
module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range: {min: 0, max: 1}, sensitivity: 1, steps: ''}) {
static description() {
return 'A knob that sends a relative direction infomation instead of an absolute value.'
}
static defaults() {
return Widget.defaults({
_encoder: 'encoder',
ticks: {type: 'number', value: 360, help: 'defines the granularity / verbosity of the encoder (number of step for a 360° arc)'},
back: {type: '*', value: -1, help: 'Defines which value is sent when rotating the encoder anticlockwise'},
forth: {type: '*', value: 1, help: 'Defines which value is sent when rotating the encoder clockwise'},
release: {type: 'number', value: '', help: [
'Defines which value is sent when releasing the encoder:',
'- Set to `null` to send send no argument in the osc message',
'- Can be an `object` if the type needs to be specified'
]},
mode: {type: 'string', value: 'circular', choices: ['circular', 'snap', 'vertical'], help: [
'- `circular`: relative move in circular motion',
'- `snap`: snap to touch position and move in vertical motion',
'- `vertical`: relative move in vertical motion',
]},
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 (`/<doubleTap> <preArgs>`)'
]},
}, [], {
touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
})
}
constructor(options) {
super(options)
this.previousPercent = 50
this.percent = 50
this.setValue(this.getProp('release'), {dragged: true})
}
angleToPercent(angle, snap) {
// knob.js without clipping
if (snap) return super.angleToPercent(angle)
var percent = angle - (360 - this.maxAngle) / 2 / this.maxAngle * 100
if (percent < 0) percent += 100
else if (percent > 100) percent -= 100
return percent
}
percentToAngle(percent, snap) {
// knob.js without clipping
if (snap) return super.percentToAngle(percent)
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
}
draginitHandle(e) {
// knob.js without clipping + extra case for snap
this.lastOffsetX = e.offsetX
this.lastOffsetY = e.offsetY
if (this.getProp('mode') === 'snap') {
this.setPercent(this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY), true))
}
}
dragHandle(e) {
// knob.js without clipping + extra case for snap
if ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
// vertical
this.setPercent(-100 * (e.movementY / e.inertia * this.getProp('sensitivity')) / this.height + this.percent)
} else {
// snap or circular
var offsetX = this.lastOffsetX + e.movementX,
offsetY = this.lastOffsetY + e.movementY
if (e.traversing || this.getProp('mode') === 'circular') {
// circular
var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
if (Math.abs(diff) < 50 && diff !== 0) this.setPercent(this.percent + diff)
} else {
// snap
this.setPercent(this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true))
}
this.lastOffsetX = offsetX
this.lastOffsetY = offsetY
}
}
dragendHandle(e, data, traversing) {
if (this.getProp('release') === '') return
this.previousPercent = 50
this.percent = 50
this.setValue(this.getProp('release'), {sync: true, send: true, dragged: true})
}
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.setPercent(this.percent + Math.max(increment, 10 / Math.pow(10, this.precision + 1)) * direction)
}
setPercent(percent) {
var div = 100 / this.getProp('ticks')
percent = Math.round(percent / div) * div
this.previousPercent = this.percent
this.percent = percent
if (this.percent === this.previousPercent) return
var dir = this.percent > this.previousPercent
if (
(this.percent >= 0 && this.percent < 25 && this.previousPercent > 75 && this.previousPercent <= 100) ||
(this.previousPercent >= 0 && this.previousPercent < 25 && this.percent > 75 && this.percent <= 100)
) dir = !dir
var val = dir ? this.getProp('forth') : this.getProp('back')
this.setValue(val, {
sync: true,
send: true,
dragged: true,
})
}
getSpringValue() {
return this.getProp('release')
}
setValue(v,options={}) {
if (options.fromLocal && v === this.getProp('release')) {
this.percent = 50
this.previousPercent = 50
} else if (
!options.dragged ||
(v !== this.getProp('forth') && v !== this.getProp('back') && (this.getProp('release') === '' && v !== this.getProp('release')))
) return
this.value = v
this.batchDraw()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
draw() {
var percent = this.percent,
d = this.percentToAngle(percent),
angle = 2 * Math.PI / 16,
min = this.percentToAngle(0),
max = this.percentToAngle(100),
minRadius = this.minDimension / 6,
maxRadius = this.minDimension / 2 - PXSCALE,
gaugeWidth = maxRadius - minRadius,
gaugeRadius = maxRadius - gaugeWidth / 2
this.clear()
// fill
this.ctx.globalAlpha = this.cssVars.alphaFill
this.ctx.strokeStyle = this.cssVars.colorFill
this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
if (this.cssVars.alphaFillOff) {
this.ctx.globalAlpha = this.cssVars.alphaFillOff
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
this.ctx.stroke()
}
if (this.cssVars.alphaFillOn) {
this.ctx.globalAlpha = this.cssVars.alphaFillOn
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, d - angle, d + angle)
this.ctx.stroke()
}
// stroke
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, minRadius, 0, 2 * Math.PI)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
this.ctx.stroke()
}
}

View file

@ -0,0 +1,269 @@
var {clip} = require('../utils'),
Slider = require('./slider'),
parser = require('../../parser'),
html = require('nanohtml')
module.exports = class Fader extends Slider {
static description() {
return 'Vertical / horizontal 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'},
dashed: {type: 'boolean', value: false, help: 'Set to `true` to display a dashed gauge'},
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\'} '
]},
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 (`/<doubleTap> <preArgs>`)'
]},
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}}`)'
]},
logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale (base 10). Set to a `number` to define the logarithm\'s base.'},
sensitivity: {type: 'number', value: 1, help: 'Defines the fader\'s sensitivity when `snap` is `false` '},
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',
]},
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`'},
})
}
constructor(options) {
super(options)
this.widget.classList.add('fader')
this.gaugeGradient = null
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 (false && 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`<div class="pips"></div>`
for (var i=0;i<=100;i++) {
if (pipTexts[i]==undefined) continue
var pos = this.getProp('horizontal')?'left':'bottom'
pips.appendChild(html`
<div class="pip val" style="${pos}:${i}%">
<span>${Math.abs(pipTexts[i])>=1000?pipTexts[i]/1000+'k':pipTexts[i]}</span>
</div>
`)
}
this.widget.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.gaugePadding) / (this.width - this.gaugePadding * 2) * 100:
(this.height - e.offsetY - this.gaugePadding) / (this.height - this.gaugePadding * 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.gaugePadding * 2)) * 100 / e.inertia * this.getProp('sensitivity'):
this.percent + (-e.movementY / (this.height - this.gaugePadding * 2)) * 100 / e.inertia * this.getProp('sensitivity')
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 - this.gaugePadding * 2) + this.gaugePadding
} else {
return (this.height - this.gaugePadding) - clip(percent / 100, [0,1]) * (this.height - this.gaugePadding * 2)
}
}
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.gaugeGradient = grad
} else {
for (var k in colors) {
if (!isNaN(k)) {
grad.addColorStop(clip(k, [0, 1]), colors[k])
}
}
this.gaugeGradient = 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 = this.getProp('horizontal') ? this.height / 2 : this.width / 2
// sharp border trick
if (width % 2 && parseInt(m) === m) m -= 0.5
var dashed = this.getProp('dashed')
this.clear()
this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
if (this.cssVars.alphaFillOff) {
this.ctx.globalAlpha = this.cssVars.alphaFillOff
this.ctx.beginPath()
this.ctx.moveTo(m, height - this.gaugePadding)
this.ctx.lineTo(m, this.gaugePadding)
this.ctx.stroke()
}
if (this.cssVars.alphaFillOn) {
this.ctx.globalAlpha = this.cssVars.alphaFillOn
this.ctx.beginPath()
this.ctx.moveTo(m, o)
this.ctx.lineTo(m, d)
this.ctx.stroke()
}
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.beginPath()
this.ctx.moveTo(0, 0)
this.ctx.lineTo(width, 0)
this.ctx.lineTo(width, height)
this.ctx.lineTo(0, height)
this.ctx.closePath()
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.stroke()
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.cssVars.colorFill
this.ctx.beginPath()
this.ctx.rect(this.gaugePadding, Math.min(d, height - 3 * PXSCALE), width - this.gaugePadding * 2, PXSCALE)
this.ctx.fill()
this.clearRect = [0, 0, width, height]
}
}

View file

@ -0,0 +1,274 @@
var {clip} = require('../utils'),
Slider = require('./slider')
module.exports = class Knob extends Slider {
static description() {
return 'Rotative knob slider.'
}
static defaults() {
return super.defaults({
_knob:'knob',
mode: {type: 'string', value: 'circular', choices: ['circular', 'snap', 'vertical'], help: [
'- `circular`: relative move in circular motion',
'- `snap`: snap to touch position and move in vertical motion',
'- `vertical`: relative move in vertical motion',
]},
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: false, help: 'Set to `true` to show the scale\'s breakpoints'},
dashed: {type: 'boolean', value: false, help: 'Set to `true` to display a dashed gauge'},
angle: {type: 'number', value: 270, help: 'Defines the angle\'s width of the knob, in degrees'},
doubleTap: {type: 'boolean', value: false, help: [
'Set to `true` to make the knob 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 (`/<doubleTap> <preArgs>`)'
]},
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}}`)'
]},
logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale (base 10). Set to a `number` to define the logarithm\'s base.'},
sensitivity: {type: 'number', value: 1, help: 'Defines the knob\'s sensitivity when `mode` is not `snap` '},
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',
]},
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`'},
})
}
constructor(options) {
super(options)
this.widget.classList.add('knob')
this.lastOffsetX = 0
this.lastOffsetY = 0
this.minDimension = 0
this.maxAngle = this.getProp('angle')
if (this.getProp('pips')) {
this.widget.classList.add('has-pips')
this.pipTexts = {}
for (var k in this.rangeKeys) {
this.pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
}
}
}
draginitHandle(e) {
this.percent = clip(this.percent,[0,100])
this.lastOffsetX = e.offsetX
this.lastOffsetY = e.offsetY
if (this.getProp('mode') === 'snap') {
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 ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
// vertical
this.percent = -100 * (e.movementY / e.inertia * this.getProp('sensitivity')) / this.minDimension + this.percent
} else {
// snap or circular
var offsetX = this.lastOffsetX + e.movementX,
offsetY = this.lastOffsetY + e.movementY
if (e.traversing || this.getProp('mode') === 'circular') {
// circular
var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY)) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY))
if (Math.abs(diff) < 50 && diff !== 0) this.percent += diff
} else {
// snap
this.percent = this.angleToPercent(this.coordsToAngle(offsetX, offsetY))
}
this.lastOffsetX = offsetX
this.lastOffsetY = offsetY
}
// this.percent = clip(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.widget.style.top = this.minDimension - (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'),
minRadius = this.minDimension / 6,
maxRadius = this.minDimension / 2 - (pips ? this.fontSize * 1.5 : PXSCALE),
gaugeWidth = maxRadius - minRadius,
gaugeRadius = maxRadius - gaugeWidth / 2
this.clear()
// fill
this.ctx.strokeStyle = this.cssVars.colorFill
this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
if (this.cssVars.alphaFillOff) {
this.ctx.globalAlpha = this.cssVars.alphaFillOff
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
this.ctx.stroke()
}
if (dashed) this.ctx.setLineDash([1.5 * PXSCALE, 1.5 * PXSCALE])
if (this.cssVars.alphaFillOn) {
this.ctx.globalAlpha = this.cssVars.alphaFillOn
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([])
// stroke
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, minRadius, 0, 2 * Math.PI)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
this.ctx.stroke()
// knob
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.cssVars.colorFill
this.ctx.lineWidth = 1.5 * PXSCALE
let r1 = minRadius + this.gaugePadding,
r2 = maxRadius - this.gaugePadding,
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.stroke()
// pips
if (pips) {
this.ctx.globalAlpha = 1
this.ctx.lineWidth = 1.5 * PXSCALE
this.ctx.strokeStyle = this.cssVars.colorStroke
for (var pip of this.rangeKeys.concat(this.valueToPercent(this.originValue))) {
let r1 = maxRadius,
r2 = r1 + 4 * PXSCALE,
a = 2 * Math.PI - this.percentToAngle(pip)
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.stroke()
}
var radius = maxRadius + this.fontSize * 1.5
this.ctx.fillStyle = this.colors.textFade
for (var p in this.pipTexts) {
if (this.pipTexts[p] == undefined) continue
var angle = this.percentToAngle(p),
size = this.ctx.measureText(this.pipTexts[p]),
x = this.width / 2 + radius * Math.cos(angle) - size.width / 2,
y = this.height / 2 + radius * Math.sin(angle)
this.ctx.fillText(this.pipTexts[p], x, y)
}
}
}
}

View file

@ -0,0 +1,290 @@
var {clip} = require('../utils'),
Canvas = require('../common/canvas'),
Fader = require('./fader'),
Input = require('../inputs/input'),
touchstate = require('../mixins/touch_state'),
html = require('nanohtml')
var faderDefaults = Fader.defaults()._props()
class Range extends Fader {
static description() {
return 'A fader with two heads for setting a range.'
}
constructor(options) {
options.multitouch = true
super({...options, html: html`
<canvas></canvas>
`})
this.faders = [
new Fader({props:{
...faderDefaults,
pips:false,
visible: false,
horizontal:this.getProp('horizontal'),
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'),
precision:this.getProp('precision'),
logScale:this.getProp('logScale'),
sensitivity:this.getProp('sensitivity'),
}, parent: this}),
new Fader({props:{
...faderDefaults,
pips:false,
visible: false,
horizontal:this.getProp('horizontal'),
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'),
precision:this.getProp('precision'),
logScale:this.getProp('logScale'),
sensitivity:this.getProp('sensitivity'),
}, parent: this})
]
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 = {}
this.setValue([
this.faders[0].rangeValsMin,
this.faders[1].rangeValsMax
])
}
resizeHandle(event){
super.resizeHandle(event)
for (var f of this.faders) {
f.width = this.width
f.height = this.height
f.gaugePadding = this.gaugePadding
}
}
draginitHandle(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
for (var f of this.faders) {
f.percent = clip(f.percent,[
f.valueToPercent(f.rangeValsMin),
f.valueToPercent(f.rangeValsMax)
])
}
e.stopPropagation = true
this.faders[id].trigger('draginit', e)
}
dragHandle(e) {
var i = this.touchMap[e.pointerId]
if (!i) return
if (e.shiftKey) {
this.faders[0].trigger('drag', e)
this.faders[1].trigger('drag', e)
} else {
this.faders[i].trigger('drag', e)
}
}
dragendHandle(e) {
var i = this.touchMap[e.pointerId]
if (!i) return
e.stopPropagation = true
this.faders[i].trigger('dragend', e)
delete this.touchMap[e.pointerId]
}
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.batchDraw()
}
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
}
draw() {
var width = this.getProp('horizontal') ? this.height : this.width,
height = !this.getProp('horizontal') ? this.height : this.width,
fader = this.faders[0]
var d = Math.round(fader.percentToCoord(fader.valueToPercent(this.faders[this.getProp('horizontal')?0:1].value))),
d2 = Math.round(fader.percentToCoord(fader.valueToPercent(this.faders[this.getProp('horizontal')?1:0].value))),
m = Math.round(this.getProp('horizontal') ? this.height / 2 : this.width / 2)
// sharp border trick
if (width % 2 && parseInt(m) === m) m -= 0.5
var dashed = this.getProp('dashed')
this.clear()
this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
if (this.cssVars.alphaFillOff) {
this.ctx.globalAlpha = this.cssVars.alphaFillOff
this.ctx.beginPath()
this.ctx.moveTo(m, height - this.gaugePadding)
this.ctx.lineTo(m, this.gaugePadding)
this.ctx.stroke()
}
if (dashed) {
this.ctx.lineDashOffset = d % 2 ? PXSCALE : 0 // avoid flickering
this.ctx.setLineDash([PXSCALE, PXSCALE])
}
if (this.cssVars.alphaFillOn) {
this.ctx.globalAlpha = this.cssVars.alphaFillOn
this.ctx.beginPath()
this.ctx.moveTo(m, d)
this.ctx.lineTo(m, d2)
this.ctx.stroke()
}
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.strokeStyle = this.cssVars.colorStroke
this.ctx.beginPath()
this.ctx.moveTo(0, 0)
this.ctx.lineTo(width, 0)
this.ctx.lineTo(width, height)
this.ctx.lineTo(0, height)
this.ctx.closePath()
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.stroke()
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.cssVars.colorFill
this.ctx.beginPath()
this.ctx.rect(this.gaugePadding, Math.min(d, height - 3 * PXSCALE), width - this.gaugePadding * 2, PXSCALE)
this.ctx.fill()
this.ctx.beginPath()
this.ctx.rect(this.gaugePadding, Math.min(d2, height - 3 * PXSCALE), width - this.gaugePadding * 2, PXSCALE)
this.ctx.fill()
this.clearRect = [0, 0, width, height]
}
onRemove() {
this.faders[0].onRemove()
this.faders[1].onRemove()
super.onRemove()
}
}
Range.dynamicProps = Range.prototype.constructor.dynamicProps
.filter(n => !['spring', 'precision'].includes(n))
module.exports = Range

View file

@ -0,0 +1,260 @@
var {clip, mapToScale} = require('../utils'),
Canvas = require('../common/canvas'),
touchstate = require('../mixins/touch_state'),
doubletab = require('../mixins/double_tap'),
html = require('nanohtml')
class Slider extends Canvas {
constructor(options) {
super({...options, html: html`
<canvas></canvas>
`})
this.value = undefined
this.percent = 0
this.gaugePadding = 0
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])
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.getSpringValue(),{sync:true, send:true, fromLocal:true})
})
}
}
this.widget.addEventListener('mousewheel',this.mousewheelHandleProxy.bind(this))
this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
this.on('drag', this.dragHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
touchstate(this, {element: this.widget, multitouch: options.multitouch})
this.setSteps()
this.setValue(this.getSpringValue())
}
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
if (this.getProp('steps')) {
var i = this.steps.indexOf(this.value)
if (i > -1 && i < this.steps.length) {
this.setValue(this.steps[i + direction], {sync: true, send: true, fromLocal: true})
}
} else {
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.getSpringValue(),{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')
this.gaugePadding = this.cssVars.padding + PXSCALE
}
getSpringValue() {
return this.getProp('default') !== '' ? this.getProp('default') : this.originValue
}
percentToValue(percent) {
var h = clip(percent,[0,100])
for (var i=0;i<this.rangeKeys.length-1;i++) {
if (h <= this.rangeKeys[i+1] && h >= 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.length-1;i++) {
if (
(this.rangeVals[i+1] > 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)
this.batchDraw()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
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 'steps':
this.setSteps()
return
}
}
onRemove() {
super.onRemove()
}
}
Slider.dynamicProps = Slider.prototype.constructor.dynamicProps
.filter(n => n !== 'precision')
.concat([
'steps',
'spring',
'sensitivity',
'default',
])
module.exports = Slider

View file

@ -0,0 +1,115 @@
var Widget = require('../common/widget'),
widgetManager = require('../../managers/widgets'),
osc = require('../../osc')
module.exports = class _switchers_base extends Widget {
constructor(options) {
super(options)
this._isSwitcher = true
this.value = {_selected:false}
this.linkedWidgets = typeof this.getProp('linkedWidgets') == 'object' ? this.getProp('linkedWidgets') : [this.getProp('linkedWidgets')]
for (var i in this.getProp('values')) {
this.value[this.getProp('values')[i]] = {}
}
widgetManager.on('change', this.syncHandler.bind(this), {context: this})
}
syncHandler(e) {
var {id, widget} = e
if (widget && this.value._selected !== false && this.value[this.value._selected] && widget._isSwitcher !== true && this.isWatching(id, widget)) {
this.value[this.value._selected][id] = widget.getValue()
}
}
isWatching(id, widget) {
if (this.linkedWidgets.indexOf(id) != -1) return true
for (var k in this.linkedWidgets) {
let widgets = widgetManager.getWidgetById(this.linkedWidgets[k])
for (var i in widgets) {
if (widgets[i].contains(widget) || widgets[i] === widget) return true
}
}
}
setValue(v, options={}) {
let apply = false
if (typeof v == 'object') {
for (var k in this.value) {
if (v.hasOwnProperty(k)) {
this.value[k] = v[k]
apply = true
}
}
} else if (this.value[v] && v != '_selected') {
this.value._selected = v
apply = true
}
if (apply) this.applyState(this.value[this.value._selected], 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)
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.changed(options)
if (options.send) this.sendValue()
}
sendValue() {
osc.sync({
h:this.hash,
v:this.value
})
}
}

View file

@ -0,0 +1,158 @@
var Switcher = require('./switcher'),
Widget = require('../common/widget'),
Fader = require('../sliders/fader'),
{mapToScale} = require('../utils')
var faderDefaults = Fader.defaults()._props()
module.exports = class Crossfader extends Switcher {
static description() {
return 'Switcher with linear interpolation slider.'
}
static defaults(){
return Widget.defaults({
_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) {
options.props.values = options.props.horizontal ? ['A', 'B'] : ['B', 'A']
super(options)
this.fader = new Fader({props:{
...faderDefaults,
horizontal: this.getProp('horizontal'),
range: {min:{'A':0}, '50%':{' ':0.5},max:{'B':1}},
input: false
}, parent: this})
this.fader.sendValue = ()=>{}
this.widget.appendChild(this.fader.widget)
if (this.getProp('horizontal')) {
this.widget.classList.add('horizontal')
} else {
this.widget.classList.add('vertical')
}
this.fader.on('change', (e)=>{
e.stopPropagation = true
this.setValue(this.fader.getValue(), e.options)
})
this.value._fader = 0
}
setValue(v, options={}) {
v = v <= 0 || v == 'A' ?
'A' :
v >= 1 || v == 'B' ?
'B' :
v
super.setValue(v, options)
if (typeof v == 'object') {
this.fader.setValue(this.value._fader, {dragged:options.dragged})
}
if (v == 'A') {
this.fader.setValue(0, {dragged:options.dragged})
this.value._fader = 0
} else if (v == 'B') {
this.fader.setValue(1, {dragged:options.dragged})
this.value._fader = 1
} else if (!isNaN(v)) {
this.fader.setValue(v, {dragged:options.dragged})
this.value._fader = this.fader.getValue()
this.value._selected = false
this.switch.setValue()
var s = this.getValue(),
a = {}
for (var i in s['A']) {
if (s['B'][i] === undefined) continue
if (Array.isArray(s['A'][i])) {
a[i] = []
for (var k in s['A'][i]) {
if (!isNaN(s['A'][i][k])) {
a[i][k] = mapToScale(v, [0,1], [s['A'][i][k], s['B'][i][k]], false)
}
}
} else if (!isNaN(s['A'][i])) {
a[i] = mapToScale(v, [0,1], [s['A'][i], s['B'][i]], false)
}
}
this.applyState(a, options)
}
}
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()
}
}

View file

@ -0,0 +1,161 @@
var Widget = require('../common/widget'),
Toggle = require('../buttons/toggle'),
pushDefaults = Toggle.defaults()._props(),
html = require('nanohtml'),
stateManager = require('../../managers/state'),
widgetManager = require('../../managers/widgets'),
{deepCopy} = require('../../utils'),
osc = require('../../osc')
class State extends Widget {
static description() {
return 'Save and recall the state of other widgets.'
}
static defaults() {
return super.defaults({
_state: 'state',
filter: {type: 'string|array', value: '', help: [
'Only save state from widgets contained in widgets designated by id. If empty, the whole session\'s state is saved. Switchers are always ignored.',
'- widget id `string`',
'- `array` of widget id strings'
]},
saveLabel: {type: 'string', value: 'Save', help: 'Label for save button'},
loadLabel: {type: 'string', value: 'Load', help: 'Label for load button'},
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display buttons horizontally'},
}, [], {
value: {type: 'object|string', value: '', help: [
'- `object`: `"widget_id": VALUE` pairs',
'- `string`: `"save"` (trigger save action), `"load"` (trigger load action) or `""` (reset value)',
'',
'Note: the widget\'s actual value is never `"save"` or `"load"`, it\'s either an empty string or an object.'
]}
})
}
constructor(options) {
super({...options, html: html`<div class="switch"></div>`})
this._isSwitcher = true
if (this.getProp('horizontal')) this.widget.classList.add('horizontal')
this.saveButton = new Toggle({props: {...pushDefaults, type: 'toggle', mode: 'push', label: this.getProp('saveLabel')}, parent: this, container: true})
this.loadButton = new Toggle({props: {...pushDefaults, type: 'toggle', mode: 'push', label: this.getProp('loadLabel')}, parent: this, container: true})
this.saveButton.container.classList.add('not-editable', 'value')
this.loadButton.container.classList.add('not-editable', 'value', 'disabled')
this.saveButton.sendValue = this.loadButton.sendValue = ()=>{}
this.widget.appendChild(this.saveButton.container)
this.widget.appendChild(this.loadButton.container)
this.on('change', (e)=>{
var {widget} = e
if (widget === this) return
e.stopPropagation = true
if (widget.active) this.setValue(widget === this.saveButton ? 'save' : 'load', {sync: true, send: true})
})
this.filter = this.getProp('filter') ? Array.isArray(this.getProp('filter')) ? this.getProp('filter') : [this.getProp('filter')] : false
this.value = ''
}
save() {
var filter = (widget)=>{
return !widget._isSwitcher
}
if (this.filter) {
var containers = this.filter.map(x=>widgetManager.getWidgetById(x)).reduce((a,b)=>a.concat(b), [])
if (!containers.length) return
filter = (widget)=>{
return !widget._isSwitcher && containers.some(x=>x.contains(widget) || x === widget)
}
}
if (!this.value) this.loadButton.container.classList.remove('disabled')
this.value = deepCopy(stateManager.get(filter))
}
load(send) {
if (this.value) stateManager.set(this.value, send)
}
setValue(v,options={}) {
var valid
if (v === 'save') {
this.save()
valid = true
} else if (v === 'load') {
this.load(options.send)
valid = true
} else if (v === '') {
if (this.value) this.loadButton.container.classList.add('disabled')
this.value = ''
} else if (typeof v === 'object' && !Array.isArray(v)) {
if (!this.value) this.loadButton.container.classList.remove('disabled')
this.value = v
valid = true
}
if (valid) {
if (options.sync) this.changed(options)
if (options.send) this.sendValue()
}
}
sendValue() {
osc.sync({
h:this.hash,
v:this.value
})
}
onRemove() {
this.saveButton.onRemove()
this.loadButton.onRemove()
super.onRemove()
}
}
module.exports = State

View file

@ -0,0 +1,94 @@
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 description() {
return 'Store other widgets\' values and recall them.'
}
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`<div class="switcher"></div>`})
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()
}
}

216
src/client/widgets/utils.js Normal file
View file

@ -0,0 +1,216 @@
var {deepCopy} = require('../utils')
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) {
// clip in
value = module.exports.clip(value,[rangeIn[0],rangeIn[1]])
// normalize
value = (value - rangeIn[0]) / (rangeIn[1] - rangeIn[0])
// log scale
if (log) {
if (log === true) log = 10
value = revertlog ?
Math.pow(log, value) / (log - 1) - 1 / (log - 1) :
Math.log(value * (log - 1) + 1) / Math.log(log)
}
// scale out
value = value * (rangeOut[1] - rangeOut[0]) + rangeOut[0]
// clip out
value = module.exports.clip(value,[rangeOut[0],rangeOut[1]])
// precision
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
},
urlParser: (()=>{
var parser = document.createElement('a'),
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}$)/
parser.isLocal = ()=>{
return parser.hostname.match(localUrlRe)
}
return (url)=>{
parser.href = url
return parser
}
})(),
evaljs: (function(){
var sandbox = document.createElement('iframe'),
loopProtect = require('loop-protect')
sandbox.style.display = 'none'
sandbox.sandbox = 'allow-same-origin'
document.documentElement.appendChild(sandbox)
// block requests
sandbox.contentWindow.document.open()
sandbox.contentWindow.document.write('<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src \'unsafe-eval\';">')
sandbox.contentWindow.document.close()
// init infinite loop guard
loopProtect.alias = '__protect'
loopProtect.hit = function(line){
throw 'Potential infinite loop found on line ' + line
}
sandbox.contentWindow.__protect = loopProtect
var _Function = sandbox.contentWindow.Function,
parsers = {}
sandbox.contentWindow.console = console
sandbox.contentWindow.setTimeout =
sandbox.contentWindow.setInterval = ()=>{
throw 'setTimeout and setInterval can\'t be used in the JS sandbox'
}
sandbox.contentWindow.global = {}
function nuke(o) {
// non-primitives created outside the sandbox context can leak
// the host window object... let's nuke that !
// (we only nuke function and objects/arrays because we don't pass anything else)
var t = typeof o
if (t === 'function' || (t === 'object' && o !== null)) {
if (o.__proto__) {
if (t === 'function') {
o.__proto__.constructor = _Function
} else {
o.__proto__.constructor.constructor = _Function
}
}
for (var k in o) {
nuke(o[k])
}
}
}
for (var imports of ['__protect', 'console', 'setTimeout', 'setInterval', 'global']) {
nuke(sandbox.contentWindow[imports])
}
document.documentElement.removeChild(sandbox)
function evaljs(code, defaultContext) {
var contextInit = '',
contextKeys = ['__VARS'],
contextValues = [{}]
if (defaultContext) {
for (var k in defaultContext) {
contextInit += `var ${k} = ${k} || ${JSON.stringify(defaultContext[k])};`
contextKeys.push(k)
contextValues.push(defaultContext[k])
}
}
parsers[code] = new _Function(
...contextKeys,
loopProtect('"use strict";' + contextInit + code)
.replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber
.replace(/(VAR_[0-9]+)/g, '__VARS.$1')
)
return (context)=>{
var ret, err, k
var __contextValues = deepCopy(contextValues)
var __VARS = __contextValues[0]
for (k in context) {
var index = contextKeys.indexOf(k)
if (index !== -1) {
__contextValues[index] = context[k]
} else {
__VARS[k] = context[k]
}
}
nuke(contextValues)
// evaluate
try {
ret = parsers[code].apply(null, __contextValues)
} catch(e) {
err = e
}
if (err) throw err
return ret
}
}
return evaljs
})()
}