package: rename browser to client and main to server

This commit is contained in:
bordun 2018-10-28 15:06:11 +01:00
parent ea142198e0
commit e8b2a3fb99
123 changed files with 43 additions and 42 deletions

107
src/client/app/dom.js Normal file
View file

@ -0,0 +1,107 @@
var DomParserFragment,
readyCallbacks = [],
initState = false
module.exports = {
init: function() {
DomParserFragment = document.createRange()
DomParserFragment.selectNode(document.body)
for (var i in readyCallbacks) {
readyCallbacks[i]()
}
initState = true
},
ready: function(callback) {
if (initState) {
callback()
} else {
readyCallbacks.push(callback)
}
},
dispatchEvent: function(element, name, data) {
var event = new CustomEvent(name, {
detail: data,
bubbles: true,
cancelable: true
})
element.dispatchEvent(event)
},
addEventListener: function(element, events, listener, capture) {
var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
for (var i in eventsAsObject) {
element.addEventListener(eventsAsObject[i], listener, capture)
}
},
get: function(a, b) {
var context = b ? a : document,
selector = b || a
if (selector.indexOf('>') == 0) selector = ':scope ' + selector
var nodes = context.querySelectorAll(selector)
return NodeList.prototype.forEach ? nodes : [...nodes]
},
create: function(html) {
return DomParserFragment.createContextualFragment(html.trim()).firstChild
},
each: function(context, selector, callback) {
var nodes = module.exports.get(context, selector)
nodes.forEach(callback)
return nodes
},
index: function(element) {
var parent = element.parentNode
return parent ? Array.prototype.indexOf.call(parent.children, element) : -1
},
offset: function(element) {
var offsetLeft = 0,
offsetTop = 0
if (element) {
do {
if (!isNaN(element.offsetLeft)) {
offsetLeft += element.offsetLeft - element.scrollLeft
}
if (!isNaN(element.offsetTop)) {
offsetTop += element.offsetTop - element.scrollTop
}
} while ((element = element.offsetParent))
}
return {
left: offsetLeft,
top: offsetTop
}
}
}

View file

@ -0,0 +1,305 @@
var {updateWidget} = require('./data-workers'),
{categories} = require('../widgets/'),
widgetManager = require('../managers/widgets'),
editor = require('./'),
locales = require('../locales')
var multiSelectKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
class ContextMenu {
constructor(){
this.menu = null
this.event = 'fast-click'
this.root = document.body
}
open(e, actions, parent) {
var menu = DOM.create('<div class="context-menu"></div>')
for (let label in actions) {
if (typeof actions[label] == 'object') {
let item = DOM.create(`<div class="item has-sub" tabIndex="1">${label}</div>`)
menu.appendChild(item)
this.open(e,actions[label],item)
} else {
let item = DOM.create(`<div class="item">${label}</div>`)
menu.appendChild(item)
item.addEventListener(this.event, (e)=>{
e.detail.preventOriginalEvent = true
actions[label]()
this.close()
})
}
}
if (parent) parent.appendChild(menu)
if (!parent) {
this.menu = menu
this.root.appendChild(menu)
DOM.each(menu, '.item', (item)=>{
item.addEventListener('mouseenter', ()=>{
DOM.each(item.parentNode, '.focus', (focused)=>{
focused.classList.remove('focus')
})
item.classList.add('focus')
})
item.addEventListener('mouseleave', ()=>{
if (!item.classList.contains('has-sub')) item.classList.remove('focus')
})
})
menu.style.top = e.pageY + 'px'
menu.style.left = e.pageX + 'px'
this.correctPosition(menu)
DOM.each(menu, '.context-menu', (m)=>{
this.correctPosition(m, m.parentNode)
})
}
}
close() {
if (this.menu) {
this.menu.parentNode.removeChild(this.menu)
this.menu = null
}
}
correctPosition(menu, parent) {
var position = DOM.offset(menu),
width = menu.offsetWidth,
height = menu.offsetHeight,
totalWidth = this.root.offsetWidth,
totalHeight = this.root.offsetHeight
if (width + position.left > totalWidth) {
menu.style.right = parent ? '100%' : '0'
menu.style.left = 'auto'
menu.style.marginRight = '2rem'
}
if (height + position.top > totalHeight) {
menu.style.top = 'auto'
menu.style.bottom = '2rem'
}
}
}
var contextMenu = new ContextMenu()
var handleClick = function(event) {
if (!EDITING) return
if (contextMenu.menu && !contextMenu.menu.contains(event.target)) contextMenu.close()
if (!event.detail[multiSelectKey] && event.type !== 'fast-right-click' && (
event.target.classList.contains('ui-resizable-handle') ||
event.target.classList.contains('ui-draggable-handle') ||
event.target.id === 'open-toggle'
)) { return }
var eventData = event.detail,
widget = widgetManager.getWidgetByElement(eventData.target, ':not(.not-editable)')
if (!widget) return
// if the widget is not already selected
if (!widget.container.classList.contains('editing')) {
// add a flag to the original event to prevent draginit
// and prevent any further fast-click (ie input focus)
eventData.capturedByEditor = true
event.capturedByEditor = true
}
if (event.type !== 'fast-right-click') {
editor.select(widget, {multi: event.detail[multiSelectKey]})
}
// right-click menu
if (event.type !== 'fast-right-click') return
if (!event.detail.shiftKey && !event.detail[multiSelectKey] && editor.selectedWidgets.length <= 1) {
editor.select(widget)
}
if (!editor.selectedWidgets.length) return
var index = editor.selectedWidgets.map((w)=>DOM.index(w.container)).sort((a,b)=>{return b-a}),
data = editor.selectedWidgets.map((w)=>w.props),
type = editor.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
parent = editor.selectedWidgets[0].parent,
actions = {}
// case root: only "add tab" option
if (parent === widgetManager) {
actions['<i class="fa fa-plus"></i> ' + locales('editor_addtab')] = ()=>{
data[0].tabs.push({})
var indexes = {addedIndexes: [data[0].tabs.length -1]}
updateWidget(widget, indexes)
editor.pushHistory(indexes)
}
contextMenu.open(eventData, actions)
return
}
// case !root
var clickX = Math.round((eventData.offsetX + eventData.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
clickY = Math.round((eventData.offsetY + eventData.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
actions['<i class="fa fa-expand"></i> ' + locales('editor_editparent')] = ()=>{
editor.select(parent)
}
if (type === 'widget') {
actions['<i class="fa fa-copy"></i> ' + locales('editor_copy')] = editor.copyWidget.bind(editor)
actions['<i class="fa fa-cut"></i> ' + locales('editor_cut')] = editor.cutWidget.bind(editor)
actions['<i class="fa fa-box"></i> ' + locales('editor_wrap')] = {}
for (let c of categories.Containers) {
if (c === 'clone') continue
actions['<i class="fa fa-box"></i> ' + locales('editor_wrap')][c] = ()=>{
var wrap = {type: c, widgets:[], label: c === 'modal' ? 'auto' : false}
wrap.widgets = data
var minTop = Math.min(...data.map(x=>isNaN(x.top) ? x.top == 'auto' ? 0 : Infinity : x.top))
var minLeft = Math.min(...data.map(x=>isNaN(x.left) ? x.left == 'auto' ? 0 : Infinity : x.left))
wrap.top = minTop === Infinity ? data[0].top : minTop
wrap.left= minLeft === Infinity ? data[0].left : minLeft
for (var w of wrap.widgets) {
if (!isNaN(w.top)) w.top = Math.max(w.top - minTop, 0)
if (!isNaN(w.left)) w.left = Math.max(w.left - minLeft, 0)
}
var i
for (i of index) {
parent.props.widgets.splice(i,1)
}
parent.props.widgets = parent.props.widgets.slice(0, i).concat(wrap, parent.props.widgets.slice(i, parent.props.widgets.length))
editor.select(updateWidget(parent, {preventSelect: true, removedIndexes: index, addedIndexes: [i]}))
editor.pushHistory({removedIndexes: index, addedIndexes: [i]})
}
}
}
if (data.length == 1 && (!data[0].tabs || !data[0].tabs.length) && (data[0].widgets)) {
if (editor.clipboard !== null) {
let paste = actions['<i class="fa fa-paste"></i> ' + locales('editor_paste')] = {}
paste['<i class="fa fa-paste"></i> ' + locales('editor_paste')] = ()=>{
editor.pasteWidget(clickX, clickY)
}
paste['<i class="fa fa-plus-square"></i> ' + locales('editor_pasteindent')] = ()=>{
editor.pasteWidget(clickX, clickY, true)
}
if (editor.idClipboard && widgetManager.getWidgetById(editor.idClipboard).length) {
paste['<i class="fa fa-clone"></i> ' + locales('editor_clone')] = ()=>{
editor.pasteWidgetAsClone(clickX, clickY)
}
}
}
actions['<i class="fa fa-plus"></i> ' + locales('editor_addwidget')] = {}
for (let category in categories) {
actions['<i class="fa fa-plus"></i> ' + locales('editor_addwidget')][category] = {}
for (let t in categories[category]) {
let type = categories[category][t]
actions['<i class="fa fa-plus"></i> ' + locales('editor_addwidget')][category][type] = ()=>{
var newData = {type: type}
if (!eventData.target.classList.contains('tablink')) {
newData.top = clickY
newData.left= clickX
}
data[0].widgets = data[0].widgets || []
data[0].widgets.push(newData)
var indexes = {addedIndexes: [data[0].widgets.length -1]}
updateWidget(editor.selectedWidgets[0], indexes)
editor.pushHistory(indexes)
}
}
}
}
if (data.length == 1 && (!data[0].widgets || !data[0].widgets.length) && (data[0].tabs)) {
actions['<i class="fa fa-plus"></i> ' + locales('editor_addtab')] = ()=>{
data[0].tabs = data[0].tabs || []
data[0].tabs.push({})
var indexes = {addedIndexes: [data[0].tabs.length -1]}
updateWidget(editor.selectedWidgets[0], indexes)
editor.pushHistory(indexes)
}
}
actions['<i class="fa fa-trash"></i> ' + locales('editor_delete')] = editor.deleteWidget.bind(editor)
contextMenu.open(eventData, actions)
}
document.addEventListener('fast-right-click', handleClick, true)
document.addEventListener('fast-click', handleClick, true)

View file

@ -0,0 +1,243 @@
var widgetManager = require('../managers/widgets'),
resize = require('../events/resize'),
stateManager = require('../managers/state'),
parser = require('../parser'),
Panel,
sidepanel,
editor,
scrollState = {},
sidepanelScroll
DOM.ready(()=>{
sidepanel = DOM.get('#sidepanel')[0]
})
function updateWidget(widget, options={}) {
if (options.changedProps) {
// alternate routine for small edits
var propNames = options.changedProps,
propValues = propNames.map(x => widget.props[x]),
linkedProps = []
Object.values(widget.nestedLinkedProps).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(widget.linkedProps).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(widget.linkedPropsValue).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(widget.oscReceivers).forEach(r => linkedProps = linkedProps.concat(r.propNames))
if (
// if non dynamic props have changed, skip this and use rebuild routine
!propNames.some(n => !widget.constructor.dynamicProps.includes(n))
) {
var edited = widget.updateProps(options.changedProps, null) || widget
if (
// if prop/osc listeners have changed (@{} / OSC{})
// refresh the widget's props cache and update linked props bindings
propValues.some(x => typeof x === 'string' && x.match(/OSC\{|@\{/))
|| propNames.some(n => linkedProps.includes(n))
) {
widget.createPropsCache()
}
if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
editor.select(edited)
}
return edited
}
}
var reuseChildren = options.reuseChildren !== false && widget instanceof Panel
// save state
if (stateManager.queueCounter === 0) {
sidepanelScroll = sidepanel.scrollTop
scrollState = {}
}
stateManager.incrementQueue()
var toSave = [widget]
if (!reuseChildren) {
toSave = toSave.concat(widget.getAllChildren())
}
for (let w of toSave) {
if (widgetManager.widgets[w.hash]) {
let id = w.getProp('id'),
value = w.getValue(),
valueProp = w.getProp('value')
stateManager.pushValueState(id, value)
if (valueProp !== '' && valueProp !== undefined) stateManager.pushValueOldProp(id, valueProp)
}
if (widgetManager.scrollingWidgets.indexOf(w.hash) > -1 && w.scroll) {
var s = w.scroll()
if (s[0] !== 0 || s[1] !== 0) {
scrollState[w.getProp('id')] = s
}
}
}
var children = undefined,
removedChildren = []
if (reuseChildren) {
children = [...widget.children]
if (options.removedIndexes) {
options.removedIndexes = options.removedIndexes.sort((a, b) => b - a)
for (let i of options.removedIndexes) {
removedChildren.push(children.splice(i, 1)[0])
}
}
if (options.addedIndexes) {
options.addedIndexes = options.addedIndexes.sort((a, b) => a - b)
for (let i of options.addedIndexes) {
children.splice(i, 0, null)
}
}
}
// get widget's index
var index = widget.parent.children.indexOf(widget)
// remove old widgets
var removedWidgets = reuseChildren ?
removedChildren.map(x => x.getAllChildren().concat(x)).concat(widget) :
widget.getAllChildren().concat(widget)
widgetManager.removeWidgets(removedWidgets)
// create new widget
var newWidget = parser.parse({
data: widget.props,
parent: widget.parent,
parentNode: widget.parentNode,
reCreateOptions: options.reCreateOptions,
children: children,
index: index
})
newWidget.container.parentNode.replaceChild(newWidget.container, widget.container)
if (newWidget.getProp('type') === 'tab') newWidget.parent.trigger('tab-created', [{widget: widget}])
if (newWidget.getProp('id') === 'root') DOM.get('.editor-root')[0].setAttribute('data-widget', newWidget.hash)
if (reuseChildren && !(newWidget instanceof Panel)) {
// remove remaining children if widget is not a container anymore
widgetManager.removeWidgets(widget.getAllChildren())
}
if (reuseChildren) {
// children don't listen to their parent's 'widget-created' event
// so we have to let them know it's been updated
widgetManager.trigger('prop-changed', [{
id: newWidget.getProp('id'),
props: [],
widget: newWidget,
options: {}
}])
}
resize.check(newWidget.container)
// restore state
stateManager.decrementQueue()
if (stateManager.queueCounter === 0) {
sidepanel.scrollTop = sidepanelScroll
for (let id in scrollState) {
for (let w of widgetManager.getWidgetById(id)) {
if (w.scroll) w.scroll(scrollState[id])
}
}
}
if (editor.selectedWidgets.includes(widget) && !options.preventSelect) {
editor.select(newWidget)
}
return newWidget
}
var fakeStore = {}
var incrementWidget = function(data, root){
if (!data) return
if (root !== false) {
fakeStore = {
id:[],
address:[]
}
}
var id = data.id,
address = data.address
if (id && address == '/'+id) {
data.address = 'auto'
} else if (address){
var addressref
while (fakeStore.address.indexOf(address) != -1 || widgetManager.getWidgetByAddress(addressref).length) {
address = address.replace(/([0-9]*)$/,function(m){
var n = parseInt(m)+1
n = isNaN(n)?1:n
return n
})
addressref = widgetManager.createAddressRef(null, data.preArgs,address)
}
fakeStore.address.push(address)
data.address = address
}
if (id) {
while (fakeStore.id.indexOf(id) != -1 || widgetManager.getWidgetById(id).length) {
id = id.replace(/([0-9]*)$/,function(m){
var n = parseInt(m)+1
n = isNaN(n)?1:n
return n
})
}
fakeStore.id.push(id)
data.id = id
}
if (data.widgets && data.widgets.length) {
for (let i in data.widgets) {
data.widgets[i] = incrementWidget(data.widgets[i], false)
}
}
if (data.tabs && data.tabs.length) {
for (let i in data.tabs) {
data.tabs[i] = incrementWidget(data.tabs[i], false)
}
}
return data
}
module.exports = {
updateWidget:updateWidget,
incrementWidget:incrementWidget
}
editor = require('./')
Panel = require('../widgets/containers/panel')

View file

@ -0,0 +1,32 @@
module.exports = {
diff: require('jsondiffpatch'),
diffToWidget: function(widget, diff) {
// traverse a diff patch and the associated widget
// to return the first node (widget and sub-patch) with actual changes
var children = diff.tabs || diff.widgets
if (children) {
var childrenKeys = Object.keys(children),
deletedChildren = childrenKeys.filter(x => typeof x === 'string' && x.match(/_[0-9]+/)),
changedChildren = childrenKeys.filter(x => !isNaN(x))
}
if (
!children ||
Array.isArray(children) || // 'tabs' or 'widgets' property created
deletedChildren.length || // 'tabs' or 'widgets' property created
changedChildren.length !== 1 || // children reordered (or same property edited in multiple widgets, but case ignored)
Array.isArray(children[changedChildren[0]]) // child item created
) {
return [widget, diff]
}
return module.exports.diffToWidget(widget.children[changedChildren[0]], children[changedChildren[0]])
}
}

View file

@ -0,0 +1,229 @@
var widgetCategories = require('../widgets/').categories,
{updateWidget} = require('./data-workers'),
widgetManager = require('../managers/widgets'),
{deepCopy} = require('../utils'),
{icon, Popup} = require('../ui/utils'),
locales = require('../locales')
module.exports = function editField(editor, widget, propName, defaultValue){
let dynamic = widget.constructor.dynamicProps.includes(propName),
disabled = widget.disabledProps.indexOf(propName) > -1,
error = widget.errors[propName]
let field = DOM.create(`
<div class="input-wrapper ${widget.errors[propName] ? 'error' : ''} ${disabled ? 'disabled' : ''}" title="${locales('editor_click_for_help')}">
<label class="btn ${error ? 'error' : ''}">${propName}</label>
</div>
`)
let input
if (propName !== 'widgets' && propName !== 'tabs') {
if (propName == 'type') {
if (widget.props.type == 'tab' || widget.props.type == 'root') {
field.classList.add('disabled')
field.appendChild(DOM.create(`<textarea class="input no-keybinding" name="${propName}" rows="1" disabled>${widget.props[propName]}</textarea>`))
return field
}
input = DOM.create('<select class="input no-keybinding"/>')
var innerHTML = ''
for (let category in widgetCategories) {
innerHTML += `<optgroup label="> ${category}">`
for (let type of widgetCategories[category]) {
innerHTML += `<option ${type == widget.props.type ? 'selected' : ''} value="${type}">${type}</option>`
}
innerHTML += '</optgroup>'
}
input.innerHTML = innerHTML
var wrapper = DOM.create('<div class="select-wrapper"></div>')
wrapper.appendChild(input)
field.appendChild(wrapper)
} else {
var value = typeof widget.props[propName] !== 'string' ?
JSON.stringify(widget.props[propName], null, ' ').replace(/\n\s\s\s\s/g, ' ').replace(/\n\s\s(\}|\])/g, ' $1') : widget.props[propName]
input = DOM.create(`<textarea class="input no-keybinding" name="${propName}" rows="${value.split('\n').length}">${value}</textarea>`)
DOM.addEventListener(input, ['input', 'focus'], ()=>{
input.setAttribute('rows',0)
input.setAttribute('rows', input.value.split('\n').length)
})
input.addEventListener('keydown', (e)=>{
if (e.keyCode == 13 && !e.shiftKey) {
e.preventDefault()
DOM.dispatchEvent(input, 'change')
}
})
if (defaultValue.type.includes('boolean')) {
let toggle = DOM.create(`
<span class="checkbox ${widget.getProp(propName) ? 'on' : ''}">
${icon('check')}
</span>
`)
toggle.addEventListener('click', ()=>{
input.value = !widget.getProp(propName)
DOM.dispatchEvent(input, 'change')
})
field.appendChild(toggle)
}
field.appendChild(input)
}
var lock
var onChange = ()=>{
if (lock) return
lock = true
input.blur()
var v
try {
v = JSON.parseFlex(input.value)
} catch(err) {
v = input.value
}
var newWidgets = []
for (var w of editor.selectedWidgets) {
w.props[propName] = v !== '' ? v : deepCopy(defaultValue.value)
newWidgets.push(updateWidget(w, {changedProps: [propName], preventSelect: editor.selectedWidgets.length > 1}))
}
editor.pushHistory()
if (newWidgets.length > 1) editor.select(newWidgets)
lock = false
}
input.addEventListener('change', onChange)
} else if (
(propName === 'widgets' && (!widget.props.tabs ||! widget.props.tabs.length)) ||
(propName === 'tabs' && (!widget.props.widgets ||! widget.props.widgets.length))
) {
if (editor.selectedWidgets.length > 1) return
var list = DOM.create('<ul></ul>')
for (var i in widget.props[propName]) {
list.appendChild(DOM.create(`
<li class="sortables" data-index="${i}">
<a class="btn small" data-action="select">${widget.props[propName][i].id}</a>
<span data-action="remove"><i class="fa fa-times"></i></span>
</li>
`))
}
list.appendChild(DOM.create(`
<li><a class="btn small" data-action="add">${icon('plus')}</a></li>
`))
list.addEventListener('click', (e)=>{
switch (e.target.getAttribute('data-action')) {
case 'select':
editor.select(widgetManager.getWidgetByElement(DOM.get(propName === 'widgets' ? widget.widget : widget.wrapper, '> .widget')[DOM.index(e.target.closest('li'))]))
break
case 'remove':
var index = DOM.index(e.target.closest('li'))
widget.props[propName].splice(index,1)
updateWidget(widget, {removedIndexes: [index] })
editor.pushHistory({removedIndexes: [index] })
break
case 'add':
widget.props[propName] = widget.props[propName] || []
widget.props[propName].push({})
updateWidget(widget, {addedIndexes: [widget.props[propName].length -1] })
editor.pushHistory({addedIndexes: [widget.props[propName].length -1] })
break
}
})
var $list = $(list)
$list.sortable({
items: '.sortables',
placeholder: 'sortable-placeholder btn small',
start:function(){$(this).sortable( 'refreshPositions' )},
update: function(e,ui){
var oldindex = $(ui.item).attr('data-index')
var index = $(ui.item).index()
widget.props[propName].splice(index, 0, widget.props[propName].splice(oldindex, 1)[0])
updateWidget(widget, {removedIndexes: [index, oldindex], addedIndexes: [index, oldindex]})
editor.pushHistory({removedIndexes: [index, oldindex], addedIndexes: [index, oldindex]})
}
})
input = DOM.create('<div class="input column"></div>')
input.appendChild(list)
field.appendChild(input)
}
var label = DOM.get(field, 'label')[0]
label.addEventListener('fast-click', ()=>{
var htmlHelp = Array.isArray(defaultValue.help) ? defaultValue.help.join('<br/><br/>').replace(/<br\/>-/g, '-') : defaultValue.help
htmlHelp = htmlHelp ? '<p class="help">' + htmlHelp.replace(/`([^`]*)`/g, '<code>$1</code>') + '</p>' : ''
var htmlError = error ? `<p class="error">${error}</p>` : '',
computedValue = propName !== 'tabs' && propName !== 'widgets' ? widget.getProp(propName) : ['...']
if (typeof computedValue === 'string') {
try {
computedValue = JSON.stringify(JSON.parse(computedValue), null, ' ')
} catch(e) {}
} else {
computedValue = JSON.stringify(computedValue, null, ' ')
}
new Popup({closable: true, title: `<span class="editor-help-title">${propName}</span>`, content: `
<div class="editor-help">
<p>Type: <code>${defaultValue.type}</code></p>
<p>Default: <code>${JSON.stringify(defaultValue.value)}</code></p>
<p>Dynamic: <code>${dynamic ? 'true' : 'false'}</code></p>
<p>Computed: <code class="pre">${computedValue}</code></p>
${htmlError}
${htmlHelp}
</div>
`})
})
if (input) {
return field
}
}

View file

@ -0,0 +1,842 @@
var {widgets} = require('../widgets/'),
editField = require('./edit-field'),
{updateWidget, incrementWidget} = require('./data-workers'),
keyboardJS = require('keyboardjs'),
{diff, diffToWidget} = require('./diff'),
widgetManager = require('../managers/widgets'),
{deepCopy} = require('../utils'),
macOs = (navigator.platform || '').match('Mac'),
SelectArea = require('./select-area'),
sessionManager
const HISTORY_SIZE = 50
var Editor = class Editor {
constructor() {
this.wrapper = DOM.create(`
<div class="editor-container">
<div class="form" id="editor-form">
</div>
</div>
`)
this.form = DOM.get(this.wrapper, '#editor-form')[0]
this.form.addEventListener('fast-click', (e)=>{
if (e.target.classList.contains('separator')) {
var name = e.target.getAttribute('data-name'),
foldedIndex = this.foldedCategories.indexOf(name)
e.target.parentNode.classList.toggle('folded', foldedIndex < 0)
if (foldedIndex > -1) {
this.foldedCategories.splice(foldedIndex, 1)
} else {
this.foldedCategories.push(name)
}
}
})
this.defaults = {}
for (var k in widgets) {
this.defaults[k] = widgets[k].defaults()
}
this.selectedWidgets = []
this.clipboard = null
this.idClipboard = null
this.enabled = false
this.enabledOnce = false
window.onbeforeunload = ()=>{
if (this.enabledOnce) return true
}
this.history = []
this.historyState = -1
this.historySession = null
this.foldedCategories = []
this.mousePosition = {x:0, y:0}
this.mouveMoveHandler = this.mouseMove.bind(this)
keyboardJS.withContext('editing', ()=>{
keyboardJS.bind('mod + z', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.undo()
})
keyboardJS.bind(['mod + y', 'mod + shift + z'], (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.redo()
})
keyboardJS.bind('mod + c', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.copyWidget()
})
keyboardJS.bind('mod + x', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.cutWidget()
})
keyboardJS.bind('mod + v', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.pasteWidget(this.mousePosition.x, this.mousePosition.y, false)
})
keyboardJS.bind('mod + shift + v', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.pasteWidget(this.mousePosition.x, this.mousePosition.y, true)
})
keyboardJS.bind(macOs ? 'backspace' : 'delete', (e)=>{
if (e.target.classList.contains('no-keybinding')) return
this.deleteWidget()
})
keyboardJS.bind(['alt + up', 'alt + down', 'alt + right', 'alt + left'], (e)=>{
if (e.target.classList.contains('no-keybinding')) return
if (!this.selectedWidgets.length) return
if (this.selectedWidgets[0].props.height === undefined && e.key.match(/Arrow(Up|Down)/)) return
if (this.selectedWidgets[0].props.width === undefined && e.key.match(/Arrow(Left|Right)/)) return
var deltaW = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
deltaH = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
if (e.shiftKey) {
deltaW *= 5
deltaH *= 5
}
this.resizeWidget(deltaW, deltaH)
})
keyboardJS.bind(['up', 'down', 'right', 'left'], (e)=>{
if (e.target.classList.contains('no-keybinding')) return
if (!this.selectedWidgets.length) return
if (this.selectedWidgets[0].props.top === undefined && e.key.match(/Arrow(Up|Down)/)) return
if (this.selectedWidgets[0].props.left === undefined && e.key.match(/Arrow(Left|Right)/)) return
var deltaX = e.key === 'ArrowLeft' ? -GRIDWIDTH : e.key === 'ArrowRight' ? GRIDWIDTH : 0,
deltaY = e.key === 'ArrowUp' ? -GRIDWIDTH : e.key === 'ArrowDown' ? GRIDWIDTH : 0
if (e.shiftKey) {
deltaX *= 5
deltaY *= 5
}
this.moveWidget(deltaX, deltaY)
})
keyboardJS.bind('mod + shift + a', (e)=>{
if (!this.selectedWidgets.length) return
if (e.target.classList.contains('no-keybinding')) return
this.unselect()
this.selectedWidgets = []
})
keyboardJS.bind('mod + a', (e)=>{
if (!this.selectedWidgets.length) return
if (e.target.classList.contains('no-keybinding')) return
var curWidget = this.selectedWidgets[0]
if (curWidget.parent !== widgetManager) {
this.select(curWidget.parent.children)
}
})
keyboardJS.bind(['mod + up','mod + down','mod + left' , 'mod + right'], (e)=>{
if (!this.selectedWidgets.length) return
if (e.target.classList.contains('no-keybinding')) return
var curWidget = this.selectedWidgets[0],
toSelect = null
if (e.key === 'ArrowUp' && curWidget.parent !== widgetManager) {
toSelect = curWidget.parent
} else if (e.key === 'ArrowDown') {
let toSelectList = [...curWidget.children]
if (toSelectList && toSelectList.length) {
toSelectList.sort((a,b) => a.container.offsetLeft>b.container.offsetLeft)
toSelect = toSelectList[0]
if (toSelect.container.classList.contains('not-editable')) {
toSelect = null
}
}
}
else if((e.key == 'ArrowLeft') || (e.key == 'ArrowRight')){
if (curWidget.parent === widgetManager) return
let toSelectList = [...curWidget.parent.children]
if (toSelectList && toSelectList.length) {
toSelectList.sort((a,b) => a.container.offsetLeft > b.container.offsetLeft)
var idx = toSelectList.indexOf(curWidget)
if (idx >= 0) {
var nextIdx = (idx + (e.key === 'ArrowLeft' ? -1 : 1 ) + toSelectList.length) % toSelectList.length
toSelect = toSelectList[nextIdx]
}
}
}
if (toSelect) {
this.select(toSelect)
}
})
keyboardJS.bind('f2', (e)=>{
var input = DOM.get(this.form, 'textarea[name="label"]')[0]
if (input) {
var folded = input.closest('.category.folded')
if (folded) DOM.dispatchEvent(DOM.get(folded, '.separator'), 'fast-click')
input.focus()
input.setSelectionRange(0, input.value.length)
}
})
})
keyboardJS.bind('mod + s', (e)=>{
e.preventDefault()
sessionManager.save()
})
keyboardJS.bind('mod + o', (e)=>{
e.preventDefault()
sessionManager.browse()
})
keyboardJS.bind('mod + e', (e)=>{
e.preventDefault()
if (this.enabled) {
this.disable()
} else {
if (sessionManager.session.length) this.enable()
}
})
this.selectarea = new SelectArea('.widget:not(.not-editable), .tablink', (elements)=>{
elements = elements.map(e => widgetManager.getWidgetByElement(e, ':not(.not-editable)')).filter(e => e)
for (var i in elements) {
this.select(elements[i], {multi:true, fromLasso:true})
}
this.select(this.selectedWidgets)
})
}
enable() {
EDITING = true
this.enabled = true
this.enabledOnce = true
DOM.get('.editor-root')[0].setAttribute('data-widget', DOM.get('.root-container')[0].getAttribute('data-widget'))
DOM.get('.editor-root')[0].classList.remove('disabled')
DOM.get('.disable-editor')[0].classList.remove('on')
DOM.get('.enable-editor')[0].classList.add('on')
document.body.classList.add('editor-enabled')
document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
GRIDWIDTH = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
var gridForm = DOM.create(`
<div class="form" id="grid-width-form">
<div class="separator"><span>Grid</span></div>
<div class="input-wrapper">
<label>Width</label>
<input class="input no-keybinding" type="number" id="grid-width-input" step="1" min="1" max="100" value="${GRIDWIDTH}"/>
</div>
</div>
`)
DOM.each(gridForm, '#grid-width-input', (input)=>{
DOM.addEventListener(input, 'keyup mouseup change mousewheel', (e)=>{
setTimeout(()=>{
var v = Math.max(Math.min(parseInt(input.value), 100), 1)
if (isNaN(v)) return
input.value = v
GRIDWIDTH = v
document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
document.documentElement.style.setProperty('--grid-width', GRIDWIDTH)
})
})
})
DOM.get(document, '.editor-menu')[0].appendChild(gridForm)
keyboardJS.setContext('editing')
document.body.addEventListener('mousemove', this.mouveMoveHandler)
this.selectarea.enable()
}
disable() {
EDITING = false
this.enabled = false
if (READ_ONLY) {
this.enable = ()=>{}
$('.editor-menu .btn').remove()
$('.editor-menu .title').html($('.editor-menu .title').html() + ' (disabled)').addClass('disabled')
return
}
this.unselect()
this.selectedWidgets = []
DOM.get('.editor-root')[0].classList.add('disabled')
DOM.get('.disable-editor')[0].classList.add('on')
DOM.get('.enable-editor')[0].classList.remove('on')
document.body.classList.remove('editor-enabled')
var gridForm = DOM.get('#grid-width-form')[0]
if (gridForm) gridForm.parentNode.removeChild(gridForm)
keyboardJS.setContext('global')
document.body.removeEventListener('mousemove', this.mouveMoveHandler)
this.selectarea.disable()
}
unselect() {
DOM.get('#editor')[0].innerHTML = ''
this.form.innerHTML = ''
DOM.each(document, '.editing', (element)=>{
element.classList.remove('editing')
})
$('.widget.ui-resizable').resizable('destroy')
$('.widget.ui-draggable').draggable('destroy').find('.ui-draggable-handle').remove()
}
select(widget, options={}){
if (!options.fromLasso) this.unselect()
if (Array.isArray(widget)) {
this.selectedWidgets = widget
} else if (options.multi) {
var sameLevel = false
while (!sameLevel && widget.parent !== widgetManager) {
let test = true
for (var w of this.selectedWidgets) {
if (w.parent !== widget.parent) test = false
}
sameLevel = test
if (!sameLevel) widget = widget.parent
}
if (!this.selectedWidgets.includes(widget) && sameLevel) {
this.selectedWidgets.push(widget)
} else if (sameLevel && !options.fromLasso){
this.selectedWidgets.splice(this.selectedWidgets.indexOf(widget), 1)
}
} else {
if (!options.refresh && (widget.container.classList.contains('editing'))) return
this.selectedWidgets = [widget]
}
if (this.selectedWidgets.length > 0 && !options.fromLasso) {
this.createEditForm()
this.createSelectionBlock()
}
}
createEditForm(){
var widget = this.selectedWidgets[0],
props = this.defaults[widget.props.type]
this.form.appendChild(DOM.create(`
<div class="separator">
${this.selectedWidgets.length > 1 ? '<span class="accent">Multiple Widgets</span>' : '<span>Widget</span>' }
</div>
`))
let category
for (let propName in props) {
let field,
shared = true
for (var w of this.selectedWidgets) {
if (this.defaults[w.props.type][propName] === undefined) {
shared = false
}
}
if (!shared) continue
if (propName.indexOf('_') === 0 && propName !== '_props') {
if (category) this.form.appendChild(category)
category = DOM.create(`<div class="category ${this.foldedCategories.indexOf(props[propName]) > -1 ? 'folded' : ''}"></div>`)
field = DOM.create(`<div class="separator" data-name="${props[propName]}"><span>${props[propName]}</span></div>`)
} else if (widget.props[propName] === undefined) {
continue
} else {
field = editField(this, widget, propName, props[propName])
if (!field) continue
}
if (category) {
category.appendChild(field)
} else {
this.form.appendChild(field)
}
}
if (category) this.form.appendChild(category)
this.wrapper.appendChild(this.form)
DOM.get('#editor')[0].appendChild(this.wrapper)
}
createSelectionBlock(){
DOM.each(document, '.editing', (element)=>{
element.classList.remove('editing')
})
for (let widget of this.selectedWidgets) {
DOM.each(document, `[data-widget="${widget.hash}"]`, (item)=>{
item.classList.add('editing')
})
}
var widget = this.selectedWidgets[0]
if (widget.props.height !== undefined || widget.props.width !== undefined) {
let $container = $(widget.container)
$container.resizable({
handles: 's, e, se',
helper: 'ui-helper',
resize: (event, ui)=>{
ui.size.height = Math.round(ui.size.height / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
ui.size.width = Math.round(ui.size.width / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
},
stop: (event, ui)=>{
var deltaH = ui.size.height - ui.originalSize.height,
deltaW = ui.size.width - ui.originalSize.width
this.resizeWidget(deltaW, deltaH, ui)
},
grid: [GRIDWIDTH * PXSCALE, GRIDWIDTH * PXSCALE]
})
}
if (widget.props.top !== undefined) {
let $container = $(widget.container)
$container.draggable({
cursor:'-webkit-grabbing',
drag: (event, ui)=>{
ui.position.top = Math.round(ui.position.top / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
ui.position.left = Math.round(ui.position.left / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH * PXSCALE
},
stop: (event, ui)=>{
event.preventDefault()
var deltaX = (ui.helper.position().left + $container.parent().scrollLeft()) / PXSCALE - widget.container.offsetLeft / PXSCALE,
deltaY = (ui.helper.position().top + $container.parent().scrollTop()) / PXSCALE - widget.container.offsetTop / PXSCALE
this.moveWidget(deltaX, deltaY)
ui.helper.remove()
},
handle:'.ui-draggable-handle, > .label',
grid: [GRIDWIDTH * PXSCALE, GRIDWIDTH * PXSCALE],
helper:()=>{
return $('<div class="ui-helper"></div>').css({height:$container.outerHeight(),width:$container.outerWidth()})
}
}).append('<div class="ui-draggable-handle"></div>')
}
}
mouseMove(e) {
this.mousePosition.x = Math.round((e.offsetX + e.target.scrollLeft) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH,
this.mousePosition.y = Math.round((e.offsetY + e.target.scrollTop) / (GRIDWIDTH * PXSCALE)) * GRIDWIDTH
}
copyWidget() {
if (!this.selectedWidgets.length) return
var data = this.selectedWidgets.map((w)=>w.props),
type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget'
if (type !== 'widget') return
this.clipboard = JSON.stringify(data)
if (data.length == 1) {
this.idClipboard = this.selectedWidgets[0].getProp('id')
} else {
this.idClipboard =null
}
}
cutWidget() {
if (!this.selectedWidgets.length) return
var type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
parent = this.selectedWidgets[0].parent,
index = this.selectedWidgets.map(w => parent.children.indexOf(w)).sort((a,b)=>{return b-a}),
data = this.selectedWidgets.map((w)=>w.props),
removedIndexes = []
if (type !== 'widget') return
this.clipboard = JSON.stringify(data)
if (data.length == 1) {
this.idClipboard = this.selectedWidgets[0].getProp('id')
} else {
this.idClipboard =null
}
for (var i of index) {
removedIndexes.push(i)
parent.props.widgets.splice(i,1)
}
this.select(updateWidget(parent, {
preventSelect: true,
removedIndexes
}))
this.pushHistory({removedIndexes})
}
pasteWidget(x, y, increment) {
if (!this.selectedWidgets.length || this.clipboard === null) return
var data = this.selectedWidgets.map((w)=>w.props)
var pastedData = JSON.parse(this.clipboard),
minTop = Infinity,
minLeft = Infinity
for (let i in pastedData) {
if (increment) pastedData[i] = incrementWidget(pastedData[i])
if (!isNaN(pastedData[i]).top && pastedData[i].top < minTop) {
minTop = pastedData[i].top
}
if (!isNaN(pastedData[i]).left && pastedData[i].left < minLeft) {
minLeft = pastedData[i].left
}
}
for (let i in pastedData) {
if (!isNaN(pastedData[i].left)) pastedData[i].left = pastedData[i].left - minLeft + x
if (!isNaN(pastedData[i].top)) pastedData[i].top = pastedData[i].top - minTop + y
}
data[0].widgets = data[0].widgets || []
data[0].widgets = data[0].widgets.concat(pastedData)
var indexes = {addedIndexes: []}
for (let i = 0; i < pastedData.length; i++) {
indexes.addedIndexes.push(data[0].widgets.length - 1 - i )
}
updateWidget(this.selectedWidgets[0], indexes)
this.pushHistory(indexes)
}
pasteWidgetAsClone(x, y) {
if (!this.selectedWidgets.length) return
if (this.clipboard === null || !(this.idClipboard && widgetManager.getWidgetById(this.idClipboard).length)) return
var data = this.selectedWidgets.map((w)=>w.props)
var clone = {type: 'clone', widgetId: this.idClipboard},
pastedData = JSON.parse(this.clipboard)
clone.width = pastedData.width
clone.height = pastedData.width
clone.css = pastedData.css
clone.left = x
clone.top = y
data[0].widgets = data[0].widgets || []
data[0].widgets.push(clone)
var indexes = {addedIndexes: [data[0].widgets.length -1]}
updateWidget(this.selectedWidgets[0], indexes)
this.pushHistory(indexes)
}
deleteWidget() {
if (!this.selectedWidgets.length) return
var type = this.selectedWidgets[0].props.type == 'tab' ? 'tab' : 'widget',
parent = this.selectedWidgets[0].parent,
index = this.selectedWidgets.map(w => parent.children.indexOf(w)).sort((a,b)=>{return b-a}),
removedIndexes = []
if (this.selectedWidgets[0].getProp('id') === 'root') return
if (type === 'widget') {
for (let i of index) {
removedIndexes.push(i)
parent.props.widgets.splice(i,1)
}
} else {
for (let i of index) {
removedIndexes.push(i)
parent.props.tabs.splice(i,1)
}
}
this.select(updateWidget(parent, {
preventSelect: true,
removedIndexes
}))
this.pushHistory({removedIndexes})
}
resizeWidget(deltaW, deltaH, ui) {
if (!this.selectedWidgets.length) return
var newWidgets = []
for (var i = 0; i < this.selectedWidgets.length; i++) {
let w = this.selectedWidgets[i],
nW, nH
if (i === 0 && ui) {
nW = ui.originalSize.width + deltaW
nH = ui.originalSize.height + deltaH
} else {
nW = w.container.offsetWidth + deltaW
nH = w.container.offsetHeight + deltaH
}
if (w.props.width !== undefined) {
var newWidth = Math.max(nW, GRIDWIDTH) / PXSCALE
if (typeof w.props.width === 'string' && w.props.width.indexOf('%') > -1) {
w.props.width = (100 * PXSCALE * newWidth / w.container.parentNode.offsetWidth).toFixed(2) + '%'
} else {
w.props.width = newWidth
}
}
if (w.props.height !== undefined) {
var newHeight = Math.max(nH, GRIDWIDTH) / PXSCALE
if (typeof w.props.height === 'string' && w.props.height.indexOf('%') > -1) {
w.props.height = (100 * PXSCALE * newHeight / w.container.parentNode.offsetHeight).toFixed(2) + '%'
} else {
w.props.height = newHeight
}
}
if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {changedProps: ['width', 'height'], preventSelect: this.selectedWidgets.length > 1}))
}
this.pushHistory()
if (newWidgets.length > 1) this.select(newWidgets, {preventSelect: this.selectedWidgets.length > 1})
}
moveWidget(deltaX, deltaY) {
if (!this.selectedWidgets.length) return
var newWidgets = []
for (var w of this.selectedWidgets) {
var newTop = w.container.offsetTop / PXSCALE + deltaY
if (typeof w.props.top === 'string' && w.props.top.indexOf('%') > -1) {
w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.offsetHeight).toFixed(2) + '%'
} else {
w.props.top = newTop
}
var newLeft = w.container.offsetLeft / PXSCALE + deltaX
if (typeof w.props.left === 'string' && w.props.left.indexOf('%') > -1) {
w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2) + '%'
} else {
w.props.left = newLeft
}
newWidgets.push(updateWidget(w, {changedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
}
this.pushHistory()
if (newWidgets.length > 1) this.select(newWidgets)
}
pushHistory(indexes) {
if (this.historyState > -1) {
this.history.splice(0, this.historyState + 1)
this.historyState = -1
}
var d = diff.diff(this.historySession, sessionManager.session)
if (d) {
diff.patch(this.historySession, deepCopy(d))
this.history.unshift([deepCopy(d), indexes])
if (this.history.length > HISTORY_SIZE) this.history.pop()
}
}
clearHistory() {
this.history = []
this.historyState = -1
this.historySession = deepCopy(sessionManager.session)
}
undo() {
if (this.historyState === this.history.length - 1) return
this.historyState += 1
var [patch, indexes] = this.history[this.historyState],
d1 = deepCopy(patch),
d2 = deepCopy(patch)
diff.unpatch(this.historySession, d1)
diff.unpatch(sessionManager.session, d2)
this.updateWidgetFromPatch(patch, indexes ? {
addedIndexes: deepCopy(indexes.removedIndexes),
removedIndexes: deepCopy(indexes.addedIndexes),
} : undefined)
}
redo() {
if (this.historyState === -1) return
var [patch, indexes] = this.history[this.historyState],
d1 = deepCopy(patch),
d2 = deepCopy(patch)
diff.patch(this.historySession, d1)
diff.patch(sessionManager.session, d2)
this.updateWidgetFromPatch(patch, indexes ? {
addedIndexes: deepCopy(indexes.addedIndexes),
removedIndexes: deepCopy(indexes.removedIndexes),
} : undefined)
this.historyState -= 1
}
updateWidgetFromPatch(patch, indexes) {
var [widget, subpatch] = diffToWidget(widgetManager.getWidgetById('root')[0], patch[0]),
options = {}
if (indexes) {
options = {...indexes}
} else {
options.changedProps = Object.keys(subpatch)
options.reuseChildren = false
}
updateWidget(widget, options)
}
}
var editor = new Editor()
module.exports = editor
require('./context-menu')
sessionManager = require('../managers/session')

View file

@ -0,0 +1,127 @@
class SelectArea {
constructor(selector, callback){
this.startX = 0
this.startY = 0
this.curX = 0
this.curY = 0
this.rectCoords = [0, 0, 0, 0]
this.rectSize = [0, 0]
this.elements = []
this.rect = DOM.create('<div class="select-area hidden"></div>')
document.body.appendChild(this.rect)
this.selector = selector
this.callback = callback
this.bindedMousedown = this.mousedown.bind(this)
this.bindedMousemove = this.mousemove.bind(this)
this.bindedMouseup = this.mouseup.bind(this)
}
mousedown(e) {
if (!e.shiftKey || event.button === 2) return
this.startX = this.curX = e.clientX
this.startY = this.curY = e.clientY
this.down = true
this.updateRect()
}
mousemove(e) {
if (!this.down) return
e.preventDefault()
e.stopPropagation()
this.curX = e.clientX
this.curY = e.clientY
this.updateRect()
}
mouseup(e) {
if (!this.down) return
this.down = false
if (this.rectSize[0] > 0 && this.rectSize[1] > 0) {
this.callback(this.getElements())
this.rect.classList.add('hidden')
}
this.elements = []
}
updateRect() {
var x0 = Math.min(this.startX, this.curX),
y0 = Math.min(this.startY, this.curY),
x1 = Math.max(this.startX, this.curX),
y1 = Math.max(this.startY, this.curY),
w = x1 - x0,
h = y1 - y0
if (w < 1 || h < 1) {
this.rect.classList.add('hidden')
} else {
this.rect.classList.remove('hidden')
this.rect.setAttribute('style', `width:${w}px;height:${h}px;left:${x0}px;top:${y0}px`)
}
this.rectSize = [w, h]
this.rectCoords = [x0, x1, y0, y1]
}
getElements(){
var [x0, x1, y0, y1] = this.rectCoords,
startEl = document.elementFromPoint(this.startX, this.startY),
elements = [startEl]
this.elements = DOM.each(document, this.selector, (el)=>{
var {left, right, top, bottom} = el.getBoundingClientRect()
if (!(
left > x1 ||
right < x0 ||
top > y1 ||
bottom < y0
)) {
if (el !== startEl) elements.push(el)
}
})
// slower implementation...
// for (var x = x0; x <= x1; x += 10) {
// for (var y = y0; y <= y1; y += 10) {
// var el = document.elementFromPoint(x, y)
// if (elements.indexOf(el) < 0) elements.push(el)
// }
// }
return elements
}
enable() {
document.addEventListener('mousedown', this.bindedMousedown)
document.addEventListener('mousemove', this.bindedMousemove, true)
document.addEventListener('mouseup', this.bindedMouseup)
}
disable() {
document.removeEventListener('mousedown', this.bindedMousedown)
document.removeEventListener('mousemove', this.bindedMousemove, true)
document.removeEventListener('mouseup', this.bindedMouseup)
}
}
module.exports = SelectArea

View file

@ -0,0 +1,54 @@
const iOS = require('../ui/ios')
var longTouchTimer = false,
clearLongTouchTimer = function() {
if (longTouchTimer) {
clearTimeout(longTouchTimer)
longTouchTimer = false
}
}
document.body.setAttribute('oncontextmenu', 'return false')
function mouseToFastClick(event) {
if (event.touchPunch) return
if (event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) return
if (event.button == 2) event.preventDefault()
var e = event
var name = event.button == 2 ? 'fast-right-click' : 'fast-click'
DOM.dispatchEvent(e.target, name, e)
}
function touchToFastClick(event) {
var e = event.changedTouches[0]
DOM.dispatchEvent(e.target, 'fast-click', e)
if (e.preventOriginalEvent) event.preventDefault()
longTouchTimer = setTimeout(()=>{
var off = DOM.offset(e.target)
e.offsetX = e.pageX - off.left
e.offsetY = e.pageY - off.top
DOM.dispatchEvent(e.target, 'fast-right-click', e)
clearLongTouchTimer()
}, 600)
}
if (!iOS) document.addEventListener('mousedown', mouseToFastClick, true)
document.addEventListener('touchstart', touchToFastClick, {passive: false, capture: true})
DOM.addEventListener(document, 'touchend touchmove touchcancel', clearLongTouchTimer)

View file

@ -0,0 +1,305 @@
const {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} = require('./utils')
const iOS = require('../ui/ios')
var targets = {},
previousPointers = {}
function pointerDownHandler(event) {
if (event.capturedByEditor || event.touchPunch) return
if (!event.multitouch) {
for (var i in targets) {
if (targets[i] == event.target) return
}
}
event = normalizeDragEvent(event)
targets[event.pointerId] = event.target
if (event.traversing === TRAVERSING_SAMEWIDGET) {
event.traversingType = event.target.closest('.drag-event')._drag_widget.getProp('type')
console.log(event.traversingType)
}
previousPointers[event.pointerId] = event
triggerWidgetEvent(targets[event.pointerId], 'draginit', event)
}
function pointerMoveHandler(event) {
event = normalizeDragEvent(event, previousPointers[event.pointerId])
event.stopPropagation = true
if (event.traversing) {
var previousTarget = targets[event.pointerId],
target = event.isTouch ?
document.elementFromPoint(event.clientX, event.clientY)
: event.target
if (target) target = target.closest('.drag-event')
if (
target && event.traversing === TRAVERSING_SAMEWIDGET
&& event.traversingType !== target._drag_widget.getProp('type')
) {
console.log(event.traversingType, target._drag_widget.getProp('type'))
target = null
}
if (target && event.isTouch) {
resetEventOffset(event, target)
}
if (previousTarget !== target) {
triggerWidgetEvent(previousTarget, 'dragend', event)
}
if (target) {
if (event.traversingContainer.contains(target)) {
triggerWidgetEvent(target, previousTarget !== target ? 'draginit' : 'drag', event)
}
}
targets[event.pointerId] = target
} else {
triggerWidgetEvent(targets[event.pointerId], 'drag', event)
}
previousPointers[event.pointerId] = event
}
function pointerUpHandler(event) {
event = normalizeDragEvent(event, previousPointers[event.pointerId])
triggerWidgetEvent(targets[event.pointerId], 'dragend', event)
delete targets[event.pointerId]
delete previousPointers[event.pointerId]
}
// Move / Up Filter
function pointerMoveFilter(event) {
if (targets[event.pointerId] !== undefined) {
pointerMoveHandler.call(targets[event.pointerId], event)
}
}
function pointerUpFilter(event) {
if (targets[event.pointerId] !== undefined) {
pointerUpHandler.call(targets[event.pointerId], event)
delete targets[event.pointerId]
}
}
// Mouse events wrappers
function mouseMultiWrapper(event) {
mouseDownCapture(event, true)
}
function mouseDownCapture(event, multitouch) {
if ((event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) || event.button == 2) return
event.pointerId = 'mouse'
event.multitouch = multitouch
pointerDownHandler(event)
}
function mouseMoveCapture(event) {
event.pointerId = 'mouse'
event.inertia = event.ctrlKey ? 10 : 1
pointerMoveFilter(event)
}
function mouseUpCapture(event){
if ((event.sourceCapabilities && event.sourceCapabilities.firesTouchEvents) || event.button == 2) return
event.pointerId = 'mouse'
pointerUpFilter(event)
}
// Touch events wrappers
function touchMultiWrapper(event) {
touchDownCapture(event, true)
}
function touchDownCapture(event, multitouch) {
event.preventDefault()
for (var i in event.changedTouches) {
if (isNaN(i) || !event.changedTouches[i]) continue
var touchEvent = event.changedTouches[i]
if (event.traversing) {
touchEvent.traversing = event.traversing
touchEvent.traversingContainer = event.traversingContainer
}
touchEvent.pointerId = touchEvent.identifier
touchEvent.multitouch = multitouch
pointerDownHandler(touchEvent)
}
}
function touchMoveCapture(event) {
for (var i in event.changedTouches) {
if (isNaN(i) || !event.changedTouches[i]) continue
var touchEvent = event.changedTouches[i]
var fingers = 0
for (var j in event.touches) {
if (event.touches[j].target && event.touches[j].target.isSameNode(touchEvent.target)) {
fingers += 1
if (fingers == 2) {
touchEvent.inertia = 10
break
}
}
}
touchEvent.pointerId = touchEvent.identifier
pointerMoveFilter(touchEvent)
}
}
function touchUpCapture(event) {
for (var i in event.changedTouches) {
if (isNaN(i) || !event.changedTouches[i]) continue
var touchEvent = event.changedTouches[i]
touchEvent.pointerId = touchEvent.identifier
pointerUpFilter(touchEvent)
}
}
// Callback trigger
function triggerWidgetEvent(target, name, event) {
if (target !== null && target._drag_widget) {
target._drag_widget.trigger(name, [event])
} else if (target !== null) {
triggerWidgetEvent(target.closest('.drag-event'), name, event)
}
}
// init
DOM.ready(()=>{
if (!iOS) document.addEventListener('mousemove', mouseMoveCapture, true)
if (!iOS) document.addEventListener('mouseup', mouseUpCapture, true)
document.addEventListener('touchmove', touchMoveCapture, true)
DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
})
module.exports = {
setup: function(options) {
if (
this._customBindings['drag'].bindings !== 0 ||
this._customBindings['draginit'].bindings !== 0 ||
this._customBindings['dragend'].bindings !== 0 ||
!options
) {
return
}
var {element, multitouch} = options
element._drag_widget = this
element.style.touchAction = 'none'
element.classList.add('drag-event')
if (multitouch) {
element.addEventListener('touchstart', touchMultiWrapper, false)
if (!iOS) element.addEventListener('mousedown', mouseMultiWrapper)
} else {
element.addEventListener('touchstart', touchDownCapture, false)
if (!iOS) element.addEventListener('mousedown', mouseDownCapture)
}
},
teardown: function(options) {
if (
this._customBindings['drag'].bindings !== 0 ||
this._customBindings['draginit'].bindings !== 0 ||
this._customBindings['dragend'].bindings !== 0 ||
!options
) {
return
}
var {element, multitouch} = options
delete element._drag_widget
element.style.touchAction = ''
element.classList.remove('drag-event')
if (multitouch) {
element.removeEventListener('touchstart', touchMultiWrapper, false)
if (!iOS) element.removeEventListener('mousedown', mouseMultiWrapper)
} else {
element.removeEventListener('touchstart', touchDownCapture, false)
if (!iOS) element.removeEventListener('mousedown', mouseDownCapture)
}
},
enableTraversingGestures: function(element, options={}) {
if (element._traversing) return
var traversing = options.smart ? TRAVERSING_SAMEWIDGET : true
element._traversing = traversing
function makeEventTraversing(event) {
if (event.ctrlKey) return
event.traversing = traversing
if (!event.traversingContainer) event.traversingContainer = element
}
if (!iOS) element.addEventListener('mousedown', makeEventTraversing, true)
element.addEventListener('touchstart', makeEventTraversing, true)
element.addEventListener('disableTraversingGestures', ()=>{
if (!iOS) element.removeEventListener('mousedown', makeEventTraversing, true)
element.removeEventListener('touchstart', makeEventTraversing, true)
})
},
disableTraversingGestures: function(element) {
if (!element._traversing) return
delete element._traversing
DOM.dispatchEvent(element, 'disableTraversingGestures')
}
}

View file

@ -0,0 +1,117 @@
var WolfyEventEmitter = require('wolfy87-eventemitter'),
customEvents = {}
customEvents['draginit'] = customEvents['drag'] = customEvents['dragend'] = require('./drag')
customEvents['resize'] = require('./resize')
module.exports = class EventEmitter extends WolfyEventEmitter {
constructor() {
super()
this._customBindings = {}
this._contextEvents = {}
for (var evt in customEvents) {
this._customBindings[evt] = {
bindings: 0
}
}
}
emitEvent(evt, args) {
// Event bubbling
super.emitEvent(evt, args)
if (args[0] && !args[0].stopPropagation) {
if (this.parent) this.parent.emitEvent(evt, args)
}
return this
}
addListener(evt, listener, options) {
// Custom event setup
if (
customEvents.hasOwnProperty(evt) &&
typeof customEvents[evt].setup === 'function'
) {
if (this._customBindings[evt].bindings === 0) {
this._customBindings[evt].options = options
customEvents[evt].setup.call(this, options)
}
this._customBindings[evt].bindings += 1
}
if (options && options.context) {
var hash = options.context.hash
if (!this._contextEvents[hash]) this._contextEvents[hash] = []
this._contextEvents[hash].push([evt, listener])
}
super.addListener(evt, listener)
return this
}
removeListener(evt, listener) {
// Custom event teardown
if (
customEvents.hasOwnProperty(evt) &&
typeof customEvents[evt].teardown === 'function' &&
this._customBindings[evt].bindings !== 0
) {
this._customBindings[evt].bindings -= 1
if (this._customBindings[evt].bindings === 0 || !listener) {
var options = this._customBindings[evt].options
customEvents[evt].teardown.call(this, options)
}
}
// Remove all listeners is none specified
if (listener) {
super.removeListener(evt, listener)
} else {
this.removeEvent(evt)
}
return this
}
removeEventContext(context, evt, listener) {
var events = this._contextEvents[context.hash]
if (events) {
for (var i = 0; i < events.length; i++) {
if (evt && evt !== events[i][0]) continue
if (listener && listener !== events[i][1]) continue
this.removeListener(events[i][0], events[i][1])
}
if (!this._contextEvents[context.hash].length) delete this._contextEvents[context.hash]
}
}
}

View file

@ -0,0 +1,64 @@
var elements = []
function checkResizes(context, force){
// Iterate over all elements to which the 'resize' event is bound.
var resizedElems = [],
cachedStyles = []
for (let i = elements.length - 1; i >= 0; i--) {
var elem = elements[i]
if (!context.contains(elem)) continue
var style = window.getComputedStyle(elem),
width = parseInt(style['width']) - parseInt(style['padding-left']) - parseInt(style['padding-right']),
height = parseInt(style['height']) - parseInt(style['padding-top']) - parseInt(style['padding-bottom'])
if (!width || !height) continue
// If element size has changed since the last time, update the element
// data store and trigger the 'resize' event.
if (force || width != elem.resizedataw || height != elem.resizedatah) {
elem.resizedataw = width
elem.resizedatah = height
resizedElems.push(elem)
cachedStyles.push(style)
}
}
for (let i = resizedElems.length - 1; i >= 0; i--) {
resizedElems[i]._resize_widget.trigger('resize', [{
width: resizedElems[i].resizedataw,
height: resizedElems[i].resizedatah,
style:cachedStyles[i],
stopPropagation: true
}])
}
}
window.addEventListener('resize', ()=>{checkResizes(document)})
module.exports = {
setup: function(options) {
if (!options) return
if (elements.indexOf(options.element) == -1) {
elements.push(options.element)
options.element._resize_widget = this
}
},
teardown: function(options) {
if (!options) return
if (elements.indexOf(options.element) != -1) {
elements.splice(elements.indexOf(options.element), 1)
delete options.element._resize_widget
}
},
check: checkResizes
}

View file

@ -0,0 +1,92 @@
const Touch = window.Touch || class Touch {}
module.exports = {
fix: function(e) {
return {
target: e.target,
offsetX: e.offsetX,
offsetY: e.offsetY,
pageX: e.pageX,
pageY: e.pageY,
clientX: e.clientX,
clientY: e.clientY,
movementX: e.movementX,
movementY: e.movementY,
pointerId: e.pointerId,
pointerType: e.pointerType,
button: e.button,
ctrlKey: e.ctrlKey,
shiftKey: e.shiftKey,
inertia: e.multitouch ? 1 : e.inertia,
traversing: e.traversing,
traversingType: e.traversingType,
traversingContainer: e.traversingContainer,
multitouch: e.multitouch,
isTouch: e instanceof Touch
}
},
normalizeDragEvent: function(event, previousEvent) {
event = module.exports.fix(event)
if (event.movementX === undefined) {
event.movementX = previousEvent ? event.pageX - previousEvent.pageX : 0
event.movementY = previousEvent ? event.pageY - previousEvent.pageY : 0
}
if (event.isTouch && !previousEvent) {
module.exports.resetEventOffset(event, event.target)
} else if (event.isTouch && previousEvent) {
event.offsetX = previousEvent.offsetX + event.movementX
event.offsetY = previousEvent.offsetY + event.movementY
}
if (event.inertia === undefined) {
event.inertia = 1
}
if (previousEvent) {
if (previousEvent.traversing) {
event.traversing = previousEvent.traversing
event.traversingType = previousEvent.traversingType
event.traversingContainer = previousEvent.traversingContainer
}
if (previousEvent.multitouch) {
event.multitouch = previousEvent.multitouch
event.inertia = 1
}
}
return event
},
resetEventOffset: function(event, target) {
var off = DOM.offset(target)
event.offsetX = event.pageX - off.left
event.offsetY = event.pageY - off.top
},
TRAVERSING_SAMEWIDGET: 1
}

41
src/client/app/globals.js Normal file
View file

@ -0,0 +1,41 @@
window.ARGV = {}
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, (s,k,v)=>{
ARGV[k]=v
})
window.ELECTRON_FULLSCREEN = window.ELECTRON_FULLSCREEN || false
window.LANG = (ARGV.lang || navigator.language || '').substr(0, 2).toLowerCase()
window.PACKAGE = require('../../../app/package.json')
document.title = PACKAGE.productName + ' v' + PACKAGE.version
window.LOADING = null
window.CLIPBOARD = null
window.READ_ONLY = false
window.EDITING = false
window.GRIDWIDTH = 10
window.CANVAS_FRAMERATE = parseFloat(ARGV.framerate || 60)
window.CANVAS_SCALING = parseFloat(ARGV.forceHdpi) || ( ARGV.hdpi ? window.devicePixelRatio : 1 )
window.INITIALZOOM = ARGV.zoom ? ARGV.zoom : 1
window.PXSCALE = INITIALZOOM
document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
window.DOUBLE_TAP_TIME = ARGV.doubletap ? ARGV.doubletap : 375
window.JSON.parseFlex = require('json5').parse
window.DOM = require('./dom')
window.$ = require('jquery/dist/jquery.slim.min.js')
require('../libs/jquery.ui')
require('../libs/jquery.touch')
require('cardinal-spline-js/curve.min.js')

View file

@ -0,0 +1,168 @@
var utils = require('../ui/utils'),
osc = require('../osc'),
session = require('../managers/session'),
widgetManager = require('../managers/widgets'),
state = require('../managers/state'),
editor = require('../editor/'),
locales = require('../locales'),
{deepCopy} = require('../utils'),
sidepanel = require('../ui/sidepanel'),
{TRAVERSING_SAMEWIDGET} = require('../events/utils'),
{enableTraversingGestures} = require('../events/drag'),
ipc = require('./')
module.exports = {
bundle: function(data) {
for (let i in data) {
osc.receive(data[i])
}
},
receiveOsc: function(data){
osc.receive(data)
},
connected:function(){
LOADING.close()
},
sessionList: function(data){
session.list(data)
},
sessionOpen: function(data){
session.open(data)
},
sessionNew: function(){
session.create()
},
stateLoad: function(data){
state.set(data.state, data.send)
},
stateSend:function(){
var p = utils.loading(locales('loading_newclient'))
setTimeout(function(){
osc.syncOnly = true
state.send()
osc.syncOnly = false
p.close()
},150)
},
editorDisable: function(data){
editor.disable(data.permanent)
},
error: function(data){
new utils.Popup({title: utils.icon('exclamation-triangle') + '&nbsp; ' + locales('error'), content: data, closable:true})
},
reloadCss: function(){
var queryString = '?reload=' + Date.now()
DOM.each(document, 'link[rel="stylesheet"][hot-reload]', (el)=>{
el.href = el.href.replace(/\?.*|$/, queryString)
})
setTimeout(()=>{
var root = widgetManager.getWidgetById('root')[0]
if (root) root.reCreateWidget()
},100)
GRIDWIDTH = getComputedStyle(document.documentElement).getPropertyValue('--grid-width')
},
readOnly: function(){
READ_ONLY = true
},
reload: function(){
var id = Math.random(),
search = location.search,
query = 'backupId=' + id
// disable editor's warning
window.onbeforeunload = null
if (!session.session.length) {
window.location.href = window.location.href
return
}
try {
// store session & state backup
ipc.send('storeBackup', {
backupId: id,
session: session.session,
state: state.get(),
history: editor.history,
historyState: editor.historyState,
editorEnabled: editor.enabled,
sidepanelOpened: document.getElementById('sidepanel').classList.contains('sidepanel-open'),
traversing: document.getElementById('container')._traversing
})
// reload page and hold backup id
if (search) {
search = search.replace(/backupId=[^&]*/, query)
} else {
search += '?' + query
}
window.location.search = search
} catch(e) {
window.location.href = window.location.href
}
},
loadBackup: function(data) {
session.load(data.session, ()=>{
state.set(data.state, false)
editor.historySession = deepCopy(data.session)
editor.history = data.history
editor.historyState = data.historyState
if (data.editorEnabled) editor.enable()
if (data.sidepanelOpened) sidepanel.open()
if (data.traversing === TRAVERSING_SAMEWIDGET) {
DOM.get('.traversingSmart')[0].click()
} else if (data.traversing) {
DOM.get('.traversingEnable')[0].click()
}
ipc.send('deleteBackup', data.backupId)
})
}
}

143
src/client/app/ipc/index.js Normal file
View file

@ -0,0 +1,143 @@
var EventEmitter = require('wolfy87-eventemitter'),
uuid = require('nanoid/generate')('0123456789abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
var reconnectInterval = 5000,
hearbeatInterval = 25000,
hearbeatTimeout = 5000
class Ipc extends EventEmitter {
constructor() {
super()
this.socket = null
this.queue = []
this.reconnect = undefined
this.hearbeat = undefined
this.hearbeatTimeout = undefined
this.on('pong', ()=>{
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
})
this.on('ping', ()=>{
this.socket.send('["pong"]')
})
this.open()
}
init() {
var callbacks = require('./callbacks')
for (let i in callbacks) {
let callback = callbacks[i]
this.on(i, (data)=>{
callback(data)
})
}
}
open() {
this.socket = new WebSocket('ws://' + window.location.host + '/' + uuid)
this.socket.onopen = (e)=>{
this.reconnect = clearInterval(this.reconnect)
this.hearbeat = setInterval(()=>{
if (!this.connected()) return
this.socket.send('["ping"]')
this.hearbeatTimeout = setTimeout(()=>{
if (this.connected()) this.socket.close()
}, hearbeatTimeout)
}, hearbeatInterval)
this.trigger('connect')
this.flush()
}
this.socket.onmessage = (e)=>{
this.receive(e.data)
}
this.socket.onclose = this.socket.onerror = ()=>{
this.close()
}
}
close() {
this.socket = null
this.hearbeat = clearInterval(this.hearbeat)
this.hearbeatTimeout = clearTimeout(this.hearbeatTimeout)
this.dieTimeout = clearTimeout(this.dieTimeout)
if (!this.reconnect) {
this.reconnect = setInterval(()=>{
this.open()
}, reconnectInterval)
}
}
connected() {
return this.socket && this.socket.readyState == this.socket.OPEN
}
receive(message) {
if (typeof message == 'string') {
var packet = JSON.parse(message)
if (Array.isArray(packet) && typeof packet[0] == 'string') {
this.emit(packet[0], packet[1])
}
}
}
send(event, data) {
var packet = JSON.stringify([event, data])
if (this.connected()) {
this.socket.send(packet)
} else {
this.queue.push(packet)
}
}
flush(){
for (var i in this.queue) {
if (this.connected()) this.socket.send(this.queue[i])
}
this.queue = []
}
}
var ipc = new Ipc()
module.exports = ipc

View file

@ -0,0 +1,63 @@
module.exports = {
// editor
editor_on: 'On',
editor_off: 'Off',
editor_root: 'Root',
editor_load: 'Load',
editor_save: 'Save',
// editor context-menu
editor_editparent: 'Edit parent',
editor_copy: 'Copy',
editor_cut: 'Cut',
editor_wrap: 'Wrap in',
editor_paste: 'Paste',
editor_pasteindent: 'ID + 1',
editor_clone: 'Clone',
editor_addwidget: 'Add widget',
editor_addtab: 'Add tab',
editor_delete: 'Delete',
editor_click_for_help: 'Click on the property name to display help',
// loadings
loading_upload: 'Uploading file...',
loading_newclient: 'New client connecting...',
loading_server: 'Connecting server...',
loading_session: 'Loading session...',
// fullscreen error
fs_unnavailable: 'Fullscreen not available',
fs_addtohome: 'You must add this page to your home screen to launch it in fullscreen',
// session
session_browse: 'Browse...',
session_new: 'New session',
session_malformed: 'Malformed session file.',
session_parsingerror: 'Parsing error.',
session_uploaderror: 'Failed to upload session file.',
// sidepanel
sidepanel_fs: 'Fullscreen',
sidepanel_state: 'State',
sidepanel_traversing: 'Traversing gestures',
sidepanel_editor: 'Editor',
// state
state_store: 'Store',
state_recall: 'Recall',
state_send: 'Send All',
state_import: 'Import',
state_export: 'Export',
state_uploaderror: 'Failed to upload state file.',
// traversing
traversing_on: 'On',
traversing_smart: 'Smart',
traversing_off: 'Off',
// misc
error: 'Error'
}

View file

@ -0,0 +1,63 @@
module.exports = {
// editor
editor_on: 'On',
editor_off: 'Off',
editor_root: 'Root',
editor_load: 'Charger',
editor_save: 'Sauver',
// editor context-menu
editor_editparent: 'Éditer parent',
editor_copy: 'Copier',
editor_cut: 'Couper',
editor_wrap: 'Grouper dans',
editor_paste: 'Coller',
editor_pasteindent: 'ID + 1',
editor_clone: 'Clone',
editor_addwidget: 'Nouveau widget',
editor_addtab: 'Nouvel onglet',
editor_delete: 'Supprimer',
editor_click_for_help: 'Cliquer sur le nom de la propriété pour afficher l\'aide',
// loadings
loading_upload: 'Téléversement...',
loading_newclient: 'Connexion d\'un nouveau client...',
loading_server: 'Connexion au serveur...',
loading_session: 'Chargement de la session...',
// fullscreen error
fs_unnavailable: 'Plein écran indisponible',
fs_addtohome: 'Vous devez ajouter cette page à votre écran d\'accueil pour pouvoir l\'ouvrir en plein écran.',
// session
session_browse: 'Parcourir...',
session_new: 'Nouvelle session',
session_malformed: 'Fichier de session mal formé.',
session_parsingerror: 'Erreur à l\'ouverture de la session.',
session_uploaderror: 'Échec à l\'envoi du fichier de session.',
// sidepanel
sidepanel_fs: 'Plein Écran',
sidepanel_state: 'État',
sidepanel_traversing: 'Gestes traversants',
sidepanel_editor: 'Éditeur',
// state
state_store: 'Sauver',
state_recall: 'Rappeler',
state_send: 'Envoyer',
state_import: 'Importer',
state_export: 'Exporter',
state_uploaderror: 'Échec à l\'envoi du fichier d\'état.',
// traversing
traversing_on: 'On',
traversing_smart: 'Auto',
traversing_off: 'Off',
// misc
error: 'Erreur'
}

View file

@ -0,0 +1,10 @@
var locales = {
debug: {/* empty */},
en: require('./en'),
fr: require('./fr'),
ru: require('./ru')
}
var lang = locales[LANG] ? LANG : 'en'
module.exports = key=>locales[lang][key] || `<em class='translation-missing'>${key}</em>`

View file

@ -0,0 +1,63 @@
module.exports = { // @https://github.com/suhr
// editor
editor_on: 'Вкл',
editor_off: 'Выкл',
editor_root: 'Корень',
editor_load: 'Загрузить',
editor_save: 'Сохранить',
// editor context-menu
editor_editparent: 'К родителю',
editor_copy: 'Копировать',
editor_cut: 'Вырезать',
editor_wrap: 'Обернуть в',
editor_paste: 'Вставить',
editor_pasteindent: 'ID + 1',
editor_clone: 'Клон',
editor_addwidget: 'Добавить виджет',
editor_addtab: 'Добавить вкладку',
editor_delete: 'Удалить',
editor_click_for_help: 'Нажмите на название свойства, чтобы отобразить справку',
// loadings
loading_upload: 'Загрузка файла...',
loading_newclient: 'Подключается новый клиент...',
loading_server: 'Соединение с сервером...',
loading_session: 'Загрузка сессии...',
// fullscreen error
fs_unnavailable: 'Полный экран не доступен',
fs_addtohome: 'Необходимо добавить эту страницу на главный экран чтобы запустить её в полноэкранном режиме',
// session
session_browse: 'Обзор...',
session_new: 'Новая сессия',
session_malformed: 'Файл сессии повреждён.',
session_parsingerror: 'Ошибка разбора.',
session_uploaderror: 'Не удалось загрузить файл сессии.',
// sidepanel
sidepanel_fs: 'Полный экран',
sidepanel_state: 'Состояние',
sidepanel_traversing: 'Скользящие жесты',
sidepanel_editor: 'Редактор',
// state
state_store: 'Запомнить',
state_recall: 'Вспомнить',
state_send: 'Отправить всё',
state_import: 'Импорт',
state_export: 'Экспорт',
state_uploaderror: 'Не удалось загрузить файл состояния.',
// traversing
traversing_on: 'Вкл',
traversing_smart: 'Умный',
traversing_off: 'Выкл',
// misc
error: 'Ошибка'
}

View file

@ -0,0 +1,192 @@
var ipc = require('../ipc/'),
parser = require('../parser'),
editor = require('../editor/'),
lobby = require('../ui/lobby'),
{loading, icon, Popup, upload} = require('../ui/utils'),
{saveAs} = require('file-saver'),
widgetManager = require('./widgets'),
locales = require('../locales')
var SessionManager = class SessionManager {
constructor() {
this.session = []
this.lock = false
}
load(session, callback) {
if (this.lock) return
this.lock = true
var container = DOM.get('#container')[0]
container.classList.remove('show')
container.innerHTML = ''
lobby.close()
var loader = loading(locales('loading_session'))
setTimeout(()=>{
try {
parser.reset()
try {
if (session[0].type != 'root') {
this.session = [{type:'root', tabs:session}]
} else if (session[0].type == 'root'){
this.session = session
}
} catch(err) {
throw new Error(locales('session_malformed'))
}
parser.parse({
data: this.session,
parentNode: DOM.get('#container')[0]
})
editor.clearHistory()
} catch (err) {
loader.close()
lobby.open()
new Popup({title:icon('exclamation-triangle')+'&nbsp; ' + locales('session_parsingerror'), content: err, closable:true})
this.lock = false
throw err
}
for (var h in widgetManager.widgets) {
if (widgetManager.widgets[h].value !== undefined) {
widgetManager.trigger('change', [{
widget: widgetManager.widgets[h],
id: widgetManager.widgets[h].getProp('id'),
linkId: widgetManager.widgets[h].getProp('linkId'),
options: {}
}])
}
}
if (editor.enabled) editor.disable()
DOM.dispatchEvent(window, 'resize')
setTimeout(()=>{
loader.close()
container.classList.add('show')
this.lock = false
if (callback) callback()
}, 25)
}, 25)
}
save() {
var sessionfile = JSON.stringify(this.session,null,' '),
blob = new Blob([sessionfile],{type : 'application/json'})
saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.json')
ipc.send('savingSession')
}
list(data) {
for (let i in data) {
var max = 50
var path = data[i],
file = path.split('\\').pop().split('/').pop(),
length = data[i].length
path = path.replace(file,'')
if (length > max - 3) {
path = path.substr(0,Math.floor((path.length)/2)-(length-max)/2) + '...' + path.substr(Math.ceil((path.length)/2)+(length-max)/2, path.length)
}
lobby.list.appendChild(DOM.create(`
<a href="#" tabIndex="0" class="btn load" data-session="${data[i]}">
${file} <em style="opacity:0.45">(${path})</em>
${READ_ONLY? '' : '<span>'+icon('times')+'</span>'}
</a>
`))
}
lobby.list.addEventListener('click', function(e){
e.preventDefault()
if (e.target.hasAttribute('data-session')) {
ipc.send('sessionOpen',{path:e.target.getAttribute('data-session')})
} else if (!READ_ONLY && e.target.tagName == 'SPAN') {
ipc.send('sessionRemoveFromHistory',e.target.parentNode.getAttribute('data-session'))
lobby.list.removeChild(e.target.parentNode)
}
})
if (!READ_ONLY) {
var brw = lobby.footer.appendChild(DOM.create('<a href="#" tabindex="0" class="btn browse">'+icon('folder-open')+' ' + locales('session_browse') +'</a>'))
var nws = lobby.footer.appendChild(DOM.create('<a href="#" tabindex="0" class="btn new">'+icon('file')+' ' + locales('session_new') +'</a>'))
brw.addEventListener('click', (e)=>{
this.browse()
})
nws.addEventListener('click', (e)=>{
this.create()
})
}
DOM.addEventListener(lobby.html, 'mousedown touchstart', function(e){
if (e.type == 'mousedown') e.preventDefault()
e.target.blur()
})
lobby.open()
}
open(data) {
this.load(data,function(){
ipc.send('sessionOpened')
})
}
browse() {
upload('.json', (path, result)=>{
ipc.send('sessionOpen',{file:result,path:path})
}, ()=>{
new Popup({title:icon('exclamation-triangle')+'&nbsp; ' + locales('error'), content: locales('session_uploaderror'), closable:true})
})
}
create() {
this.load([{}],function(){
require('../ui/sidepanel').open()
editor.enable()
editor.select(widgetManager.getWidgetById('root'))
})
}
}
var sessionManager = new SessionManager()
module.exports = sessionManager

View file

@ -0,0 +1,170 @@
var widgetManager = require('./widgets'),
{icon, Popup, upload} = require('../ui/utils'),
{saveAs} = require('file-saver'),
locales = require('../locales')
var StateManager = class StateManager {
constructor() {
this.quickState = []
this.valueStateQueue = {}
this.valueOldPropQueue = {}
this.valueNewPropQueue = {}
this.queueCounter = 0
}
get() {
var data = []
for (let i in widgetManager.widgets) {
var widget = widgetManager.widgets[i]
if (widget.setValue && widget.getValue) {
var v = widget.getValue()
if (v!=undefined) {
data.push([widget.getProp('id'),v])
continue
}
}
}
return data
}
set(preset,send) {
for (let i in preset) {
var data = preset[i],
widgets = widgetManager.getWidgetById(data[0])
if (widgets.length) {
for (var j=widgets.length-1;j>=0;j--) {
if (widgets[j].setValue) {
widgets[j].setValue(data[1],{send:send,sync:true})
}
}
}
}
}
send(options) {
for (let i in widgetManager.widgets) {
var widget = widgetManager.widgets[i]
if (widget.sendValue) {
widget.sendValue(null, options)
}
}
}
load() {
upload('.state', (path, result)=>{
this.set(JSON.parse(result),true)
}, (e)=>{
new Popup({title:icon('exclamation-triangle')+'&nbsp; ' + locales('error'), content: locales('state_uploaderror'), closable:true})
})
}
save() {
var state = JSON.stringify(this.get(),null,' ')
var blob = new Blob([state],{type : 'application/json'})
saveAs(blob, new Date().toJSON().slice(0,10)+'_'+new Date().toJSON().slice(11,16) + '.state')
}
quickSave(state) {
if (state) {
this.quickState = state
} else {
this.quickState = this.get()
}
}
quickLoad() {
this.set(this.quickState,true)
}
pushValueState(id, value) {
this.valueStateQueue[id] = value
}
pushValueOldProp(id, value) {
this.valueOldPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
}
pushValueNewProp(id, value) {
this.valueNewPropQueue[id] = typeof value == 'object' ? JSON.stringify(value) : value
if (this.queueCounter == 0) this.flush()
}
flush(){
for (let id in this.valueStateQueue) {
if (this.valueStateQueue[id] !== undefined) {
for (let w of widgetManager.getWidgetById(id)) {
w.setValue(this.valueStateQueue[id], {sync: true})
}
}
}
for (let id in this.valueNewPropQueue) {
if (this.valueNewPropQueue[id] != this.valueOldPropQueue[id]) {
for (let w of widgetManager.getWidgetById(id)) {
w.setValue(w.getProp('value'), {sync: true})
}
}
}
this.valueStateQueue = {}
this.valueOldPropQueue = {}
this.valueNewPropQueue = {}
}
incrementQueue() {
this.queueCounter++
}
decrementQueue() {
this.queueCounter--
if (this.queueCounter == 0) this.flush()
}
}
var stateManager = new StateManager()
module.exports = stateManager

View file

@ -0,0 +1,337 @@
var EventEmitter = require('../events/event-emitter'),
ipc = require('../ipc/')
var WidgetManager = class WidgetManager extends EventEmitter {
constructor() {
super()
this.widgets = {}
this.children = []
this.addressRoute = {}
this.idRoute = {}
this.linkIdRoute = {}
this.linkIdLock = []
this.linkIdLockDepth = 0
this.scrollingWidgets = []
this.preArgsSeparator = '||||'
this.on('change', this.onChange, this)
ipc.on('connect', ()=>{
for (var hash in this.widgets) {
this.registerWidget(this.widgets[hash])
}
})
}
onChange(e) {
var {id, widget, linkId, options} = e
if (linkId) {
if (!Array.isArray(linkId)) linkId = [linkId]
linkId = linkId.map(x=>x.replace(/^>>\s*/, '')).filter(x=>x.indexOf('<<') < 0)
linkId = linkId.filter(x=>this.linkIdLock.indexOf(x)<0)
this.linkIdLock = this.linkIdLock.concat(linkId)
this.linkIdLockDepth++
}
var widgetsById = this.getWidgetById(id),
widgetsByLinkId = linkId ? this.getWidgetByLinkId(linkId) : []
// Widget that share the same id will update each other
// without sending any extra osc message
if (widgetsById.length > 1) {
let v = widget.getValue()
for (let i in widgetsById) {
if (widgetsById[i] !== widget) {
widgetsById[i].setValue(v,{send:false,sync:false})
}
}
}
// widgets that share the same linkId will update each other.
// Updated widgets will send osc messages normally
if (widgetsByLinkId.length > 0) {
let v = widget.getValue()
for (let i in widgetsByLinkId) {
if (widgetsByLinkId[i] !== widget) {
widgetsByLinkId[i].setValue(v,{send: options.send,sync: true})
}
}
}
if (linkId && this.linkIdLockDepth) {
this.linkIdLockDepth--
if (!this.linkIdLockDepth) {
this.linkIdLock = []
}
}
}
createAddressRef(widget, preArgs, address) {
preArgs = widget ? widget.getProp('preArgs') : preArgs
address = widget ? widget.getProp('address') : address
if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
if (preArgs === '') preArgs = []
preArgs = preArgs.map(x=>typeof x === 'object' && x !== null && x.value !== undefined ? x.value : x)
return preArgs && preArgs.length ?
address + this.preArgsSeparator + preArgs.join(this.preArgsSeparator)
: address
}
addWidget(widget) {
var hash = widget.hash,
address = this.createAddressRef(widget),
id = widget.getProp('id'),
linkId = widget.getProp('linkId'),
scroll = widget.getProp('scroll')
this.widgets[hash] = widget
if (!this.idRoute[id]) this.idRoute[id] = []
this.idRoute[id].push(hash)
if (address) {
if (!this.addressRoute[address]) this.addressRoute[address] = []
this.addressRoute[address].push(hash)
}
if (linkId) {
if (!Array.isArray(linkId)) linkId = [linkId]
linkId = linkId.map(x=>x.replace(/^<<\s*/, '')).filter(x=>x.indexOf('>>') < 0)
for (var i in linkId) {
if (linkId[i]) {
if (!this.linkIdRoute[linkId[i]]) this.linkIdRoute[linkId[i]] = []
this.linkIdRoute[linkId[i]].push(hash)
}
}
}
if (scroll) {
this.scrollingWidgets.push(hash)
}
this.registerWidget(widget)
}
registerWidget(widget, updatedData, oldData) {
ipc.send('addWidget', {
hash: widget.hash,
data: updatedData || {
precision: widget.getProp('precision'),
preArgs: widget.getProp('preArgs'),
split: widget.getSplit(),
target: widget.getProp('target'),
address: widget.getProp('address'),
noSync: widget.getProp('noSync'),
}
})
if (updatedData && oldData) {
var address = this.createAddressRef(null, oldData.preArgs, oldData.address),
newAddress = this.createAddressRef(widget),
hash = widget.hash
if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
if (!this.addressRoute[newAddress]) this.addressRoute[newAddress] = []
this.addressRoute[newAddress].push(hash)
}
}
removeWidget(widget) {
var hash = widget.hash,
address = this.createAddressRef(widget),
linkId = widget.getProp('linkId'),
id = widget.getProp('id'),
scroll = widget.getProp('scroll')
if (this.widgets[hash]) {
if (this.widgets[hash].onRemove) this.widgets[hash].onRemove()
delete this.widgets[hash]
ipc.send('removeWidget', {
hash:hash
})
widget.trigger('widget-removed', [{widget: widget}])
}
if (id && this.idRoute[id].indexOf(hash) != -1) this.idRoute[id].splice(this.idRoute[id].indexOf(hash), 1)
if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
if (scroll && this.scrollingWidgets.indexOf(hash) != -1) this.scrollingWidgets.splice(this.scrollingWidgets.indexOf(hash), 1)
if (!Array.isArray(linkId)) linkId = [linkId]
for (var i in linkId) {
if (linkId[i] && this.linkIdRoute[linkId[i]] && this.linkIdRoute[linkId[i]].indexOf(hash) != -1) this.linkIdRoute[linkId[i]].splice(this.linkIdRoute[linkId[i]].indexOf(hash), 1)
}
}
removeWidgets(widgets, nested) {
for (let i in widgets) {
if (Array.isArray(widgets[i])) {
this.removeWidgets(widgets[i], true)
} else if (this.widgets[widgets[i].hash]) {
this.removeWidget(widgets[i])
}
}
if (!nested) this.purge()
}
purge() {
for (let route of [this.addressRoute, this.idRoute, this.linkIdRoute]) {
for (let key in route) {
for (let i=route[key].length-1; i>=0; i--) {
let hash = route[key][i]
if (!this.widgets[hash]) {
route[key].splice(i, 1)
}
}
}
}
for (let i in this.scrollingWidgets) {
if (!this.widgets[this.scrollingWidgets[i]]) {
this.scrollingWidgets.splice(i, 1)
}
}
}
reset() {
this.removeWidgets(Object.values(this.widgets))
this.removeEvent()
this.on('change', this.onChange, this)
}
getWidgetBy(key, dict, widgets = []) {
var hash, w
if (Array.isArray(key)) {
for (let i in key) {
this.getWidgetBy(key[i], dict, widgets)
}
return widgets
}
if (dict[key]) {
for (let i = dict[key].length-1; i>=0; i--) {
hash = dict[key][i]
w = this.widgets[hash]
if (!w) {
dict[key].splice(i,1)
} else if (widgets.indexOf(w) == -1) {
widgets.push(w)
}
}
}
return widgets
}
getWidgetById(id) {
return this.getWidgetBy(id, this.idRoute)
}
getWidgetByLinkId(linkId) {
return this.getWidgetBy(linkId, this.linkIdRoute)
}
getWidgetByAddress(address) {
return this.getWidgetBy(address, this.addressRoute)
}
getWidgetByAddressAndArgs(address, args) {
var addressref = address,
restArgs = args
if (typeof args == 'object' && args != null) {
for (var i = args.length; i >= 0; i--) {
var ref = this.createAddressRef(null, args.slice(0,i), address)
if (this.getWidgetByAddress(ref).length) {
addressref = ref
restArgs = args.slice(i, args.length)
break
}
}
} else {
restArgs = args
}
if (restArgs == null || restArgs.length == 0) restArgs = null
else if (restArgs.length == 1) restArgs = restArgs[0]
var widgets = this.getWidgetByAddress(addressref)
return [
widgets,
restArgs
]
}
getWidgetByElement(e, filter = '') {
var element = e ? e.closest('[data-widget]' + filter) : undefined
if (element) {
return element._widget_instance ?
element._widget_instance :
this.widgets[element.getAttribute('data-widget')]
}
}
}
var widgetManager = new WidgetManager()
module.exports = widgetManager

63
src/client/app/osc.js Normal file
View file

@ -0,0 +1,63 @@
var widgetManager = require('./managers/widgets'),
EventEmitter = require('./events/event-emitter'),
ipc = require('./ipc/')
var Osc = class Osc extends EventEmitter {
constructor() {
super()
this.syncOnly = false
this.remoteControl = {}
}
send(data) {
if (this.syncOnly) {
this.sync(data)
} else {
ipc.send('sendOsc', data)
}
}
sync(data) {
ipc.send('syncOsc', data)
}
receive(data){
if (this.remoteControl.exists(data.address)) this.remoteControl.exec(data.address, data.args)
var [widgets, restArgs] = widgetManager.getWidgetByAddressAndArgs(data.address, data.args)
for (let i in widgets) {
let widgetTarget = widgets[i].getProp('target')
// if the message target is provided (when message comes from another client connected to the same server)
// then we only update the widgets that have the same target
if (!data.target || !widgetTarget || String(widgetTarget) === String(data.target)) {
// update matching widgets
if (widgets[i] && widgets[i].setValue) widgets[i].setValue(restArgs,{send:false,sync:true,fromExternal:!data.target})
}
}
this.trigger(data.address, [data.args])
}
}
var osc = new Osc()
module.exports = osc
osc.remoteControl = require('./remote-control')

123
src/client/app/parser.js Normal file
View file

@ -0,0 +1,123 @@
var widgetManager = require('./managers/widgets'),
stateManager = require('./managers/state')
var Parser = class Parser {
constructor() {
this.iterators = {}
this.widgets = {}
}
getIterator(id) {
this.iterators[id] = (this.iterators[id] || 0) + 1
return this.iterators[id]
}
reset() {
this.iterators = {}
widgetManager.reset()
}
parse(options) {
var {
data,
parentNode,
parent,
tab,
reCreateOptions,
children,
index
} = options
if (!Array.isArray(data)) data = [data]
for (let i in data) {
var props = data[i]
// Set default widget type
props.type = tab ? 'tab' : props.type || 'fader'
// Backward compatibility patches
if (props.path) props.address = props.path
if (props.noPip) props.pips = !props.noPip
if (props.noSync) {
props.bypass = props.noSync
delete props.noSync
}
// Safe copy widget's options
let defaults = this.widgets[props.type].defaults()._props()
// Set widget's undefined options to default
for (let i in defaults) {
if (i.indexOf('_')!=0 && props[i]===undefined) props[i] = defaults[i]
}
// Genrate widget's id, based on its type
if (props.id=='auto' || !props.id ) {
var id
while (!id || widgetManager.getWidgetById(id).length) {
id=props.type+'_'+this.getIterator(props.type)
}
props.id = id
}
// Generate default address
props.address = props.address == 'auto' ? '/' + props.id : props.address
for (let j in props) {
if (defaults[j] === undefined || j[0] === '_') delete props[j]
}
// create widget
var widget = new this.widgets[props.type]({
container:true,
props,
parent,
parentNode,
reCreateOptions,
children
})
widgetManager.addWidget(widget)
widget.created(index)
// set widget's initial state
var defaultValue = widget.getProp('default'),
currentValue = widget.getProp('value')
if (currentValue !== '' && currentValue !== undefined) {
stateManager.pushValueNewProp(widget.getProp('id'), currentValue)
} else if (defaultValue !== '' && defaultValue !== undefined) {
widget.setValue(defaultValue)
}
parentNode.appendChild(widget.container)
}
// Editor needs to get the container object
if (data && data.length==1) return widget
}
}
var parser = new Parser()
module.exports = parser
parser.widgets = require('./widgets/').widgets

View file

@ -0,0 +1,206 @@
var {updateWidget} = require('./editor/data-workers'),
editor = require('./editor'),
widgetManager = require('./managers/widgets'),
deepExtend = require('deep-extend')
var callbacks = {
'/EDIT': function(args) {
if (READ_ONLY) return
var [id, json] = args,
newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
for (var i = widgets.length - 1; i >= 0; i--) {
var widget = widgets[i],
data = widget.props
for (var k in newdata) {
data[k] = newdata[k]
}
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs)
})
}
editor.pushHistory()
},
'/EDIT/MERGE': function(args) {
if (READ_ONLY) return
var [id, json] = args,
newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
for (var i = widgets.length - 1; i >= 0; i--) {
var widget = widgets[i],
data = widget.props
deepExtend(data, newdata)
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs)
})
}
editor.pushHistory()
},
'/EDIT/UNDO': function(args) {
if (READ_ONLY) return
editor.undo()
},
'/EDIT/REDO': function(args) {
if (READ_ONLY) return
editor.redo()
},
'/EDIT/GET': function(args) {
var [target, idOrAddress, ...preArgs] = args,
widgets = []
if (idOrAddress[0] == '/') {
widgets = widgetManager.getWidgetByAddress(
widgetManager.createAddressRef(null, preArgs, idOrAddress)
)
} else {
widgets = widgetManager.getWidgetById(idOrAddress)
}
for (var i = widgets.length - 1; i >= 0; i--) {
return widgets[i].sendValue({
target: [target],
address: '/EDIT/GET',
preArgs: [idOrAddress, ...preArgs],
v: JSON.stringify(widgets[i].props),
noSync: true
}, {force: true})
}
},
'/GET': function(args, transparentReply) {
var [target, idOrAddress, ...preArgs] = args,
widgets = []
if (idOrAddress[0] == '/') {
widgets = widgetManager.getWidgetByAddress(
widgetManager.createAddressRef(null, preArgs, idOrAddress)
)
} else {
widgets = widgetManager.getWidgetById(idOrAddress)
}
for (var i = widgets.length - 1; i >= 0; i--) {
let overrides = {
target: [target],
noSync: true
}
if (!transparentReply) {
overrides.address = '/GET'
overrides.preArgs = [idOrAddress, ...preArgs]
}
return widgets[i].sendValue(overrides, {force: true})
}
},
'/GET/#': function(args) {
callbacks['/GET'](args, true)
},
'/SET': function(args) {
var [idOrAddress, ...preArgsOrValue] = args,
widgets = [],
value = null
if (idOrAddress[0] == '/') {
[widgets, value] = widgetManager.getWidgetByAddressAndArgs(
idOrAddress,
preArgsOrValue
)
} else {
widgets = widgetManager.getWidgetById(idOrAddress)
value = preArgsOrValue
if (value.length == 0) value = null
else if (value.length == 1) value = value[0]
}
for (var i = widgets.length - 1; i >= 0; i--) {
return widgets[i].setValue(value, {
sync: true,
send: true
})
}
},
'/TABS': function(args) {
if (!Array.isArray(args)) args = [args]
for (let id of args) {
let ws = widgetManager.getWidgetById(id)
for (let w of ws) {
DOM.each(document, `.tablink[data-widget="${w.hash}"]`, (el)=>{
DOM.dispatchEvent(el, 'fast-click', {})
})
}
}
}
}
// backward-compatibility
callbacks['/EDIT_SOFT'] = callbacks['/EDIT/MERGE']
module.exports = {
exec: function(name, args){
if (callbacks[name]) {
callbacks[name](args)
}
},
exists: function(name){
return name in callbacks
}
}

View file

@ -0,0 +1,28 @@
var StackTrace = require('stacktrace-js'),
ipc = require('./ipc')
window.onerror = function(msg,url,row,col, error) {
StackTrace.fromError(error).then((stackframes)=>{
var stringifiedStack = stackframes.filter((sf)=>{
return !sf.fileName.match('browser-pack')
}).map(function(sf) {
if (sf.functionName.match(/Object\./)) sf.functionName = 'require'
return ` at ${sf.functionName} (${sf.fileName}:${sf.lineNumber}:${sf.columnNumber})`
}).join('\n')
ipc.send('errorLog', `[Renderer process error]\n${msg}\n${stringifiedStack}`)
}).catch(()=>{
ipc.send('errorLog', `[Renderer process error]\n${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
})
}

View file

@ -0,0 +1,40 @@
var screenfull = require('screenfull'),
{Popup} = require('./utils'),
locales = require('../locales')
var fullscreen
if (screenfull.enabled) {
fullscreen = screenfull
} else {
class IOSFullScreen {
constructor(){
this.enabled = !navigator.standalone
this.isFullScreen = navigator.standalone
}
toggle(){
new Popup({
title: locales('fs_unnavailable'),
content: locales('fs_addtohome'),
closable: true
})
}
on(){}
}
fullscreen = new IOSFullScreen()
}
module.exports = fullscreen

View file

@ -0,0 +1,5 @@
require('./zoom')
require('./lobby').create()
require('./sidepanel')
require('../events/click')
require('./ios')

25
src/client/app/ui/ios.js Normal file
View file

@ -0,0 +1,25 @@
// Prevent iOS Pull-To-Refresh
var iOS
if (navigator.platform.match(/iPhone|iPod|iPad/)) {
iOS = true
var preventNextMove = false
document.addEventListener('touchstart', (e)=>{
if (e.touches.length === 1 && !e.target._drag_widget) preventNextMove = true
}, false)
document.addEventListener('touchmove', (e)=>{
// preventDefault the first overscrolling touchmove
if (preventNextMove) {
preventNextMove = false
e.preventDefault()
}
}, false)
}
module.exports = iOS

View file

@ -0,0 +1,49 @@
class Lobby {
constructor() {
this.state = 0
}
create() {
this.html = DOM.create(`
<div id="lobby">
<div class="main">
<div class="header">
${PACKAGE.productName}
</div>
<div class="list"></div>
<div class="footer"></div>
</div>
</div>
`)
this.main = DOM.get(this.html, '.main')[0]
this.list = DOM.get(this.html, '.list')[0]
this.footer = DOM.get(this.html, '.footer')[0]
}
open() {
if (this.state) return
this.state = 1
document.body.appendChild(this.html)
setTimeout(()=>{
this.main.classList.add('show')
})
}
close() {
if (!this.state) return
this.state = 0
this.main.classList.remove('show')
document.body.removeChild(this.html)
}
}
var lobby = new Lobby()
module.exports = lobby

View file

@ -0,0 +1,270 @@
var state = require('../managers/state'),
session = require('../managers/session'),
editor = require('../editor/'),
{icon} = require('./utils'),
fullscreen = require('./fullscreen'),
{enableTraversingGestures, disableTraversingGestures} = require('../events/drag'),
locales = require('../locales')
var sidepanelData = [
{
actions: [
{
title: locales('sidepanel_fs') + (ELECTRON_FULLSCREEN ? ' (F11)' : ''),
action:()=>{
if (fullscreen.enabled) fullscreen.toggle()
},
class:'fullscreenToggle' + (!fullscreen.enabled || ELECTRON_FULLSCREEN ? ' disabled' : '')
}
]
},
{
title: icon('sliders-h') + '&nbsp; ' + locales('sidepanel_state'),
actions: [
{
title: locales('state_store'),
action:()=>{
state.quickSave()
DOM.get('.quickload')[0].classList.remove('disabled')
}
},
{
title: locales('state_recall'),
action:state.quickLoad.bind(state),
class:'disabled quickload'
},
{
title: locales('state_send'),
action:state.send.bind(state)
},
{
title: locales('state_import'),
action:state.load.bind(state)
},
{
title: locales('state_export'),
action:state.save.bind(state)
}
]
},
{
title: icon('magic') + '&nbsp; ' + locales('sidepanel_traversing'),
actions: [
{
title: locales('traversing_on'),
action:(el)=>{
DOM.each(el.parentNode, 'a', (el)=>{
el.classList.remove('on')
})
el.classList.add('on')
var container = document.getElementById('container')
disableTraversingGestures(container)
enableTraversingGestures(container)
},
class:'traversingEnable'
},
{
title: locales('traversing_smart'),
action:(el)=>{
DOM.each(el.parentNode, 'a', (el)=>{
el.classList.remove('on')
})
el.classList.add('on')
var container = document.getElementById('container')
disableTraversingGestures(container)
enableTraversingGestures(container, {smart: true})
},
class:'traversingSmart'
},
{
title: locales('traversing_off'),
action:(el)=>{
DOM.each(el.parentNode, 'a', (el)=>{
el.classList.remove('on')
})
el.classList.add('on')
disableTraversingGestures(document.getElementById('container'))
},
class:'traversingDisable on'
}
]
},
{
title: icon('edit') + '&nbsp; ' + locales('sidepanel_editor'),
class:'editor-menu',
actions: [
{
title: locales('editor_on'),
action:editor.enable.bind(editor),
class:'enable-editor'
},
{
title: locales('editor_off'),
action:editor.disable.bind(editor),
class:'on disable-editor'
},
{
title: locales('editor_root'),
class:'editor-root disabled'
},
{
title: locales('editor_load'),
action:session.browse.bind(session)
},
{
title: locales('editor_save'),
action:session.save.bind(session)
}
]
},
]
var options = DOM.create('<ul id="options"></ul>')
for (let i in sidepanelData) {
let data = sidepanelData[i],
item = DOM.create(`
<li>
<div class="${data.class || ''}">
<div class="actions">
${data.title ? `<div class="title">${data.title}</div>` : ''}
</div>
</div>
</li>
`),
wrapper = DOM.get(item, '.actions')[0]
for (let j in data.actions) {
let actionData = data.actions[j],
element = DOM.create(`<a class="btn ${actionData.class || ''}">${actionData.title}</a>`)
if (actionData.action) element.addEventListener('click', ()=>{actionData.action(element)})
wrapper.appendChild(element)
}
options.appendChild(item)
}
var sidepanel = document.getElementById('sidepanel')
sidepanel.appendChild(DOM.create(`
<div class="navigation"><ul><li><a>${PACKAGE.productName.toUpperCase()}</a></li></ul></div>
`))
sidepanel.appendChild(options)
sidepanel.appendChild(DOM.create('<div id="editor"></div>'))
// Fullscreen
var fsToggle = DOM.get(sidepanel, '.fullscreenToggle')[0]
if (fullscreen.enabled) {
fullscreen.on('change', ()=>{
fsToggle.classList.toggle('on', fullscreen.isFullScreen)
})
}
// open / close / toggle
var sidepaneLock = false
function sidepanelOpen() {
sidepaneLock = true
DOM.get('#open-toggle, #sidepanel').forEach((el)=>{
el.classList.add('sidepanel-open')
})
setTimeout(function(){
DOM.get('#container')[0].classList.add('sidepanel-open')
setTimeout(function(){
DOM.dispatchEvent(window, 'resize')
sidepaneLock = false
}, 25)
}, 250)
}
function sidepanelClose() {
if (sidepaneLock) return
DOM.get('#open-toggle, #sidepanel, #container').forEach((el)=>{
el.classList.remove('sidepanel-open')
})
setTimeout(function(){
DOM.dispatchEvent(window, 'resize')
}, 25)
}
function sidepanelToggle() {
if (sidepanel.classList.contains('sidepanel-open')) {
sidepanelClose()
} else {
sidepanelOpen()
}
}
DOM.get('#container')[0].addEventListener('fast-click', function(e){
if (e.target.id == 'open-toggle') {
e.stopPropagation()
e.detail.preventOriginalEvent = true
sidepanelToggle()
}
})
document.addEventListener('keydown', function(e){
// F10
if (e.keyCode==121) sidepanelToggle()
})
// Sidepanel resize
var resizeHandle = DOM.create('<div id="sidepanel-handle">'+icon('bars')+'</div>'),
sidepanelWidth
sidepanel.appendChild(resizeHandle)
$(resizeHandle).draggable({
cursor:'col-resize',
start: ()=>{
sidepanelWidth = parseInt(sidepanel.offsetWidth) / PXSCALE
sidepanel.classList.add('resizing')
},
drag: (event, ui)=>{
var delta = (ui.originalPosition.left - ui.position.left) / PXSCALE,
newWidth = Math.max(sidepanelWidth + delta, 300)
if (!isNaN(sidepanelWidth)) {
document.documentElement.style.setProperty('--sidepanel-size', newWidth + 'rem')
}
},
stop: ()=>{
sidepanel.classList.remove('resizing')
}
})
module.exports = {
open: sidepanelOpen,
close: sidepanelClose,
toggle: sidepanelToggle
}

133
src/client/app/ui/utils.js Normal file
View file

@ -0,0 +1,133 @@
var popupSingleton = null,
uploadSingleton = null,
locales = require('../locales')
module.exports = {
Popup: class Popup {
constructor(options) {
if (options.closable) {
if (popupSingleton) {
popupSingleton.close()
popupSingleton = null
}
popupSingleton = this
}
this.closable = options.closable
this.escKey = options.closable || options.escKey
this.enterKey = options.enterKey
this.content = options.content
this.title = options.title
this.state = 0
this.html = DOM.create(`
<div class="popup show">
<div class="popup-wrapper">
<div class="popup-title ${this.closable? 'closable' : ''}">${this.title}${this.closable? `<span class="closer">${module.exports.icon('times')}</span>` : ''}</div>
<div class="popup-content">
${this.content}
</div>
</div>
</div>
`)
if (this.closable) {
var closer = DOM.get(this.html, '.popup-title .closer')[0]
this.html.addEventListener('fast-click',(e)=>{
if (e.target === this.html || e.target === closer) {
e.detail.preventOriginalEvent = true
this.close()
}
})
}
if (this.escKey) {
this.escKeyHandler = ((e)=>{
if (e.keyCode==27) this.close()
}).bind(this)
}
if (this.enterKey) {
this.enterKeyHandler = ((e)=>{
if (e.keyCode == 13) this.enterKey.call(this, e)
}).bind(this)
}
this.open()
}
close() {
if (!this.state) return
this.state = 0
if (this.escKey) document.removeEventListener('keydown', this.escKeyHandler)
if (this.enterKey) document.removeEventListener('keydown', this.enterKeyHandler)
document.body.removeChild(this.html)
}
open() {
if (this.state) return
this.state = 1
if (this.escKey) document.addEventListener('keydown', this.escKeyHandler)
if (this.enterKey) document.addEventListener('keydown', this.enterKeyHandler)
document.body.appendChild(this.html)
}
},
loading: function(title){
return new module.exports.Popup({
title: title,
content: '<p><div class="spinner"></div></p>',
closable: false
})
},
icon: function(i) {
return `<i class="fa fa-fw fa-${i}"></i>`
},
iconify:function(string){
return String(string).replace(/\^[^\s]*/g,(x)=>{return module.exports.icon(x.substring(1))})
},
upload: function(types, ok, error) {
if (uploadSingleton) document.body.removeChild(uploadSingleton)
uploadSingleton = DOM.create('<input type="file" accept="' + types + '" style="position:absolute;opacity:0;pointer-events:none;"/>')
document.body.appendChild(uploadSingleton)
uploadSingleton.addEventListener('change',function(e){
var reader = new FileReader(),
file = e.target.files[0],
loader = module.exports.loading(locales('loading_upload'))
reader.onerror = reader.onabort = function() {
loader.close()
error()
}
reader.onload = function(e) {
loader.close()
ok(file.path, e.target.result)
}
reader.readAsText(file, 'utf-8')
})
uploadSingleton.click()
}
}

29
src/client/app/ui/zoom.js Normal file
View file

@ -0,0 +1,29 @@
// mousewheel zoom
var mod = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
document.addEventListener('mousewheel', function(event) {
if (event.ctrlKey) event.preventDefault()
if (event[mod]) {
event.preventDefault()
if (event.deltaY === 0) return
var d = - event.deltaY / (10 * Math.abs(event.deltaY))
PXSCALE = parseFloat(d) + parseFloat(PXSCALE)
document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
DOM.dispatchEvent(window, 'resize')
}
})
document.addEventListener('keydown', function(event){
if (event[mod] && (event.keyCode == 96 || event.keyCode == 48)) {
PXSCALE = INITIALZOOM
document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
DOM.dispatchEvent(window, 'resize')
}
})

41
src/client/app/utils.js Normal file
View file

@ -0,0 +1,41 @@
module.exports = {
deepCopy: function(obj, precision) {
var copy = obj
if (obj === null) {
return obj
}
if (typeof obj === 'object') {
copy = Array.isArray(obj) ? [] : {}
for (let key in obj) {
copy[key] = module.exports.deepCopy(obj[key], precision)
}
} else if (typeof obj == 'number') {
return precision === undefined ? copy : parseFloat(copy.toFixed(precision))
}
return copy
},
deepEqual: function(a, b) {
// about 2,75 x faster than JSON.stringify(a) === JSON.stringify(b)
var ta = typeof a,
tb = typeof b
if (ta !== tb) {
return false
} else if (ta === 'object') {
return JSON.stringify(a) === JSON.stringify(b)
} else {
return a === b
}
}
}

View file

@ -0,0 +1,104 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils')
class Dropdown extends Widget {
static defaults() {
return super.defaults({
_dropdown:'dropdown',
values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
'`Array` of possible values to switch between : `[1,2,3]`',
'`Object` of label:value pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
'An empty option will always be prepended to values (sends an osc message without any value); it can be hidden by adding `option:first-child{display:none}` to the widget\'s `css`'
]}
})
}
constructor(options) {
super({...options, html: '<div class="select"></div>'})
this.select = this.widget.appendChild(DOM.create('<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'),
html = ''
if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
values = values !== '' ? [values] : []
}
html += '<option value=""></option>'
this.values = []
for (var k in values) {
this.values.push(values[k])
html += `<option value="${i}">${iconify(parseFloat(k) != k ? k : values[k])}</option>`
i++
}
this.select.innerHTML = html
}
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,131 @@
var Widget = require('../common/widget'),
osc = require('../../osc')
class Push extends Widget {
static defaults() {
return super.defaults({
_push: 'push',
on: {type: '*', value: 1, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
off: {type: '*', value: 0, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
norelease: {type: 'boolean', value: false, help: 'Set to `true` to prevent sending any osc message when releasing the button'},
}, ['_value', 'default', 'value'])
}
constructor(options) {
super({...options, html: '<div class="toggle"></div>'})
this.state = 0
this.active = 0
this.lastChanged = 'state'
this.on('draginit',()=>{
if (this.active) return
this.setValuePrivate(this.getProp('on'),{send:true,sync:true})
}, {element: this.widget})
this.on('dragend',()=>{
this.setValuePrivate(this.getProp('off'),{send:true,sync:true})
}, {element: this.widget})
this.value = this.getProp('off')
}
updateValue(){
this.value = this[this.lastChanged] ?
this.getProp('on') != null && this.getProp('on').value !== undefined ? this.getProp('on').value : this.getProp('on')
:
this.getProp('off') != null && this.getProp('off').value !== undefined ? this.getProp('off').value : this.getProp('off')
}
setValuePrivate(v,options={}) {
if (typeof v == 'object' && v !== null) v = v.value
if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
this.widget.classList.add('active')
this.container.classList.add('active')
this.active = 1
this.lastChanged = 'active'
this.updateValue()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
} else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
this.widget.classList.remove('active')
this.container.classList.remove('active')
this.active = 0
this.lastChanged = 'active'
this.updateValue()
if (options.send) this.sendValue(null, {syncOnly: this.getProp('norelease')})
if (options.sync) this.changed(options)
}
}
setValue(v,options={}) {
if (!options.fromExternal) {
this.setValuePrivate(v,options)
return
}
if (typeof v == 'object' && v !== null) v = v.value
if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
this.widget.classList.add('on')
this.container.classList.add('on')
this.state = 1
if (options.send) this.sendValue()
this.lastChanged = 'state'
if (options.sync) this.changed(options)
} else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
this.widget.classList.remove('on')
this.container.classList.remove('on')
this.state = 0
if (options.send) this.sendValue()
this.lastChanged = 'state'
if (options.sync) this.changed(options)
}
}
sendValue(overrides, options={}) {
if (!options.syncOnly) {
super.sendValue(overrides, options)
} else {
osc.sync({
h: this.hash,
v: this.value
})
}
}
}
Push.dynamicProps = Push.prototype.constructor.dynamicProps.concat(
'on',
'off',
'norelease'
)
module.exports = Push

View file

@ -0,0 +1,99 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils')
module.exports = class Switch extends Widget {
static defaults() {
return super.defaults({
_switch:'switch',
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display values horizontally'},
showValues: {type: 'boolean', value: false, help: 'If values is an object, set to `true` to display both values and labels instead of labels only'},
values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
'`Array` of possible values to switch between : `[1,2,3]`',
'`Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
]}
})
}
constructor(options) {
super({...options, html: '<div class="switch"></div>'})
if (this.getProp('horizontal')) this.widget.classList.add('horizontal')
this.values = []
this.stringValues = []
var values = this.getProp('values')
if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
values = [values]
}
var isArray = Array.isArray(values)
for (var k in values) {
this.values.push(values[k])
if (typeof values[k] == 'object') {
this.stringValues.push(JSON.stringify(values[k]))
} else {
this.stringValues.push(0)
}
var label = isArray ? values[k]: k
if (this.getProp('showValues') && !isArray) label = label + ': ' + (this.stringValues[this.stringValues.length - 1] || values[k])
this.widget.appendChild(DOM.create(`
<div class="value"> ${iconify(label)}</div>
`))
}
this.value = undefined
this.on('draginit', (e)=>{
var index = 0,
node = e.target
while ( (node = node.previousSibling) ) {
if (node.nodeType != 3) {
index++
}
}
var value = this.values[index]
if (value!=this.value || this.value===undefined) this.setValue(value,{sync:true,send:true})
}, {element: this.widget})
}
setValue(v, options={}) {
var i = typeof v == 'object' ?
this.stringValues.indexOf(JSON.stringify(v)) :
this.values.indexOf(v)
DOM.each(this.widget, '.on', (el)=>{el.classList.remove('on')})
if (i!=-1) {
this.value = this.values[i]
DOM.get(this.widget, '.value')[i].classList.add('on')
if (options.send) this.sendValue(this.value)
if (options.sync) this.changed(options)
} else {
this.value = undefined
if (options.sync) this.changed(options)
}
}}

View file

@ -0,0 +1,90 @@
var Widget = require('../common/widget'),
doubletab = require('../mixins/double_tap')
class Toggle extends Widget {
static defaults() {
return super.defaults({
_toggle: 'toggle',
doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the button require a double tap to be toggled instead of a single tap'},
led: {type: 'boolean', value: false, help: 'Set to `true` to display the toggle\'s state with a led'},
on: {type: '*', value: 1, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
off: {type: '*', value: 0, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]}
})
}
constructor(options) {
super({...options, html: '<div class="toggle"></div>'})
this.state = 0
this.active = false
if (this.getProp('led')) this.container.classList.add('led')
if (this.getProp('doubleTap')) {
doubletab(this.widget, ()=>{
var newVal = this.state?this.getProp('off'):this.getProp('on')
this.setValue(newVal,{sync:true,send:true})
})
} else {
this.on('draginit',()=>{
if (this.active) return
this.active = true
var newVal = this.state?this.getProp('off'):this.getProp('on')
this.setValue(newVal,{sync:true,send:true})
}, {element: this.widget})
this.on('dragend',()=>{
this.active = false
}, {element: this.widget})
}
this.value = this.getProp('off')
}
setValue(v,options={}) {
if (typeof v == 'object' && v !== null) v = v.value
if (v===this.getProp('on') || (this.getProp('on') != null && v === this.getProp('on').value && v !== undefined)) {
this.widget.classList.add('on')
this.container.classList.add('on')
this.state = 1
this.value = this.getProp('on')
if (options.send) this.sendValue()
} else if (v===this.getProp('off') || (this.getProp('off') != null && v === this.getProp('off').value && v !== undefined)) {
this.widget.classList.remove('on')
this.container.classList.remove('on')
this.state = 0
this.value = this.getProp('off')
if (options.send) this.sendValue()
}
if (options.sync) this.changed(options)
}
}
Toggle.dynamicProps = Toggle.prototype.constructor.dynamicProps.concat(
'on',
'off'
)
module.exports = Toggle

View file

@ -0,0 +1,205 @@
var Widget = require('./widget')
class CanvasQueue {
constructor() {
this.queue = {}
this.flushed = 0
this.running = false
this.frameLength = 1000 / CANVAS_FRAMERATE
this.lastFrame = 0
this.bindedLoop = this.loop.bind(this)
}
push(widget) {
this.queue[widget.hash] = widget
this.flushed = 0
if (!this.running) {
this.running = true
requestAnimationFrame(this.bindedLoop)
}
}
flush() {
for (var h in this.queue) {
this.queue[h].draw()
}
this.queue = {}
this.flushed++
}
loop(timestamp) {
if (this.flushed >= 10) {
this.running = false
return
}
requestAnimationFrame(this.bindedLoop)
var delta = timestamp - this.lastFrame
if (delta > this.frameLength) {
this.lastFrame = timestamp - (delta % this.frameLength)
this.flush()
}
}
}
var canvasQueue = new CanvasQueue()
class Canvas extends Widget {
constructor(options) {
super(options)
this.canvas = DOM.get(this.widget, 'canvas')[0]
this.ctx = this.canvas.getContext('2d')
this.height = undefined
this.width = undefined
this.scaling = 1
this.clearRect = []
this.visible = false
this.colors = {}
this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
this.ctx.arc = (x, y, r, s, e, c)=>{
CanvasRenderingContext2D.prototype.arc.call(this.ctx, x, y, Math.max(0,r), s, e, c)
}
}
resizeHandleProxy() {
this.resizeHandle(...arguments)
}
resizeHandle(event){
var {width, height, style} = event,
ratio = CANVAS_SCALING * this.scaling
this.height = height
this.width = width
this.canvas.setAttribute('width', width * ratio)
this.canvas.setAttribute('height', height * ratio)
this.clearRect = []
if (ratio != 1) {
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
this.ctx.scale(ratio, ratio)
}
this.cacheCanvasStyle(style)
if (!this.visible) this.visible = true
requestAnimationFrame(this.draw.bind(this))
}
cacheCanvasStyle(style){
style = style || window.getComputedStyle(this.canvas)
this.colors.custom = style.getPropertyValue('--color-custom')
this.colors.track = style.getPropertyValue('--color-track')
this.colors.text = style.getPropertyValue('--color-text')
this.colors.raised = style.getPropertyValue('--color-raised')
this.colors.bg = style.getPropertyValue('--color-bg')
this.colors.fg = style.getPropertyValue('--color-fg')
this.colors.faded = style.getPropertyValue('--color-faded')
this.colors.light = style.getPropertyValue('--color-light')
this.fontFamily = style.getPropertyValue('font-family')
this.textAlign = style.getPropertyValue('text-align')
this.fontSize = parseFloat(style.getPropertyValue('font-size'))
this.fontWeight = parseFloat(style.getPropertyValue('font-weight'))
this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
this.ctx.textBaseline = 'middle'
this.ctx.textAlign = this.textAlign
}
clear() {
if (!this.clearRect.length) {
this.ctx.clearRect(0, 0, this.width, this.height)
return
}
if (typeof this.clearRect[0] == 'object') {
for (let i in this.clearRect) {
this.ctx.clearRect(...this.clearRect[i])
}
return
}
this.ctx.clearRect(...this.clearRect)
}
batchDraw() {
if (this.visible) canvasQueue.push(this)
}
draw(){
throw new Error('Calling unimplemented draw() method')
}
onPropChanged(propName, options, oldPropValue) {
var ret = super.onPropChanged(...arguments)
switch (propName) {
case 'color':
this.cacheCanvasStyle()
this.batchDraw()
return
}
return ret
}
onRemove() {
this.off('resize')
super.onRemove()
}
}
Canvas.dynamicProps = Canvas.prototype.constructor.dynamicProps.concat(
'on',
'off'
)
module.exports = Canvas

View file

@ -0,0 +1,75 @@
var Widget = require('./widget')
class Container extends Widget {
constructor(options) {
super(options)
this.on('widget-created', (e)=>{
if (e.widget.parent === this) {
var index = e.index
if (index !== undefined) {
if (!this.children[index]) {
this.children[index] = e.widget
} else {
this.children.splice(index, 0, e.widget)
}
} else {
this.children.push(e.widget)
}
}
})
this.on('widget-removed', (e)=>{
if (e.widget.parent === this) {
this.children.splice(this.children.indexOf(e.widget), 1)
}
})
}
alignChildrenProps() {
// this is needed after editor.undo to fix data shifting:
// say we have children [a, b, c] bound with session data [a, b, c]
// we delete one widget [ b, c] the data changes too: [ b, c]
// undo first only mutates the data: [a, b, c]
// so children have their data mutated too, child 'b' gets data 'a' and so on
// each child has to get the data corresponding to its index again.
// ...right ? :)
var tabs = this.getProp('tabs'),
widgets= this.getProp('widgets'),
type = tabs && tabs.length ? 'tabs' : widgets && widgets.length ? 'widgets' : null,
data = type ? this.getProp(type) : null
if (!type) return
for (let i in this.children) {
if (this.children[i] && data[i]) {
this.children[i].props = data[i]
this.children[i].cachedProps[type] = this.children[i].props[type]
if (this.children[i].alignChildrenProps) {
this.children[i].alignChildrenProps()
}
}
}
}
onRemove() {
super.onRemove()
}
}
module.exports = Container

View file

@ -0,0 +1,60 @@
var osc = require('../../osc')
module.exports = class OscReceiver {
constructor(address, value, parent, propName) {
try {
this.value = JSON.parse(value)
} catch (err) {
this.value = value
}
this.parent = parent
this.propNames = [propName]
this.bindedCallback = this.callback.bind(this)
this.setAddress(address)
}
setAddress(address) {
if (this.address !== address) {
if (this.address) osc.removeEventContext(this.parent, this.address, this.bindedCallback)
this.address = address
osc.on(this.address, this.bindedCallback, {context: this.parent})
}
}
addProp(propName){
if (!this.propNames.includes(propName)) this.propNames.push(propName)
}
callback(args) {
if (typeof args !== 'object') args = [args]
var preArgs = this.parent.getProp('preArgs') || []
if (!Array.isArray(preArgs) && preArgs !== '') preArgs = [preArgs]
if (args.length >= preArgs.length) {
for (var i in preArgs) {
if (preArgs[i] !== args[i]) return
}
var val = args.slice(preArgs.length)
if (val.length < 2) val = val[0]
try {
this.value = JSON.parse(val)
} catch (err) {
this.value = val
}
this.parent.updateProps(this.propNames, this.parent)
}
}
}

View file

@ -0,0 +1,866 @@
var EventEmitter = require('../../events/event-emitter'),
osc = require('../../osc'),
nanoid = require('nanoid/generate'),
widgetManager = require('../../managers/widgets'),
{math} = require('../utils'),
scopeCss = require('scope-css'),
{iconify} = require('../../ui/utils'),
resize = require('../../events/resize'),
OscReceiver = require('./osc-receiver'),
{deepCopy, deepEqual} = require('../../utils'),
updateWidget = ()=>{}
var oscReceiverState = {}
var OSCProps = [
'precision',
'address',
'preArgs',
'target',
'bypass'
]
var dummyDOM
DOM.ready(()=>{
dummyDOM = DOM.create('<div></div>')
})
setTimeout(()=>{
updateWidget = require('../../editor/data-workers').updateWidget
})
class Widget extends EventEmitter {
static defaults(insert={}, except=[], push={}) {
var defaults = {
type: {type: 'string', value: 'auto', help: ''},
id: {type: 'string', value: 'auto', help: 'Widgets sharing the same `id` will act as clones and update each other\'s value(s) without sending extra osc messages.' },
linkId: {type: 'string|array', value: '', help: [
'Widgets sharing the same `linkId` update each other\'s value(s) AND send their respective osc messages.',
'When prefixed with >>, the `linkId` will make the widget act as a master (sending but not receiving)',
'When prefixed with <<, the `linkId` will make the widget act as a slave (receiving but not sending)'
]},
_geometry:'geometry',
left: {type: 'number|string', value: 'auto', help: [
'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
'Otherwise, the widget will be absolutely positioned'
]},
top: {type: 'number|percentage', value: 'auto', help: [
'When both top and left are set to auto, the widget is positioned according to the normal flow of the page (from left to right, by order of creation).',
'Otherwise, the widget will be absolutely positioned'
]},
width: {type: 'number|percentage', value: 'auto', help: ''},
height: {type: 'number|percentage', value: 'auto', help: ''},
_style:'style',
label: {type: 'string|boolean', value: 'auto', help: [
'Set to `false` to hide completely',
'Insert icons using the prefix ^ followed by the icon\'s name : ^play, ^pause, etc'
]},
color: {type: 'string', value: 'auto', help: 'CSS color code. Set to "auto" to inherit from parent widget.'},
css: {type: 'string', value: '', help: 'CSS rules'},
_value: 'value',
default: {type: '*', value: '', help: 'If set, the widget will be initialized with this value when the session is loaded.'},
value: {type: '*', value: '', help: 'Define the widget\'s value depending on other widget\'s values / properties using property inheritance and property maths'},
_osc: 'osc',
precision: {type: 'integer|string', value: 2, help: [
'Defines the number of decimals to display and to send.',
'Set to `0` to send integers only.',
'Data type can be specified by appending a valid osc type tag to the precision value, for example : `3d` will make the widget send double precision numbers rounded to three decimals'
]},
address: {type: 'string', value: 'auto', help: 'OSC address for sending messages, it must start with a /'},
preArgs: {type: '*|array', value: '', help: [
'A value or array of values that will be prepended to the OSC messages.',
'Values can be defined as objects if the osc type tag needs to be specified: `{type: "i", value: 1}`'
]},
target: {type: 'string|array|null', value: '', help: [
'This defines the targets of the widget\'s OSC messages',
'- A `string` or `array` of strings formatted as follow: `ip:port` or `["ip:port"]`',
'- If midi is enabled, targets can be `midi:device_name`',
'- The special item `"self"` can be used to refer to the emitting client directly.',
'- If no target is set, messages can still be sent if the server has default targets',
'- The server\'s default targets can be bypassed by setting one of the items to `null`'
]},
bypass: {type: 'boolean', value: false, help: 'Set to `true` to prevent the widget from sending any osc message'}
}
// okay that's bad, but keys happen to be ordered anyway...
var alterDefaults = {}
for (var k in defaults) {
if (k === '_value') {
for (var l in insert) {
alterDefaults[l] = insert[l]
}
}
if (except.indexOf(k) < 0) alterDefaults[k] = defaults[k]
}
for (var m in push) {
alterDefaults[m] = push[m]
}
alterDefaults._props = function() {
var props = {}
for (var k in this) {
if (k[0] !== '_') {
props[k] = this[k].value
}
}
return props
}
return alterDefaults
}
constructor(options={}) {
super()
this.widget = DOM.create(options.html)
this.props = options.props
this.errors = {}
this.parsers = {}
this.parent = options.root ? widgetManager : options.parent
this.parentNode = options.parentNode
this.hash = nanoid('abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZ', 10)
this.children = []
this.reCreateOptions = options.reCreateOptions
// strip parent ? no position
if (this.parent && this.parent.props && this.parent.props.type == 'strip') {
delete this.props.top
delete this.props.left
delete this.props[this.parent.getProp('horizontal') ? 'height' : 'width']
}
this.createPropsCache()
if (this.getProp('id') == 'root' && !options.root) {
this.cachedProps.id = '_root'
this.errors.id = 'There can only be one root'
}
this.createLinkedPropsBindings()
this.disabledProps = []
// cache precision
if (this.props.precision != undefined) {
this.precision = Math.min(20,Math.max(this.getProp('precision', undefined, false),0))
}
if (options.container) {
this.container = DOM.create(`
<div class="widget ${options.props.type}-container" id="${this.hash}" data-widget="${this.hash}"></div>
`)
this.label = DOM.create('<div class="label"></div>')
this.container.appendChild(this.label)
this.container.appendChild(this.widget)
this.container._widget_instance = this
this.setContainerStyles()
} else {
this.container = dummyDOM
}
}
contains(widget) {
if (this.children.indexOf(widget) > 0) return true
var parent = widget.parent
while (parent && parent !== widgetManager) {
if (parent === this) return true
parent = parent.parent
}
return false
}
getAllChildren() {
var children = []
for (var i = 0; i < this.children.length; i++) {
if (!this.children[i]) continue
children.push(this.children[i])
children = children.concat(this.children[i].getAllChildren())
}
return children
}
created(index) {
this.trigger('widget-created', [{
id: this.getProp('id'),
widget: this,
options: this.reCreateOptions,
index: index
}])
}
changed(options) {
this.trigger('change', [{
widget: this,
options: options,
id: this.getProp('id'),
linkId: this.getProp('linkId')
}])
}
sendValue(overrides, options={}) {
if (this.selfLinkedOSCProps) {
this.updateProps(this.selfLinkedOSCProps, this)
}
if (this.getProp('bypass') && !options.force) return
var data = {
h:this.hash,
v:this.value
}
if (overrides) {
for (var k in overrides) {
data[k] = overrides[k]
}
}
if (options.syncOnly) {
osc.sync(data)
} else {
osc.send(data)
}
}
setValue() {}
getValue(withPrecision) {
return deepCopy(this.value, withPrecision ? this.precision : undefined)
}
getSplit() {}
createPropsCache() {
// @{props} links lists
this.linkedProps = {}
this.nestedLinkedProps = {}
this.linkedPropsValue = {}
// OSC{/path} receivers
if (this.oscReceivers) {
this.removeOscReceivers()
}
this.oscReceivers = {}
// Cache resolved props
this.cachedProps = {}
for (var k in this.props) {
if (k != 'widgets' && k != 'tabs') {
this.cachedProps[k] = this.resolveProp(k, undefined, true)
} else {
this.cachedProps[k] = this.props[k]
}
}
this.createLinkedPropsBindings()
}
createLinkedPropsBindings() {
if (!this.linkedCreatedCallback && Object.keys(this.linkedProps).length) {
this.linkedCreatedCallback = (e)=>{
this.onLinkedPropsChanged(e, 'widget-created')
}
this.linkedPropChangedCallback = (e)=>{
this.onLinkedPropsChanged(e, 'prop-changed')
}
widgetManager.on('widget-created', this.linkedCreatedCallback, {context: this})
widgetManager.on('prop-changed', this.linkedPropChangedCallback, {context: this})
} else if (this.linkedCreatedCallback && !Object.keys(this.linkedPropsValue).length) {
widgetManager.removeEventContext('widget-created', this.linkedCreatedCallback, {context: this})
widgetManager.removeEventContext('prop-changed', this.linkedPropChangedCallback, {context: this})
}
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.removeEventContext('change', this.linkedValueChangedCallback, {context: this})
}
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.removeEventContext(this)
for (var i in this.oscReceivers) {
oscReceiverState[i] = this.oscReceivers[i].value
}
this.oscReceivers = {}
}
updateLinkedPropsWithNesting(i) {
// 1. remove all linked props found in properties bound to the nested link
// 2. resolve these props again and recreate links (3rd arg to true)
for (var prop of this.nestedLinkedProps[i]) {
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]
}
}
}
this.resolveProp(prop, undefined, true, this)
}
}
resolveProp(propName, propValue, storeLinks=true, originalWidget, originalPropName, context) {
propValue = propValue !== undefined ? propValue : deepCopy(this.props[propName])
originalWidget = originalWidget || this
originalPropName = originalPropName || propName
var variables = {},
mathscope = context || {},
varnumber = 0
if (typeof propValue == 'string') {
propValue = propValue.replace(/@\{[^{}]*(@\{[^{}]*\})*[^{}]*\}/g, (m, nested)=>{
// pretty regexp:
// @\{
// [^{}]*
// (
// @\{
// [^{}]*
// \}
// )*
// [^{}]*
// \}
if (nested) {
m = m.replace(nested, this.resolveProp(propName, nested, storeLinks ? 'nested' : false, this))
}
let id = m.substr(2, m.length - 3).split('.'),
k, subk
if (id.length > 1) {
k = id.pop()
subk = undefined
if (id.length > 1) {
subk = k
k = id.pop()
}
id = id.join('.')
} else {
id = id[0]
k = 'value'
}
// backward compat
if (k === '_value') k = 'value'
var widgets = id == 'parent' && this.parent ?
[this.parent] : id == 'this' ? [this] :
widgetManager.getWidgetById(id)
if (!widgets.length) {
var parent = this.parent
while (parent && parent != widgetManager) {
if (parent.getProp('id') == id) {
widgets.push(parent)
break
}
parent = parent.parent
}
}
// ignore clone wrapper in @parent stack (https://github.com/jean-emmanuel/open-stage-control/issues/379)
if (widgets[0] === this.parent && this.parent.getProp('type') === 'clone') widgets = [this.parent.parent]
if (storeLinks) {
if (k == 'value') {
if (!this.linkedPropsValue[id]) this.linkedPropsValue[id] = []
if (this.linkedPropsValue[id].indexOf(propName) == -1) this.linkedPropsValue[id].push(propName)
} else {
if (!this.linkedProps[id]) this.linkedProps[id] = []
if (this.linkedProps[id].indexOf(propName) == -1) this.linkedProps[id].push(propName)
}
if (storeLinks === 'nested') {
if (!this.nestedLinkedProps[id]) this.nestedLinkedProps[id] = []
if (this.nestedLinkedProps[id].indexOf(propName) == -1) this.nestedLinkedProps[id].push(propName)
}
}
for (var i in widgets) {
if (widgets[i] === widgetManager) continue
if (widgets[i].props[k] !== undefined || k === 'value') {
if (k !== 'value' && originalPropName == k && widgets[i].props.id == originalWidget.props.id) {
return undefined
}
var r = k == 'value' ?
widgets[i].getValue(true) :
widgets[i].resolveProp(k, undefined, storeLinks, originalWidget, originalPropName)
if (subk !== undefined && r !== undefined) r = r[subk]
var varname = 'VAR_' + varnumber
varnumber++
variables[varname] = r
mathscope[varname] = r
return varname
}
}
})
propValue = propValue.replace(/OSC\{([^}]+)\}/g, (m)=>{
let [address, value] = m.substr(4, m.length - 5).split(',').map(x=>x.trim()),
resolvedAddress = address.replace(/VAR_[0-9]+/g, (m)=>{
return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
})
if (!this.oscReceivers[address]) {
this.oscReceivers[address] = new OscReceiver(resolvedAddress, value, this, propName)
if (oscReceiverState[address]) {
this.oscReceivers[address].value = oscReceiverState[address]
delete oscReceiverState[address]
}
} else {
this.oscReceivers[address].setAddress(resolvedAddress)
this.oscReceivers[address].addProp(propName)
}
var r = this.oscReceivers[address].value
var varname = 'VAR_' + varnumber
varnumber++
variables[varname] = r
mathscope[varname] = r
return varname
})
try {
propValue = propValue.replace(/#\{(?:[^{}]|\{[^{}]*\})*\}/g, (m)=>{
// one bracket nesting allowed, if we need two: #\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}
// unescape brackets (not needed anymore, just here for backward compatibility)
m = m.replace(/\\(\{|\})/g, '$1')
// espace multiline strings
m = m.replace(/`([^`]*)`/g, (m)=>{
return m.replace(/"/g,'\\"').replace(/\n/g,'\\n').replace(/`/g,'"')
})
if (!this.parsers[m]) this.parsers[m] = math.compile(m.substr(2, m.length - 3).trim())
let r = this.parsers[m].eval(mathscope)
if (r instanceof math.type.ResultSet && !r.entries.length) {
r = ''
} else if (typeof r === 'object' && r !== null && r.valueOf) {
r = r.valueOf()
if (Array.isArray(r) && r.length == 1) r = r[0]
}
return typeof r != 'string' ? JSON.stringify(r) : r
})
} catch (err) {}
for (let k in variables) {
var v = typeof variables[k] === 'string' ? variables[k] : JSON.stringify(variables[k])
propValue = propValue.replace(new RegExp(k, 'g'), v)
}
// heuristic to avoid using JSON when unnecessary
// if the string doesn't starts with one of these chars
// it's going to fail
// ref in source: https://github.com/douglascrockford/JSON-js
if (' \n+-eE{([0123456789tfn"'.indexOf(propValue[0]) !== -1) {
try {
propValue = JSON.parse(propValue)
} catch (err) {}
}
} else if (propValue != null && typeof propValue == 'object') {
for (let k in propValue) {
propValue[k] = this.resolveProp(propName, propValue[k], storeLinks, originalWidget, originalPropName, context)
}
}
return propValue
}
getProp(propName) {
return this.cachedProps[propName]
}
updateProps(propNames, widget, options, updatedProps = []) {
if (propNames.includes('value')) {
propNames.splice(propNames.indexOf('value'), 1)
propNames.push('value')
}
var reCreate = false,
changedProps = []
for (var propName of propNames) {
if (widget === this && updatedProps.includes(propName)) continue
let propValue = this.resolveProp(propName, undefined, false),
oldPropValue = this.getProp(propName)
if (!deepEqual(oldPropValue, propValue)) {
if (!this.constructor.dynamicProps.includes(propName)) {
reCreate = true
} else {
this.cachedProps[propName] = propValue
changedProps.push({propName, oldPropValue})
}
}
}
if (reCreate && (!widget || !this.contains(widget)) && widget !== this && !(widget === this && updatedProps.length === 1 && updatedProps[0] === 'value')) {
return this.reCreateWidget({reCreateOptions: options})
} else if (changedProps.length) {
for (var i in changedProps) {
this.onPropChanged(changedProps[i].propName, options, changedProps[i].oldPropValue)
}
widgetManager.trigger('prop-changed', [{
id: this.getProp('id'),
props: changedProps,
widget: this,
options: options
}])
}
}
onPropChanged(propName, options, oldPropValue) {
switch(propName) {
case 'value':
this.setValue(this.getProp('value'), {sync: true, send: options && options.send})
return
case 'top':
case 'left':
this.setContainerStyles(['geometry'])
return
case 'height':
case 'width':
this.setContainerStyles(['geometry'])
resize.check(this.container)
return
case 'label':
this.setContainerStyles(['label'])
if (oldPropValue === false || this.getProp('label') === false) {
resize.check(this.container)
}
return
case 'css':
this.setContainerStyles(['css'])
this.onPropChanged('color')
var re = /width|height|display/
if (re.test(oldPropValue) || re.test(this.getProp('css'))) {
resize.check(this.container)
}
return
case 'color':
this.setContainerStyles(['color'])
return
case 'precision':
case 'address':
case 'preArgs':
case 'target':
case 'noSync':
if (propName == 'precision') this.precision = Math.min(20,Math.max(this.getProp('precision', undefined, false),0))
var data = {},
oldData = {
preArgs: propName == 'preArgs' ? oldPropValue : this.getProp('preArgs'),
address: propName == 'address' ? oldPropValue : this.getProp('address')
}
data[propName] = this.getProp(propName)
if (propName === 'address' && this.getSplit()) {
data['split'] = this.getSplit()
}
widgetManager.registerWidget(this, data, oldData)
return
}
}
setContainerStyles(styles = ['geometry', 'label', 'css', 'color']) {
if (styles.includes('geometry')) {
// geometry
for (let d of ['width', 'height', 'top', 'left']) {
let val = this.getProp(d),
geometry
if (val !== undefined) {
if (parseFloat(val) < 0) val = 0
geometry = parseFloat(val) == val ? parseFloat(val)+'rem' : val
}
if (geometry && geometry != 'auto') {
this.container.style[d] = geometry
if (d == 'width') this.container.style.minWidth = geometry
if (d == 'height') this.container.style.minHeight = geometry
if (d == 'top' || d == 'left') this.container.classList.add('absolute-position')
}
}
}
if (styles.includes('label')) {
// label
if (this.getProp('label') === false) {
this.container.classList.add('nolabel')
} else {
this.container.classList.remove('nolabel')
var label = this.getProp('label') == 'auto'?
this.getProp('id'):
iconify(this.getProp('label'))
this.label.innerHTML = label
}
}
if (styles.includes('css')) {
// css
var css = String(this.getProp('css')),
prefix = '#' + this.hash,
scopedCss = scopeCss(css, prefix),
unScopedCss = '',
extraCssClasses = []
// extra css "class" property
css = css.replace(/^[^\S\n]*class[^\S\n]*:[^\S\n]*([^;\n\s]+);?/igm, (m, c)=>{
if (c === 'widget' || c.includes('-container')) return
extraCssClasses.push(c.replace(/"'/g,''))
})
try {
dummyDOM.style = css
unScopedCss = dummyDOM.getAttribute('style') || ''
} catch(err) {
// fallback for browser that don't allow assigning "style" property
css
.replace(/\{[^}]*\}/g, '')
.replace(/^[^@#.]*:.*/gm, (m)=>{
unScopedCss += m[m.length - 1] === ';' ? m : m + ';'
})
}
if (scopedCss.indexOf('@keyframes') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s+([0-9]+%|to|from)', 'g'), ' $1')
if (scopedCss.indexOf('&') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s&', 'g'), prefix)
var style = DOM.create(`<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.widget)
}
// apply extra css classes
if (this.extraCssClasses && this.extraCssClasses.length) {
this.container.classList.remove(...this.extraCssClasses)
this.extraCssClasses = []
}
if (extraCssClasses.length) {
this.container.classList.add(...extraCssClasses)
this.extraCssClasses = extraCssClasses
}
}
if (styles.includes('color')) {
// color
this.container.style.setProperty('--color-custom', this.getProp('color') && this.getProp('color') != 'auto' ? this.getProp('color') : '')
}
}
reCreateWidget(options={}){
return updateWidget(this, options)
}
onRemove(){
widgetManager.removeEventContext(this)
this.removeOscReceivers()
}
}
Widget.dynamicProps = [
'top',
'left',
'height',
'width',
'label',
'css',
'value',
'color',
'precision',
'address',
'preArgs',
'target',
'bypass'
]
module.exports = Widget

View file

@ -0,0 +1,292 @@
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')
var excludedCloneClasses = ['widget', 'absolute-position', 'ui-resizable', 'ui-draggable', 'not-editable']
class Clone extends Container {
static defaults() {
return super.defaults({
_clone:'clone',
widgetId: {type: 'string', value: '', help: '`id` of the widget to clone'},
_overrides:'overrides',
props: {type: 'object', value: {}, help: 'Cloned widget\'s properties to override'},
}, ['label', 'color', 'linkId', '_value', 'default', 'value', '_osc', 'precision', 'address', 'preArgs', 'target', 'bypass'])
}
constructor(options) {
options.props.label = ''
options.props.variables = '@{parent.variables}'
super({...options, html: '<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()
}
}, {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.removeEventContext(this)
this.cloneTarget = null
}
bindTarget(target) {
if (!target) return
this.cloneTarget = target
// listen for cloneTarget's deletion
// if it is just edited, its recreation will be catched by the global 'widget-created' event handler
this.cloneTarget.on('widget-removed', (e)=>{
if (this.cloneTarget === e.widget) {
this.unbindTarget()
}
}, {context: this})
// listen for cloneTarget's content updates
this.cloneTarget.on('widget-created', (e)=>{
var {widget} = e,
parent = widget.parent
while (parent !== this.cloneTarget && parent !== widgetManager) {
// if updated widget is in a nested clone, ignore it:
// it will be handled by the nested clone that targets it
if (parent.getProp('type') === 'clone') return
parent = parent.parent
}
this.updateClone()
}, {context: this})
}
updateClone() {
if (this.cloneLock) return
this.cloneLock = true
var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')},
clone = this.children[0]
var delta = diff.diff(clone.props, data) || {},
[widget, patch] = diffToWidget(clone, delta),
changedProps = Object.keys(patch)
if (changedProps.length) {
diff.patch(widget.props, patch)
if (changedProps.some(x => !widget.constructor.dynamicProps.includes(x))) {
clone.reCreateWidget({reuseChildren: false})
this.updateContainer(false)
} else {
widget.updateProps(changedProps, this)
this.updateContainer(true)
}
}
this.cloneLock = false
}
updateContainer(checkResize) {
if (this.cloneTarget) {
var classes = [...this.cloneTarget.container.classList].filter(i=>excludedCloneClasses.indexOf(i) === -1)
if (!deepEqual(classes, this.cloneClass)) {
this.container.classList.remove(...this.cloneClass)
this.cloneClass = classes
this.container.classList.add(...this.cloneClass)
}
this.container.classList.remove('empty')
for (var w of this.getAllChildren()) {
w.container.classList.add('not-editable')
}
if (checkResize) resize.check(this.widget)
} else if (this.cloneClass.length) {
this.container.classList.remove(...this.cloneClass)
this.container.classList.add('empty')
this.cloneClass = []
this.widget.innerHTML = ''
widgetManager.removeWidgets(this.getAllChildren())
}
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'widgetId':
this.unbindTarget()
this.updateContainer(false)
this.bindTarget(this.getCloneTarget())
if (this.cloneTarget) this.createClone()
return
}
}
onRemove(){
this.unbindTarget()
super.onRemove()
}
}
Clone.dynamicProps = Clone.prototype.constructor.dynamicProps.concat(
'widgetId'
)
module.exports = Clone

View file

@ -0,0 +1,178 @@
var Panel = require('./panel'),
Widget = require('../common/widget'),
{icon, iconify} = require('../../ui/utils'),
resize = require('../../events/resize'),
doubletab = require('../mixins/double_tap')
module.exports = class Modal extends Panel {
static defaults() {
return Widget.defaults({
_modal:'modal',
doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the modal require a double tap to open instead of a single tap'},
popupLabel: {type: 'string', value: '', help: 'Alternative label for the modal popup'},
popupWidth: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
popupHeight: {type: 'number|percentage', value: '80%', help: 'Modal popup\'s size'},
popupLeft: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
popupTop: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
}, [], {
_chidlren:'children',
variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object'},
value: {type: 'integer', value: '', help: [
'Defines the modal\'s state:`0` for closed, `1` for opened'
]},
})
}
constructor(options) {
options.props.scroll = true
super(options)
this.disabledProps = []
this.popup = DOM.create(`
<div class="popup">
<div class="popup-wrapper">
<div class="popup-title closable"><span class="popup-label"></span><span class="closer">${icon('times')}</span></div>
<div class="popup-content"></div>
</div>
</div>
`)
this.container.appendChild(this.popup)
// convert dimensions / coordinates to rem
var geometry = {}
for (var g of ['Width', 'Height', 'Left', 'Top']) {
geometry[g] = parseFloat(this.getProp('popup' + g)) == this.getProp('popup' + g) ? parseFloat(this.getProp('popup' + g)) + 'rem' : this.getProp('popup' + g)
}
this.popup.style.setProperty('--width', geometry.Width)
this.popup.style.setProperty('--height', geometry.Height)
if (geometry.Left !== 'auto') {
this.popup.style.setProperty('--left', geometry.Left)
this.popup.classList.add('x-positionned')
}
if (geometry.Top !== 'auto') {
this.popup.style.setProperty('--top', geometry.Top)
this.popup.classList.add('y-positionned')
}
this.light = this.container.appendChild(DOM.create('<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
this.setValue(1, {sync:true, send:true})
})
}
var closer = DOM.get(this.popup, '.closer')[0]
this.popup.addEventListener('fast-click',(e)=>{
if ((e.target === this.popup || e.target === closer) && this.value == 1) {
e.detail.preventOriginalEvent = true
this.setValue(0, {sync:true, send:true})
}
})
this.escapeKeyHandler = ((e)=>{
if (e.keyCode==27) this.setValue(0, {sync:true, send:true})
}).bind(this)
this.parentScroll = [0,0]
this.value = 0
this.init = false
}
setValue(v, options={}) {
if (this.init === undefined) return
this.value = v ? 1 : 0
if (!this.init && this.value) {
var label = this.getProp('popupLabel') ? iconify(this.getProp('popupLabel')) : DOM.get(this.container, '> .label')[0].innerHTML
DOM.get(this.popup, '.popup-title .popup-label')[0].innerHTML = label
DOM.get(this.popup, '.popup-content')[0].appendChild(this.widget)
this.init = true
}
this.popup.classList.toggle('show', this.value)
this.container.classList.toggle('on', this.value)
this.light.classList.toggle('on', this.value)
this.bindEscKey(this.value)
if (this.value) {
resize.check(this.widget, true)
}
if (this.init) this.fixParents()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
bindEscKey(set) {
if (set) {
document.addEventListener('keydown', this.escapeKeyHandler)
} else {
document.removeEventListener('keydown', this.escapeKeyHandler)
}
}
onRemove() {
this.bindEscKey(false)
this.setValue(0)
super.onRemove()
}
fixParents() {
var parent = this.parent,
scrollFixed = false
while (parent && parent.props) {
// scroll
if (!scrollFixed && parent.getProp('type') == 'tab') {
if (this.value) {
this.parentScroll = [parent.widget.scrollLeft, parent.widget.scrollTop]
}
parent.widget.scrollLeft = this.value ? 0 : this.parentScroll[0]
parent.widget.scrollTop = this.value ? 0 : this.parentScroll[1]
parent.widget.style.overflow = this.value ? 'hidden' : ''
scrollFixed = true
}
// stacking
parent.container.style.zIndex = this.value ? 'initial' : ''
parent = parent.parent
}
}
}

View file

@ -0,0 +1,205 @@
var Container = require('../common/container'),
widgetManager = require('../../managers/widgets'),
parser = require('../../parser')
class Panel extends Container {
static defaults() {
return super.defaults({
_panel:'panel',
scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
border: {type: 'boolean', value: true, help: 'By default, widgets in panels/strip have their border disabled, except for panels and strips. Set to `false` to apply this rule to the panel too'},
}, [], {
_children:'children',
variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously.'},
tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously'},
value: {type: 'integer', value: '', help: [
'Defines currently opened tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
super({...options, html: '<div class="panel"></div>'})
if (this.getProp('scroll') === false) this.widget.classList.add('noscroll')
if (this.getProp('border') === false) this.container.classList.add('noborder')
if (this.getProp('tabs') && this.getProp('tabs').length) this.widget.classList.add('has-tabs')
this.value = -1
this.tabs = []
if (this.getProp('tabs') && this.getProp('tabs').length) {
this.widget.appendChild(DOM.create('<div class="navigation"><ul class="tablist"></ul></div>'))
this.navigation = DOM.get(this.widget, '.tablist')[0]
this.wrapper = this.widget.appendChild(DOM.create('<div class="tabs-wrapper"></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.wrapper.appendChild(this.children[i].container)
this.children[i].parent = this
this.children[i].parentNode = this.wrapper
} else {
parser.parse({
data: this.getProp('tabs')[i],
parentNode: this.wrapper,
parent: this,
tab: true,
index: i
})
}
}
if (options.children) this.alignChildrenProps()
this.createNavigation()
this.navigation.addEventListener('fast-click', (e)=>{
if (!e.target.hasAttribute('data-widget')) return
var index = DOM.index(e.target)
this.setValue(index, {sync: true, send:this.value != index})
})
this.on('tab-created', (e)=>{
this.createNavigation()
e.stopPropagation = true
})
this.setValue(this.getProp('value') || 0)
} else if (this.getProp('widgets') && this.getProp('widgets').length) {
this.children = options.children || new Array(this.getProp('widgets').length)
for (let i = 0; i < this.children.length; i++) {
if (this.children[i]) {
this.widget.appendChild(this.children[i].container)
this.children[i].parent = this
this.children[i].parentNode = this.widget
} else {
parser.parse({
data: this.getProp('widgets')[i],
parentNode: this.widget,
parent: this,
index: i
})
}
}
if (options.children) this.alignChildrenProps()
}
if (this.getProp('tabs') && !this.getProp('tabs').length) {
this.disabledProps.push(
'precision', 'address', 'preArgs', 'target', 'bypass',
'value', 'default'
)
}
if (this.getProp('widgets') && !this.getProp('widgets').length) {
this.disabledProps.push(
'scroll'
)
}
}
createNavigation() {
this.navigation.innerHTML = ''
this.tabs = []
var html = ''
DOM.each(this.wrapper, '> .widget', (tab)=>{
let widget = widgetManager.getWidgetByElement(tab),
style = widget.getProp('color') == 'auto' ? '' : `style="--color-custom:${widget.getProp('color')}"`
this.tabs.push(widget)
html += `<li class="tablink" data-widget="${widget.hash}" ${style}><a><span>${DOM.get(tab, '> .label')[0].innerHTML}</span></a></li>`
})
this.navigation.innerHTML = html
this.setValue(this.value)
}
setValue(v, options={}) {
if (this.tabs.length && typeof v == 'number' && v >= 0 && v < this.tabs.length) {
for (let i in this.tabs) {
if (i != v) this.tabs[i].hide()
}
this.value = v
this.tabs[v].show()
DOM.each(this.navigation, 'li', (el)=>{el.classList.remove('on')})[v].classList.add('on')
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}
scroll(s) {
if (!s) {
return [this.widget.scrollLeft, this.widget.scrollTop]
} else {
this.widget.scrollLeft = s[0]
this.widget.scrollTop = s[1]
}
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
for (var w of this.children) {
if (w) w.onPropChanged('color')
}
return
}
}
onRemove() {
this.off('resize')
super.onRemove()
}
}
Panel.dynamicProps = Panel.prototype.constructor.dynamicProps.concat(
'variables'
)
module.exports = Panel

View file

@ -0,0 +1,93 @@
var Panel = require('./panel'),
Widget = require('../common/widget'),
{iconify} = require('../../ui/utils'),
{enableTraversingGestures, disableTraversingGestures} = require('../../events/drag')
class Root extends Panel {
static defaults() {
return Widget.defaults({}, ['label', '_geometry', 'left', 'top', 'width', 'height'], {
_children:'children',
traversing: {type: 'boolean', value: false, help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` or `auto` to limit affected widgets by the type of the first touched widget'},
variables: {type: '*', value: {}, help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object'},
id: {type: 'string', value: 'root', help: 'Widgets sharing the same id will act as clones and update each other\'s value(s) without sending extra osc messages' },
value: {type: 'integer', value: '', help: [
'Defines currently opened tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
options.root = true
options.props.id = 'root'
options.props.scroll = true
options.props.label = false
super(options)
this.widget.classList.add('root')
this.disabledProps.push('id')
DOM.each(this.widget, '> .navigation', (el)=>{
el.classList.add('main')
})
if (this.getProp('traversing')) this.setTraversing()
}
createNavigation() {
super.createNavigation()
this.navigation.appendChild(DOM.create(`
<li class="not-editable">
<a id="open-toggle" class="${DOM.get('#sidepanel')[0].classList.contains('sidepanel-open')?'sidepanel-open':''}">${iconify('^bars')}</a>
</li>
`))
}
setTraversing(update) {
var traversing = this.getProp('traversing')
disableTraversingGestures(this.widget)
if (traversing) {
enableTraversingGestures(this.widget, {smart: typeof traversing === 'string' && traversing.match(/smart|auto/)})
}
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'traversing':
this.setTraversing()
return
}
}
}
Root.dynamicProps = Root.prototype.constructor.dynamicProps.concat(
'traversing'
)
module.exports = Root

View file

@ -0,0 +1,60 @@
var Panel = require('./panel'),
Widget = require('../common/widget')
module.exports = class Strip extends Panel {
static defaults() {
return Widget.defaults({
_strip: 'strip',
scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display widgets horizontally'},
stretch: {type: 'boolean', value: true, help: 'Set to `true` to stretch widgets evenly'},
border: {type: 'boolean', value: true, help: 'By default, widgets in panels/strip have their border disabled, except for panels and strips. Set to `false` to apply this rule to the panel too'},
spacing: {type: 'integer|percentage', value: 0, help: 'Adds space between widgets. Percents are always relative to the strips width'}
}, [], {
_children:'children',
variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
widgets: {type: 'array', value: [], help: [
'Each element of the array must be a widget object',
'- By default, children widgets that don\'t have an explicit `width`/`height` set will be shrinked to respect the sizes specified by others',
'- Adding `flex:1;` to a children\'s `css` will give it the ability the fill the remaining space',
'- Multiple children can have a `flex:x;` css property (`x` will ponderate their expansion)'
]}
})
}
constructor(options) {
var defaults = Panel.defaults()._props()
for (var k in defaults) {
if (!options.props.hasOwnProperty(k))
options.props[k] = defaults[k]
}
super(options)
this.disabledProps = []
if (this.getProp('spacing')) {
var spacing = this.getProp('spacing')
if (!isNaN(spacing)) spacing += 'rem'
this.widget.style.setProperty('--spacing', spacing)
}
this.container.classList.add(this.getProp('horizontal') ? 'horizontal' : 'vertical')
if (this.getProp('stretch')) this.container.classList.add('stretch')
}
setValue(){}
getValue(){}
}

View file

@ -0,0 +1,69 @@
var Panel = require('./panel'),
Widget = require('../common/widget'),
resize = require('../../events/resize')
module.exports = class Tab extends Panel {
static defaults() {
return Widget.defaults({}, ['_geometry', 'left', 'top', 'width', 'height'], {
_children:'children',
variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A tab cannot contain widgets and tabs simultaneously'},
tabs: {type: 'array', value: [], help: 'Each element of the array must be a tab object. A tab cannot contain widgets and tabs simultaneously'},
value: {type: 'integer', value: '', help: [
'Defines currently opened tab in the widget',
'A tab can be opened only by setting its parent\'s value'
]},
})
}
constructor(options) {
options.props.scroll = true
super(options)
this.container.classList.add('show')
this.widget.classList.add('tab')
this.detached = false
}
hide() {
if (this.detached) return
this.container.removeChild(this.widget)
this.container.classList.remove('show')
this.detached = true
}
show() {
if (!this.detached) return
this.container.appendChild(this.widget)
this.container.classList.add('show')
this.detached = false
resize.check(this.widget, true)
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'label':
case 'color':
if (this.parent.createNavigation) this.parent.createNavigation()
return
}
}
}

View file

@ -0,0 +1,73 @@
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'),
push: require('./buttons/push'),
switch: require('./buttons/switch'),
dropdown: require('./buttons/dropdown'),
// pads
xy: require('./pads/xy'),
rgb: require('./pads/rgb'),
multixy: require('./pads/multixy'),
// matrices
matrix: require('./matrices/matrix'),
multitoggle: require('./matrices/multitoggle'),
multipush: require('./matrices/multipush'),
multifader: require('./matrices/multifader'),
keyboard: require('./matrices/keyboard'),
// plots
led: require('./plots/led'),
rgbled: require('./plots/rgbled'),
plot: require('./plots/plot'),
eq: require('./plots/eq'),
visualizer: require('./plots/visualizer'),
meter: require('./plots/meter'),
text: require('./plots/text'),
image: require('./plots/image'),
svg: require('./plots/svg'),
frame: require('./plots/frame'),
// containers
strip: require('./containers/strip'),
panel: require('./containers/panel'),
modal: require('./containers/modal'),
clone: require('./containers/clone'),
// state switchers
switcher: require('./switchers/switcher'),
crossfader: require('./switchers/crossfader'),
// inputs
input: require('./inputs/input'),
keys: require('./inputs/keys'),
script: require('./inputs/script'),
gyroscope: require('./inputs/gyroscope'),
// maths
// deprecated / hidden
formula: require('./maths/formula')
}
module.exports.categories = {
'Sliders':['fader','knob', 'encoder', 'range'],
'Buttons':['toggle','push','switch', 'dropdown'],
'Pads':['xy','rgb','multixy'],
'Matrices':['matrix', 'multifader','multitoggle','multipush', 'keyboard'],
'Plots':['plot','eq','visualizer','led', 'rgbled','meter','text', 'image', 'svg', 'frame'],
'Containers':['panel','strip','modal', 'clone'],
'Switchers':['switcher','crossfader'],
'Inputs':['input', 'keys', 'script', 'gyroscope']
}

View file

@ -0,0 +1,118 @@
var Widget = require('../common/widget'),
GyroNorm = require('gyronorm/dist/gyronorm.complete.min.js'),
{iconify} = require('../../ui/utils'),
{clip} = require('../utils')
class Gyroscope extends Widget {
static defaults() {
return super.defaults({
_gyroscope: 'gyroscope',
frequency: {type: 'number', value: 30, help: 'Value update frequency (updates per seconds)'},
normalize: {type: 'boolean', value: true, help: 'Normalize gravity related values'},
compass: {type: 'boolean', value: false, help: 'Set to `true` to return the orientation values with respect to the actual north direction of the world instead of the head direction of the device'},
screenAdjusted: {type: 'boolean', value: false, help: 'Set to `true` to return screen adjusted values'}
}, [], {
value: {type: 'object', value: '', help: [
'The gyroscope\'s value is an object containing multiple values, which can be used by other widgets via the property maths syntax',
'- `value.do.alpha`: deviceorientation event alpha',
'- `value.do.beta`: deviceorientation event beta',
'- `value.do.gamma`: deviceorientation event gamma',
'- `value.do.absolute`: deviceorientation event absolute',
'- `value.dm.x`: devicemotion event acceleration x',
'- `value.dm.y`: devicemotion event acceleration y',
'- `value.dm.z`: devicemotion event acceleration z',
'- `value.dm.gx`: devicemotion event accelerationIncludingGravity x',
'- `value.dm.gy`: devicemotion event accelerationIncludingGravity y',
'- `value.dm.gz`: devicemotion event accelerationIncludingGravity z',
'- `value.dm.alpha`: devicemotion event rotationRate alpha',
'- `value.dm.beta`: devicemotion event rotationRate beta',
'- `value.dm.gamma`: devicemotion event rotationRate gamma'
]},
})
}
constructor(options) {
var html = `
<div class="gyroscope">
${iconify('^compass')}
</div>
`
super({...options, html: html})
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,153 @@
var Canvas = require('../common/canvas'),
{deepCopy} = require('../../utils')
module.exports = class Input extends Canvas {
static defaults() {
return super.defaults({
_input:'input',
vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
align: {type: 'string', value: '', help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
editable: {type: 'boolean', value: true, help: 'Set to `false` to make the input non-editable'}
})
}
constructor(options) {
var html = `
<div class="input">
<canvas></canvas>
</div>
`
super({...options, html: html})
this.value = ''
this.stringValue = ''
this.focused = false
if (this.getProp('vertical')) this.widget.classList.add('vertical')
if (this.getProp('align') === 'left') this.widget.classList.add('left')
if (this.getProp('align') === 'right') this.widget.classList.add('right')
if (this.getProp('editable')) {
this.canvas.setAttribute('tabindex', 0)
this.canvas.addEventListener('focus', this.focus.bind(this))
this.input = DOM.create('<input class="no-keybinding"></input>')
this.input.addEventListener('blur', (e)=>{
this.blur(false)
})
this.input.addEventListener('keydown', (e)=>{
if (e.keyCode==13) this.blur()
if (e.keyCode==27) this.blur(false)
})
} else {
this.widget.classList.add('not-editable')
}
}
focus() {
if (this.focused) return
this.focused = true
this.canvas.setAttribute('tabindex','-1')
this.input.value = this.stringValue
this.widget.insertBefore(this.input, this.canvas)
this.input.focus()
}
blur(change=true) {
if (!this.focused) return
this.focused = false
if (change) this.inputChange()
this.canvas.setAttribute('tabindex','0')
this.widget.removeChild(this.input)
}
inputChange() {
this.setValue(this.input.value, {sync:true, send:true})
}
resizeHandle(event){
super.resizeHandle(event)
if (this.getProp('vertical')){
var ratio = CANVAS_SCALING * this.scaling
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
this.ctx.rotate(-Math.PI/2)
this.ctx.translate(-this.height * ratio, 0)
if (ratio != 1) this.ctx.scale(ratio, ratio)
}
}
setValue(v, options={} ) {
try {
this.value = JSON.parse(v)
} catch (err) {
this.value = v
}
this.stringValue = this.getStringValue()
this.batchDraw()
if (options.send && !options.fromSync) this.sendValue()
if (options.sync) this.changed(options)
}
draw() {
var v = this.stringValue,
width = this.getProp('vertical') ? this.height : this.width,
height = !this.getProp('vertical') ? this.height : this.width
if (this.getProp('unit') && v.length) v += ' ' + this.getProp('unit')
this.clear()
this.ctx.fillStyle = this.colors.text
if (this.textAlign == 'center') {
this.ctx.fillText(v, Math.round(width/2), Math.round(height/2))
} else if (this.textAlign == 'right') {
this.ctx.fillText(v, width, Math.round(height/2))
} else {
this.ctx.fillText(v, 0, Math.round(height/2))
}
this.clearRect = [0, 0, width, height]
}
getStringValue() {
if (this.value === undefined) return ''
return typeof this.value != 'string' ?
JSON.stringify(deepCopy(this.value, this.precision)).replace(/,/g, ', ') :
this.value
}
}

View file

@ -0,0 +1,142 @@
var Widget = require('../common/widget'),
{iconify} = require('../../ui/utils'),
keyboardJS = require('keyboardjs')
class Keys extends Widget {
static defaults() {
return super.defaults({
_keys:'keys',
binding: {type: 'string|array', value: '', help: 'Key combo `string` or `array` of strings (see <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. Formulas are given extras variables in this context:',
'- `key`: pressed key name (usefull for handling multiple keys with a single keys widget)',
'- `ctrl`: control key state',
'- `alt`: alt key state',
'- `shift`: shift key state',
'- `super`: command/windows key state'
]},
keyup: {type: 'string', value: '', help: 'Same as `keydown`, but evaluated when releasing the key combo'},
repeat: {type: 'boolean', value: true, help: 'Set to `false` to prevent keydown repeats when holding the key combo pressed'},
})
}
constructor(options) {
var html = `
<div class="keys">
${iconify('^keyboard')}
</div>
`
super({...options, html: html})
if (this.getProp('binding')) {
this.widget.appendChild(DOM.create(`<span>${this.getProp('binding')}</span>`))
this.keyDownHandler = this.keyDown.bind(this)
this.keyUpHandler = this.keyUp.bind(this)
keyboardJS.bind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
}
}
onRemove() {
super.onRemove()
if (this.getProp('binding')) {
keyboardJS.unbind(this.getProp('binding'), this.keyDownHandler, this.keyUpHandler)
}
}
keyDown(e) {
if (e.target.classList.contains('no-keybinding')) return
if (!this.getProp('repeat') && e) e.preventRepeat()
if (this.getProp('keydown') !== '') {
var context = {
key: e.key,
ctrl: e.ctrlKey,
shift: e.shiftKey,
alt: e.altKey,
meta: e.metaKey
}
this.setValue(this.resolveProp('keydown', undefined, false, false, false, context), {sync: true, send: true})
}
this.showKeydown()
}
keyUp(e) {
if (e.target.classList.contains('no-keybinding')) return
if (this.getProp('keyup') !== '') {
var context = {
key: e.key,
ctrl: e.ctrlKey,
shift: e.shiftKey,
alt: e.altKey,
meta: e.metaKey
}
this.setValue(this.resolveProp('keyup', undefined, false, false, false, context), {sync: true, send: true})
}
this.showKeyup()
}
showKeydown(){
this.widget.style.setProperty('--opacity', 1)
}
showKeyup(){
this.widget.style.setProperty('--opacity', 0.75)
}
setValue(v, options = {}) {
this.value = v
// if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}
Keys.dynamicProps = Keys.prototype.constructor.dynamicProps.concat(
'keydown',
'keyup',
'repeat'
)
module.exports = Keys

View file

@ -0,0 +1,95 @@
var Widget = require('../common/widget'),
widgetManager = require('../../managers/widgets'),
{iconify} = require('../../ui/utils')
class Script extends Widget {
static defaults() {
return super.defaults({
_script:'script',
condition: {type: 'string', value: 1, help: [
'When the widget receives a value, if this property return a falsy value, the script property won\'t be evaluated. If it\'s non-falsy, it will be evaluated normally. Formulas are given one extra variable in this context:',
'- `value`: the value received by the widget'
]},
script: {type: 'string', value: '', help: [
'This property is evaluated each time the widget receives a value if condition is non-falsy. Formulas are given extras variables in this context:',
'- `value`: the value received by the widget',
'- `send(target, address, arg1, arg2, ...)`: function for sending osc messages (ignores the script\'s targets and the server\'s defaults unless `target` is `false`; ignores the script\'s `preArgs`)',
'- `set(id, value)`: function for setting a widget\'s value'
]}
})
}
constructor(options) {
var html = `
<div class="script">
${iconify('^code')}
</div>
`
super({...options, html: html})
}
static scriptSet(id, value, options) {
var widgets = widgetManager.getWidgetById(id)
for (var i = widgets.length - 1; i >= 0; i--) {
return widgets[i].setValue(value, options)
}
}
scriptSend(target, address, ...args) {
var overrides = {
address,
v: args,
preArgs: []
}
if (target) overrides.target = Array.isArray(target) ? target : [target]
this.sendValue(overrides)
}
setValue(v, options={} ) {
var context = {
value: v,
send: options.send ? this.scriptSend.bind(this) : ()=>{},
set: (id, value)=>{Script.scriptSet(id, value, options)},
log: console.log
}
var condition = this.resolveProp('condition', undefined, false, false, false, {value: v})
if (condition) this.resolveProp('script', undefined, false, false, false, context)
// if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
}
Script.dynamicProps = Script.prototype.constructor.dynamicProps.concat(
'condition',
'script'
)
module.exports = Script

View file

@ -0,0 +1,197 @@
var Widget = require('../common/widget'),
widgetManager = require('../../managers/widgets'),
{math} = require('../utils'),
Input = require('../inputs/input')
module.exports = class Formula extends Widget {
static defaults() {
return super.defaults({
_formula: 'formula',
formula: {type: 'string', value: '', help: ''},
condition: {type: 'string', value: '', help: ''},
unit: {type: 'string', value: '', help: ''},
})
}
constructor(options) {
var html = `
<div class="formula">
</div>
`
super({...options, html: html})
this.formulaString = String(this.getProp('formula'))
this.conditionString = String(this.getProp('condition'))
this.input = new Input({
props:{
...Input.defaults()._props(),
editable:false,
precision:this.getProp('precision'),
unit: this.getProp('unit')
},
parent:this, parentNode:this.widget
})
this.widget.appendChild(this.input.widget)
this.linkedWidgets = []
if (this.formulaString.length) {
if (this.formulaString.match(/\$\{([^}]*)\}/g) != null) this.linkedWidgets = this.linkedWidgets.concat(this.formulaString.match(/\$\{([^}]*)\}/g).map((a)=>{return a.substr(2, a.length - 3)}))
}
if (this.conditionString.length) {
if (this.conditionString.match(/\$\{([^}]*)\}/g) != null) this.linkedWidgets = this.linkedWidgets.concat(this.conditionString.match(/\$\{([^}]*)\}/g).map((a)=>{return a.substr(2, a.length - 3)}))
}
try {
this.condition = math.compile(this.conditionString.replace(/\$\{([^}]*)\}/g, '_$1'))
delete this.errors.condition
} catch(err) {
this.errors.condition = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
}
try {
this.formula = math.compile(this.formulaString.replace(/\$\{([^}]*)\}/g, '_$1'))
delete this.errors.formula
} catch(err) {
this.errors.formula = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
}
this.conditionState = true
widgetManager.on('change', this.syncHandle.bind(this), {context: this})
if (this.formulaString.length) this.updateValue({options:{}})
}
syncHandle(e) {
if (this.linkedWidgets.indexOf(e.id)==-1 || !widgetManager.getWidgetById(e.id).length) return
this.updateValue(e)
}
updateValue(e){
var variables = {}
for (let id of this.linkedWidgets) {
if (id !== undefined) {
variables['_'+id] = 0
let widgets = widgetManager.getWidgetById(id)
for (let w of widgets) {
if (w.getValue) {
variables['_'+id] = w.getValue()
break
}
}
}
}
if (this.conditionString.length) {
try {
var s = this.condition.eval(variables).valueOf()
if (Array.isArray(s) && s.length == 1) s = s[0]
this.conditionState = s.data !== undefined ? s.data : s
delete this.errors.condition
} catch(err) {
this.errors.condition = 'Error parsing formula "' + this.conditionString + '" (' + err + ')'
this.conditionState = false
}
}
try {
var v = this.formula.eval(variables).valueOf()
if (Array.isArray(v) && v.length == 1) v = v[0]
this.value = v.data ? v.data : v
this.showValue()
if (e.options.sync && this.conditionState) this.changed(e.options)
if (e.options.send && this.conditionState) this.sendValue()
delete this.errors.formula
} catch(err) {
this.errors.formula = 'Error parsing formula "' + this.formulaString + '" (' + err + ')'
this.value = undefined
}
}
showValue() {
this.input.setValue(this.value)
if (this.getProp('condition').length && !this.conditionState) {
this.input.stringValue = '* ' + this.input.stringValue
this.input.batchDraw()
}
}
getSplit() {
return typeof this.getProp('split') == 'object' && this.getProp('split').length ? this.getProp('split') : false
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
if (this.input) this.input.onPropChanged('color')
return
}
}
onRemove() {
this.input.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,44 @@
var Container = require('../common/container'),
{enableTraversingGestures} = require('../../events/drag')
module.exports = class _matrix_base extends Container {
constructor(options) {
super({...options, html: '<div class="matrix"></div>'})
this.value = []
this.start = parseInt(this.getProp('start'))
this.on('change',(e)=>{
if (e.widget == this) return
this.value[DOM.index(e.widget.container)] = e.widget.getValue()
this.changed(e.options)
})
if (this.getProp('traversing')) enableTraversingGestures(this.widget)
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
for (var w of this.children) {
if (w) w.onPropChanged('color')
}
return
}
}
}

View file

@ -0,0 +1,104 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
module.exports = class Keyboard extends _matrix_base {
static defaults() {
return super.defaults({
_matrix: 'matrix',
keys: {type: 'number', value: 25, help: 'Defines the number keys'},
start: {type: 'number', value: 48, help: [
'MIDI note number to start with (default is C4)',
'Standard keyboards settings are: `[25, 48]`, `[49, 36]`, `[61, 36]`, `[88, 21]`'
]},
traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
on: {type: '*', value: 1, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
off: {type: '*', value: 0, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
}, ['_value', 'default', 'value'], {
split: {type: 'boolean|string', value: false, help: [
'`true`: the widget\'s index will be appended to the matrice\'s osc address',
'`false`: it will be prepended to the widget\'s preArgs',
'`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
]},
css: {type: 'string', value: '', help: [
'Available CSS variables:',
'- `--color-white:color;` (white keys color)',
'- `--color-black:color;` (black keys color)'
]}
})
}
constructor(options) {
super(options)
this.keys = parseInt(this.getProp('keys'))
var strData = JSON.stringify(options.props),
pattern = 'wbwbwwbwbwbw',
whiteKeys = 0, whiteKeys2 = 0, i
for (i = this.start; i < this.keys + this.start && i < 109; i++) {
if (pattern[i % 12] == 'w') whiteKeys++
}
for (i = this.start; i < this.keys + this.start && i < 109; i++) {
var data = JSON.parse(strData)
data.top = data.left = data.height = data.width = 'auto'
data.type = 'push'
data.id = this.getProp('id') + '/' + i
data.label = false
data.css = ''
if (!this.getProp('split')) {
data.address = '@{parent.address}'
data.preArgs = '#{concat(@{parent.preArgs},[' + 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.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-this.start] = this.getProp('off')
}
}
}

View file

@ -0,0 +1,110 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
class Matrix extends _matrix_base {
static defaults() {
return super.defaults({
_matrix: 'matrix',
widgetType: {type: 'string', value: 'toggle', help: 'Defines the type of the widgets in the matrix'},
matrix: {type: 'array', value: [2,2], help: 'Defines the number of columns and and rows in the matrix'},
start: {type: 'integer', value: 0, help: 'First widget\'s index'},
spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
border: {type: 'boolean', value: true, help: 'Set to `false` to disables the widgets\' borders'},
props: {type: 'object', value: {}, help: [
'Defines a set of property to override the widgets\' defaults.',
'Formulas in this field are resolved with an extra variable representing each widget\'s index: `$`'
]}
}, [], {})
}
constructor(options) {
super(options)
this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
if (this.getProp('borders') === false) this.widget.classList.add('noborders')
if (parser.widgets[this.getProp('widgetType')]) {
for (var i = this.start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + this.start; i++) {
var props = this.resolveProp('props', undefined, false, false, false, {'$':i})
var data = {
type: this.getProp('widgetType'),
id: this.getProp('id') + '/' + i,
label: i,
top: 'auto',
left: 'auto',
height: 'auto',
width: 'auto'
}
if (typeof props === 'object' && props !== null) {
Object.assign(data, props)
}
var widget = parser.parse({
data: data,
parentNode: this.widget,
parent: this
})
widget.container.classList.add('not-editable')
this.value[i-this.start] = widget.getValue()
}
} else {
this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
}
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'props':
for (let i = this.children.length - 1; i >= 0; i--) {
let data = this.resolveProp('props', undefined, false, false, false, {'$':i})
if (typeof data === 'object' && data !== null) {
Object.assign(this.children[i].props, data)
}
this.children[i].updateProps(Object.keys(data), this)
// this.children[i] might have been recreated
this.children[i].container.classList.add('not-editable')
}
return
}
}
}
Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
'props'
)
module.exports = Matrix

View file

@ -0,0 +1,99 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
module.exports = class Multifader extends _matrix_base {
static defaults() {
return super.defaults({
_matrix:'matrix',
strips: {type: 'integer', value: 2, help: [
'Number of faders in the row, each fader will inherit its parent\'s properties and the following ones (where i is the fader\'s index in the row)',
'- `id`: same as the widget\'s with /i appended to it',
'- `label`: i',
'- `address`: see split',
]},
start: {type: 'integer', value: 0, help: 'First widget\'s index'},
traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
_fader: 'fader',
range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
origin: {type: 'number', value: 'auto', help: 'See fader\'s `origin`'},
unit: {type: 'string', value: '', help: 'See fader\'s `unit`'},
alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
pips: {type: 'boolean', value: false, help: 'See fader\'s `pips`'},
dashed: {type: 'boolean', value: false, help: 'See fader\'s `dashed`'},
snap: {type: 'boolean', value: true, help: 'See fader\'s `snap`'},
meter: {type: 'boolean', value: false, help: 'See fader\'s `meter`'},
input: {type: 'boolean', value: true, help: 'See fader\'s `input`'},
compact: {type: 'boolean', value: false, help: 'See fader\'s `compact`'},
}, [], {
split: {type: 'boolean|string', value: false, help: [
'- `true`: the widget\'s index will be appended to the matrice\'s osc address',
'- `false`: it will be prepended to the widget\'s preArgs',
'- `string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
]}
})
}
constructor(options) {
super(options)
this.strips = parseInt(this.getProp('strips'))
if (this.getProp('horizontal')) {
this.widget.classList.add('horizontal')
}
if (this.getProp('compact')) {
this.widget.classList.add('compact')
}
var strData = JSON.stringify(options.props)
for (var i = this.start; i < this.strips + this.start; i++) {
var data = JSON.parse(strData)
data.top = data.left = data.height = data.width = 'auto'
data.type = 'fader'
data.id = this.getProp('id') + '/' + i
data.label = i
data.css = ''
if (!this.getProp('split')) {
data.address = '@{parent.address}'
data.preArgs = '#{concat(@{parent.preArgs},[' + i + '])}'
} else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
data.preArgs = '@{parent.preArgs}'
} else if (this.getProp('split')) {
data.address = '@{parent.address}/' + i
data.preArgs = '@{parent.preArgs}'
}
var fader = parser.parse({
data: data,
parentNode: this.widget,
parent: this
})
fader.container.classList.add('not-editable')
this.value[i-this.start] = this.getProp('range').min
}
}
}

View file

@ -0,0 +1,91 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
module.exports = class Multipush extends _matrix_base {
static defaults() {
return super.defaults({
_matrix: 'matrix',
matrix: {type: 'array', value: [2,2], help: [
'Defines the number of columns and and rows in the matrix. Each cell will contain a push button that will inherit its parent\'s properties and the following ones (where i is the push\'s index)',
'- `id`: same as the widget\'s with /i appended to it',
'- `label`: i',
'- `address`: see split'
]},
start: {type: 'integer', value: 0, help: 'First widget\'s index'},
traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
_push: 'push',
on: {type: '*', value: 1, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
off: {type: '*', value: 0, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
norelease: {type: 'boolean', value: false, help: 'Set to `true` to prevent sending any osc message when releasing the button'},
}, ['_value', 'default', 'value'], {
split: {type: 'boolean|string', value: false, help: [
'`true`: the widget\'s index will be appended to the matrice\'s osc address',
'`false`: it will be prepended to the widget\'s preArgs',
'`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
]}
})
}
constructor(options) {
super(options)
this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
var strData = JSON.stringify(options.props)
for (var i = this.start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + this.start; i++) {
var data = JSON.parse(strData)
data.top = data.left = data.height = data.width = 'auto'
data.type = 'push'
data.id = this.getProp('id') + '/' + i
data.label = i
data.css = ''
if (!this.getProp('split')) {
data.address = '@{parent.address}'
data.preArgs = '#{concat(@{parent.preArgs},[' + i + '])}'
} else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
data.preArgs = '@{parent.preArgs}'
} else if (this.getProp('split')) {
data.address = '@{parent.address}/' + i
data.preArgs = '@{parent.preArgs}'
}
var push = parser.parse({
data: data,
parentNode: this.widget,
parent: this
})
push.container.classList.add('not-editable')
this.value[i-this.start] = this.getProp('off')
}
}
}

View file

@ -0,0 +1,90 @@
var _matrix_base = require('./_matrix_base'),
parser = require('../../parser')
module.exports = class Multitoggle extends _matrix_base {
static defaults() {
return super.defaults({
_matrix:'matrix',
matrix: {type: 'array', value: [2,2], help: [
'Defines the number of columns and and rows in the matrix. Each cell will contain a toggle button that will inherit its parent\'s properties and the following ones (where i is the toggle\'s index)',
'- `id`: same as the widget\'s with /i appended to it',
'- `label`: i',
'- `address`: see split'
]},
start: {type: 'integer', value: 0, help: 'First widget\'s index'},
spacing: {type: 'integer', value: 0, help: 'Adds space between widgets'},
traversing: {type: 'boolean', value: true, help: 'Set to `false` to disable traversing gestures'},
_toggle: 'toggle',
led: {type: 'boolean', value: false, help: 'Set to `true` to display the toggle\'s state with a led'},
on: {type: '*', value: 1, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see preArgs)'
]},
off: {type: '*', value: 0, help: [
'Set to `null` to send send no argument in the osc message',
'Can be an `object` if the type needs to be specified (see `preArgs`)'
]},
}, [], {
split: {type: 'boolean|string', value: false, help: [
'`true`: the widget\'s index will be appended to the matrice\'s osc address',
'`false`: it will be prepended to the widget\'s `preArgs`',
'`string`: will be used to define the widgets\' addresses, replacing dollar signs (`$`) with their respective index (to insert the actual dollar sign, it must be escaped with a backslash (`\\$`))'
]}
})
}
constructor(options) {
super(options)
this.widget.style.setProperty('--columns', this.getProp('matrix')[0])
this.widget.style.setProperty('--rows', this.getProp('matrix')[1])
this.widget.style.setProperty('--spacing', this.getProp('spacing') + 'rem')
var strData = JSON.stringify(options.props)
for (var i = this.start; i < this.getProp('matrix')[0] * this.getProp('matrix')[1] + this.start; i++) {
var data = JSON.parse(strData)
data.top = data.left = data.height = data.width = 'auto'
data.type = 'toggle'
data.id = this.getProp('id') + '/' + i
data.label = i
data.css = ''
if (!this.getProp('split')) {
data.address = '@{parent.address}'
data.preArgs = '#{concat(@{parent.preArgs},[' + i + '])}'
} else if (typeof this.getProp('split') === 'string' && this.getProp('split')[0] === '/' && /[^\\]\$/.test(this.getProp('split'))) {
data.address = this.getProp('split').replace(/([^\\])(\$)/g,'$1' + i).replace(/\\\$/g, '$')
data.preArgs = '@{parent.preArgs}'
} else if (this.getProp('split')) {
data.address = '@{parent.address}/' + i
data.preArgs = '@{parent.preArgs}'
}
var toggle = parser.parse({
data: data,
parentNode: this.widget,
parent: this
})
toggle.container.classList.add('not-editable')
this.value[i-this.start] = this.getProp('off')
}
}
}

View file

@ -0,0 +1,37 @@
module.exports = (element, callback)=>{
var lastTapTime = 0,
lastTapX,
lastTapY
element.addEventListener('fast-click', (event)=>{
if (event.capturedByEditor) return
var tapTime = Date.now(),
tapLength = tapTime - lastTapTime,
eventData = event.detail
if (
tapLength < DOUBLE_TAP_TIME &&
Math.abs(lastTapX - eventData.pageX) < 20 &&
Math.abs(lastTapY - eventData.pageY) < 20
) {
// execute callback at next cycle to ensure draginit events are resolved first
setTimeout(callback, 0)
lastTapTime = 0
} else {
lastTapTime = tapTime
lastTapX = eventData.pageX
lastTapY = eventData.pageY
}
})
}

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 (arguments.cancelDraw) this.noDraw = true
}
sendValue() {
// disabled
}
}

View file

@ -0,0 +1,272 @@
var Pad = require('./pad'),
Xy = require('./xy'),
{clip} = require('../utils'),
touchstate = require('../mixins/touch_state')
var xyDefaults = Xy.defaults()._props()
module.exports = class MultiXy extends Pad {
static defaults() {
return super.defaults({
_mutlixy: 'multi xy',
points: {type: 'integer|array', value: 2, help: [
'Defines the number of points on the pad',
'Can be an array of strings that will be used as labels for the points (ex: `[\'A\', \'B\']`)'
]},
_xy: 'xy',
pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
snap: {type: 'boolean', value: false, help: [
'By default, the points are dragged from their initial position.',
'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
]},
spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'}
}, [], {
touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
split: {type: 'boolean|object', value: false, help: [
'Set to `true` to send separate osc messages for each point\'s x and y axis. The address will be the same as the widget\'s with `/N/x` or `/N/y` appended to it, where N is the point\'s id (or the point\'s label if points is an array)',
'Can be set as an `object` to specify a different address : `[\'/0/x\', \'/0/y\', \'/1/x\', \'/2/y\']`',
'Note: the widget will only respond to its original osc address, not to the splitted version'
]}
})
}
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=this.npoints-1;i>=0;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.precision,
logScaleX:this.getProp('logScaleX'),
logScaleY:this.getProp('logScaleY'),
pointSize: this.getProp('pointSize'),
pips: this.getProp('pips') && i == this.npoints-1,
input:false
}, parent: this})
this.pads[i].sendValue = ()=>{}
this.wrapper.appendChild(this.pads[i].widget)
}
this.value = []
this.padsCoords = []
this.touchMap = {}
touchstate(this, {element: this.wrapper, multitouch: true})
this.on('draginit',(e)=>{
var id
if (!this.touchMap[e.pointerId]) {
var ndiff, diff = -1
for (var i in this.pads) {
if (Object.values(this.touchMap).indexOf(i) != -1) continue
ndiff = Math.abs(e.offsetX - this.padsCoords[i][0]) + Math.abs(e.offsetY - (this.padsCoords[i][1] + this.height))
if (diff == -1 || ndiff < diff) {
id = i
diff = ndiff
}
}
this.touchMap[e.pointerId] = id
}
if (!id) return
e.stopPropagation = true
this.pads[id].trigger('draginit', [e])
}, {element: this.wrapper, multitouch: true})
this.on('drag',(e)=>{
var i = this.touchMap[e.pointerId]
this.pads[i].trigger('drag', [e])
}, {element: this.wrapper[0], multitouch: true})
this.on('dragend',(e)=>{
var i = this.touchMap[e.pointerId]
e.stopPropagation = true
this.pads[i].trigger('dragend', [e])
delete this.touchMap[e.pointerId]
}, {element: this.wrapper, multitouch: true})
this.on('change',(e)=>{
if (e.widget == this) return
e.stopPropagation = true
this.setValue(this.getValue(), e.options)
})
var v = []
for (let i = 0; i < this.npoints * 2; i = i + 2) {
[v[i],v[i+1]] = this.pads[i/2].getValue()
}
this.setValue(v)
}
resizeHandle() {
super.resizeHandle(...arguments)
this.updateHandlesPosition()
}
updateHandlesPosition() {
for (var i=0;i<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.pointSize + 1) * PXSCALE,
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.colors.text
this.ctx.fillText(t, x + 0.5 * PXSCALE, y + 0.5 * 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 'color':
for (var w of this.pads) {
w.onPropChanged('color')
}
return
}
}
onRemove() {
for (var i in this.pads) {
this.pads[i].onRemove()
}
super.onRemove()
}
}

View file

@ -0,0 +1,24 @@
var Canvas = require('../common/canvas')
module.exports = class Pad extends Canvas {
constructor(options) {
var html = `
<div class="pad">
<div class="wrapper">
<canvas></canvas>
</div>
</div>
`
super({...options, html: html})
this.wrapper = DOM.get(this.widget, '.wrapper')[0]
this.pointSize = parseInt(this.getProp('pointSize'))
this.widget.style.setProperty('--pointSize', this.pointSize + 'rem')
}
}

View file

@ -0,0 +1,226 @@
var Pad = require('./pad'),
Xy = require('./xy'),
Fader = require('./_fake_fader'),
{clip, hsbToRgb, rgbToHsb} = require('../utils'),
Input = require('../inputs/input')
var faderDefaults = Fader.defaults()._props(),
xyDefaults = Xy.defaults()._props()
module.exports = class Rgb extends Pad {
static defaults() {
return super.defaults({
_rgb:'rgb',
snap: {type: 'boolean', value: false, help: [
'By default, the points are dragged from their initial position.',
'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
]},
spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
range: {type: 'object', value: {min: 0, max: 255}, help: 'Defines the widget\'s output scale.'},
input: {type: 'boolean', value: true, help: 'Set to `false` to hide the built-in input widget'},
}, ['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(DOM.create('<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.margin = this.pointSize
this.hue.sendValue = ()=>{}
this.hueWrapper.appendChild(this.hue.widget)
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.value = []
this.hsb = {h:0,s:0,b:0}
this.hue.on('change',(e)=>{
e.stopPropagation = true
this.dragHandle(true)
})
this.pad.on('change',(e)=>{
e.stopPropagation = true
this.dragHandle()
})
if (this.getProp('input')) {
this.input = new Input({
props:{...Input.defaults()._props(), precision:this.getProp('precision'), unit:this.getProp('unit')},
parent:this, parentNode:this.widget
})
this.widget.appendChild(this.input.widget)
this.input.on('change', (e)=>{
e.stopPropagation = true
this.setValue(this.input.getValue(), {sync:true, send:true})
this.showValue()
})
}
this.setValue([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),
{min, max} = this.getProp('range')
if (min !== 0 || max !== 255) {
for (var k in rgb) {
rgb[k] = min + max * rgb[k] / 255
}
}
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})
}
}
}
setValue(v, options={}) {
if (!v || !v.length || v.length!=3) return
if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
for (let i in [0,1,2]) {
v[i] = clip(v[i],[this.getProp('range').min, this.getProp('range').max])
}
var rgb = {r:v[0],g:v[1],b:v[2]},
{min, max} = this.getProp('range')
if (min !== 0 || max !== 255) {
for (var k in rgb) {
rgb[k] = (rgb[k] - min ) * 255 / max
}
}
var hsb = rgbToHsb(rgb)
if (!options.dragged) {
this.pad.setValue([hsb.s, hsb.b], {sync: false, send:false, dragged:false})
}
this.hsb = hsb
this.value = v
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')
return
}
}
onRemove() {
this.hue.onRemove()
this.pad.onRemove()
if (this.input) this.input.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,299 @@
var Pad = require('./pad'),
Fader = require('./_fake_fader'),
doubletab = require('../mixins/double_tap'),
Input = require('../inputs/input'),
touchstate = require('../mixins/touch_state')
var faderDefaults = Fader.defaults()._props()
module.exports = class Xy extends Pad {
static defaults() {
return super.defaults({
_xy:'xy',
pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
snap: {type: 'boolean', value: false, help: [
'By default, the points are dragged from their initial position.',
'If set to `true`, touching anywhere on the widget\'s surface will make them snap to the touching coordinates',
]},
spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its default value when released'},
pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'},
input: {type: 'boolean', value: true, help: 'Set to false to hide the built-in input widget'},
doubleTap: {type: 'boolean|string', value: false, help: [
'Set to `true` to make the fader reset to its default value when receiving a double tap.',
'Can also be an osc address, which case the widget will just send an osc message: `/<doubleTap> <preArgs>`'
]},
}, [], {
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 Fader({props:{
...faderDefaults,
id:0,
compact:true,
pips:false,
horizontal:true,
height:'100%',
width:'100%',
default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
snap:this.getProp('snap'),
range:this.getProp('rangeX'),
origin:'auto',
precision:this.precision,
logScale:this.getProp('logScaleX'),
input:false
}, cancelDraw: true, parent: this}),
y: new Fader({props:{
...faderDefaults,
id:1,
compact:true,
pips:false,
horizontal:false,
height:'100%',
width:'100%',
default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
snap:this.getProp('snap'),
range:this.getProp('rangeY'),
origin:'auto',
precision:this.precision,
logScale:this.getProp('logScaleY'),
input:false
}, cancelDraw: true, parent: this}),
}
this.faders.x.margin = this.faders.y.margin = this.pointSize + 1
this.value = [this.faders.x.value, this.faders.y.value]
this.wrapper.appendChild(this.faders.x.widget)
this.wrapper.appendChild(this.faders.y.widget)
this.faders.x.on('change',(e)=>{
e.stopPropagation = true
})
this.faders.y.on('change',(e)=>{
e.stopPropagation = true
})
touchstate(this, {element: this.wrapper})
this.on('draginit',(e)=>{
e.stopPropagation = true
this.faders.x.trigger('draginit', [e])
this.faders.y.trigger('draginit', [e])
this.dragHandle()
}, {element: this.wrapper})
this.on('drag',(e)=>{
this.faders.x.trigger('drag', [e])
this.faders.y.trigger('drag', [e])
this.dragHandle()
}, {element: this.wrapper})
this.on('dragend', (e)=>{
e.stopPropagation = true
this.faders.x.trigger('dragend', [e])
this.faders.y.trigger('dragend', [e])
if (this.getProp('spring')) {
this.setValue([this.faders.x.springValue,this.faders.y.springValue],{sync:true,send:true})
}
}, {element: this.wrapper})
if (this.getProp('doubleTap')) {
if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
doubletab(this.widget, ()=>{
this.sendValue({v:null, address: this.getProp('doubleTap')})
})
} else {
doubletab(this.wrapper, ()=>{
this.faders.x.setValue(this.faders.x.springValue, {sync: false, send:false, dragged:true})
this.faders.y.setValue(this.faders.y.springValue, {sync: false, send:false, dragged:true})
this.setValue([this.faders.x.springValue,this.faders.y.springValue],{sync:true, send:true})
})
}
}
if (this.getProp('input')) {
this.input = new Input({
props:{...Input.defaults()._props(), precision:this.getProp('precision'), unit:this.getProp('unit')},
parent:this, parentNode:this.widget
})
this.widget.appendChild(this.input.widget)
this.input.on('change', (e)=>{
e.stopPropagation = true
this.setValue(this.input.getValue(), {sync:true, send:true})
this.showValue()
})
}
this.setValue([0,0])
}
dragHandle(){
var x = this.faders.x.value,
y = this.faders.y.value
if (x != this.value[0] || y != this.value[1]) {
this.setValue([x, y],{send:true,sync:true,dragged:true})
}
}
setValue(v, options={}) {
if (!v || !v.length || v.length!=2) return
if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
if (!options.dragged) {
this.faders.x.setValue(v[0], {sync: false, send:false, dragged:false})
this.faders.y.setValue(v[1], {sync: false, send:false, dragged:false})
}
this.value = [
this.faders.x.value,
this.faders.y.value
]
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
this.batchDraw()
this.showValue()
}
draw() {
var pointSize = this.pointSize * PXSCALE,
margin = (this.pointSize + 1) * PXSCALE,
x = this.faders.x.percentToCoord(this.faders.x.percent),
y = this.faders.y.percentToCoord(this.faders.y.percent)
this.clear()
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.custom
this.ctx.strokeStyle = this.colors.custom
if (this.getProp('pips')) {
this.ctx.globalAlpha = 0.1
this.ctx.beginPath()
this.ctx.rect(margin + 0.5, margin + 0.5, this.width - margin * 2 - 1, this.height - margin * 2 - 1)
this.ctx.stroke()
this.ctx.beginPath()
for (var pip of this.faders.x.rangeKeys.concat(this.faders.x.valueToPercent(this.faders.x.originValue))) {
if (pip == 0 || pip == 100) continue
var xpip = Math.round(2 * this.faders.x.percentToCoord(pip)) / 2
this.ctx.moveTo(xpip, margin + 0.5)
this.ctx.lineTo(xpip, this.height - margin - 0.5)
}
for (pip of this.faders.y.rangeKeys.concat(this.faders.y.valueToPercent(this.faders.y.originValue))) {
if (pip == 0 || pip == 100) continue
var ypip = Math.round(2 * this.faders.y.percentToCoord(pip)) / 2
this.ctx.moveTo(margin + 0.5, ypip)
this.ctx.lineTo(this.width - margin - 0.5, ypip)
}
this.ctx.stroke()
} else {
this.clearRect = [x - margin, y - margin, margin * 2, margin * 2]
}
this.ctx.globalAlpha = 0.7
this.ctx.beginPath()
this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
this.ctx.stroke()
this.ctx.globalAlpha = 1
this.ctx.lineWidth = 1.5 * PXSCALE
this.ctx.beginPath()
this.ctx.arc(x, y, pointSize / 1.5, Math.PI * 2, false)
this.ctx.stroke()
}
showValue() {
if (this.getProp('input')) this.input.setValue(this.value)
}
getSplit() {
return this.getProp('split')?
typeof this.getProp('split') == 'object' && this.getProp('split').length == 2 ?
this.getProp('split')
: [this.getProp('address') + '/x', this.getProp('address') + '/y']
: false
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
for (var w of [this.faders.x, this.faders.y]) {
w.onPropChanged('color')
}
if (this.input) this.input.onPropChanged('color')
return
}
}
onRemove() {
this.faders.x.onRemove()
this.faders.y.onRemove()
if (this.input) this.input.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,137 @@
//
// calcBiquad
//
// Dec 14, 2010 njr
// original @ Nigel Redmon
module.exports = function(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,209 @@
var {mapToScale} = require('../utils'),
Canvas = require('../common/canvas')
module.exports = class _plots_base extends Canvas {
constructor(options) {
var html = `
<div class="plot">
<canvas></canvas>
</div>
`
super({...options, html: html})
this.value = []
this.rangeX = this.getProp('rangeX') || {min:0,max:1}
this.rangeY = this.getProp('rangeY') || {min:0,max:1}
this.logScaleX = this.getProp('logScaleX')
this.logScaleY = this.getProp('logScaleY')
this.pips = {
x : {
min: Math.abs(this.rangeX.min)>=1000?this.rangeY.min/1000+'k':this.rangeX.min,
max: Math.abs(this.rangeX.max)>=1000?this.rangeY.max/1000+'k':this.rangeX.max
},
y : {
min: Math.abs(this.rangeY.min)>=1000?this.rangeY.min/1000+'k':this.rangeY.min,
max: Math.abs(this.rangeY.max)>=1000?this.rangeY.max/1000+'k':this.rangeY.max
}
}
this.smooth = this.getProp('smooth') === true ? 0.25 : this.getProp('smooth') === false ? 0 : parseFloat(this.getProp('smooth')) || 0
}
resizeHandle() {
this.updateData()
super.resizeHandle(...arguments)
}
draw() {
this.ctx.clearRect(0,0,this.width,this.height)
if (this.getProp('bars')) {
this.draw_bars()
} else {
var points = this.draw_line()
if (this.getProp('dots')) {
this.draw_dots(points)
}
}
if (this.getProp('pips')) this.draw_pips()
}
draw_pips() {
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.colors.text
if (this.pips.x) {
this.ctx.textBaseline = 'bottom'
this.ctx.textAlign = 'left'
this.ctx.fillText(this.pips.x.min,(this.pips.y?12:2)*PXSCALE,this.height)
this.ctx.textAlign = 'right'
this.ctx.fillText(this.pips.x.max,this.width-2*PXSCALE,this.height)
}
if (this.pips.y) {
this.ctx.save()
this.ctx.translate(0, this.height)
this.ctx.rotate(-Math.PI/2)
this.ctx.textBaseline = 'top'
this.ctx.textAlign = 'left'
this.ctx.fillText(this.pips.y.min,(this.pips.x?12:2)*PXSCALE,2*PXSCALE)
this.ctx.textAlign = 'right'
this.ctx.fillText(this.pips.y.max,this.height-2*PXSCALE,2*PXSCALE)
this.ctx.rotate(Math.PI/2)
this.ctx.restore()
}
}
draw_line() {
var points = []
for (let i in this.value) {
if (this.value[i].length) {
points.push(mapToScale(this.value[i][0],[this.rangeX.min,this.rangeX.max],[0,this.width],0,this.logScaleX,true))
points.push(mapToScale(this.value[i][1],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true))
} else {
points.push(mapToScale(i,[0,this.value.length-1],[0,this.width],0,this.logScaleX,true))
points.push(mapToScale(this.value[i],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true))
}
}
if (points.length < 4) return points
this.ctx.beginPath()
this.ctx.curve(points, this.smooth, Math.round(this.width/(points.length/2 - 1)))
this.ctx.globalAlpha = 0.7
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.strokeStyle = this.colors.custom
this.ctx.stroke()
if (this.getProp('origin') !== false) {
var origin = mapToScale(this.getProp('origin') || this.rangeY.min,[this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
this.ctx.globalAlpha = 0.1
this.ctx.fillStyle = this.colors.custom
this.ctx.lineTo(this.width,origin)
this.ctx.lineTo(0,origin)
this.ctx.closePath()
this.ctx.fill()
}
return points
}
draw_dots(points) {
this.ctx.globalAlpha = 1
this.ctx.fillStyle = this.colors.custom
this.ctx.strokeStyle = this.colors.track
this.ctx.lineWidth = 2 * PXSCALE
for (var i = 0; i < points.length; i += 2) {
this.ctx.beginPath()
this.ctx.arc(points[i], points[i + 1], 4 * PXSCALE, 0, 2*Math.PI)
this.ctx.fill()
this.ctx.stroke()
}
}
draw_bars() {
var barWidth = Math.round(this.width / this.value.length),
offset = Math.round((this.width - barWidth * this.value.length) / 2)
var origin = mapToScale(this.getProp('origin') || this.rangeY.min,[this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
this.ctx.beginPath()
for (let i in this.value) {
var y = mapToScale(this.value[i].length ? this.value[i][1] : this.value[i],[this.rangeY.min,this.rangeY.max],[this.height-2*PXSCALE,2*PXSCALE],0,this.logScaleY,true)
this.ctx.rect(offset + i * barWidth, Math.min(y, origin), barWidth - PXSCALE, Math.abs(Math.min(y - origin)))
}
this.ctx.globalAlpha = 0.4
this.ctx.fillStyle = this.colors.custom
this.ctx.fill()
}
setValue(v, options={}) {
if (typeof v == 'string') {
try {
v = JSON.parseFlex(v)
} catch(err) {}
}
if (typeof v == 'object' && v !== null) {
if (Array.isArray(v)) {
this.value = v
} else {
for (var i in v) {
if (!isNaN(i)) this.value[i] = v[i]
}
}
this.batchDraw()
if (options.sync) this.changed(options)
}
}
updateData() {
// update the coordinates to draw
}
}

View file

@ -0,0 +1,91 @@
var {clip} = require('../utils'),
_biquad_response = require('./_biquad_response'),
_plots_base = require('./_plots_base')
module.exports = class Eq extends _plots_base {
static defaults() {
return super.defaults({
_eq:'eq',
pips: {type: 'boolean', value: true, help: 'Set to false to hide the scale'},
resolution: {type: 'number', value: 128, help: 'Defines the number of points used to compute the frequency response'},
rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
origin: {type: 'number|boolean', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
}, ['target', 'precision', 'bypass'], {})
}
constructor(options) {
// backward compat
if (options.props.filters && options.props.filters.length) {
options.props.value = options.props.filters
delete options.props.filters
}
super(options)
this.rangeX = {min:20,max:22050}
this.pips.x.min = '20'
this.pips.x.max = '22k'
this.resolution = clip(this.getProp('resolution'),[64,1024])
}
setValue(v, options={}) {
if (typeof v == 'string') {
try {
v = JSON.parseFlex(v)
} catch(err) {}
}
if (Array.isArray(v)) {
var filters = v,
eqResponse = []
if (v.length === this.resolution) {
eqResponse = v
} else {
for (let i in filters) {
var filterResponse
if (!filters[i].type) filters[i].type = 'peak'
if (!filters[i].on) {
filterResponse = _biquad_response({type:'peak',freq:1,gain:0,q:1},!this.getProp('logScaleX'), this.resolution)
} else {
filterResponse = _biquad_response(filters[i],!this.getProp('logScaleX'), this.resolution)
}
for (var k in filterResponse) {
if (eqResponse[k]===undefined) {
eqResponse[k]=[0,0]
}
eqResponse[k] = [filterResponse[k][0], eqResponse[k][1]+filterResponse[k][1]]
}
}
}
if (eqResponse.length) super.setValue(eqResponse, options)
}
}
}

View file

@ -0,0 +1,71 @@
var Widget = require('../common/widget'),
locales = require('../../locales'),
localUrlRe = /(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.1[6-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.2[0-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.3[0-1]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)/
class Frame extends Widget {
static defaults() {
return super.defaults({
_frame: 'frame',
border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
}, ['color', 'target', 'precision', 'bypass'], {
label: {type: 'string|boolean', value: 'auto', help: [
'Set to `false` to hide completely',
'Insert icons using the prefix ^ followed by the icon\'s name : ^play, ^pause, etc',
'If set to `false`, all pointer-events will be disabled on the frame as long as the editor is enabled to ensure it can be selected'
]},
value: {type: 'string', value: '', help: [
'External web page URL. Only local URLs are allowed (starting with `http://127.0.0.1/`, `http://10.x.x.x/`, `http://192.168.x.x/`, etc)',
]}
})
}
constructor(options) {
super({...options, html: '<div class="frame"><iframe src=""></iframe></div>'})
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, 'iframe')[0]
this.errorText = DOM.create('<span>' + locales('iframe_unauthorized') + '<span>')
this.errorTextMounted = false
}
setValue(v, options={}) {
this.value = v
var parser = document.createElement('a')
parser.href = this.value
if (parser.hostname.match(localUrlRe)) {
this.frame.setAttribute('src', this.value)
this.widget.classList.remove('error')
if (this.errorTextMounted) {
this.widget.removeChild(this.errorText)
this.errorTextMounted = false
}
} else {
this.frame.setAttribute('src', '')
this.widget.classList.add('error')
this.widget.appendChild(this.errorText)
this.errorTextMounted = true
}
if (options.sync) this.changed(options)
}
}
module.exports = Frame

View file

@ -0,0 +1,97 @@
var Widget = require('../common/widget'),
ipc = require('../../ipc')
module.exports = class Led extends Widget {
static defaults() {
return super.defaults({
_image:'image',
size: {type: 'string', value: 'cover', help: 'CSS background-size'},
position: {type: 'string', value: 'center', help: 'CSS background-position'},
repeat: {type: 'string', value: 'no-repear', help: 'CSS background-repeat'},
border: {type: 'boolean', value: true, help: 'Set to `false` to disable the borders and background-color'},
cache: {type: 'boolean', value: true, help: [
'Set to false to disable image caching (forces file reload when updating or editing the widget).',
'When true, sending `reload` to the widget reloads its image without changing its value'
]}
}, ['color', 'target', 'precision', 'bypass'], {
value: {type: 'string', value: '', help: [
'- File `url` or `absolute path`',
'- Base64 encoded image : `data:image/...`'
]}
})
}
constructor(options) {
var html = `
<div class="image"></div>
`
super({...options, html: html})
if (!this.getProp('border')) this.container.classList.add('noborder')
this.widget.style.setProperty('background-size', this.getProp('size'))
this.widget.style.setProperty('background-position', this.getProp('position'))
this.widget.style.setProperty('background-repeat', this.getProp('repeat'))
if (this.getProp('stream') !== '') {
this.bindedOnStreamUpdate = this.onStreamUpdate.bind(this)
ipc.on('video', this.bindedOnStreamUpdate)
}
}
setValue(v, options={}) {
var s = v==null ? '' : '' + v,
cache_query = ''
if (!s.length) {
this.value = this.getProp('value')
} else if (s != 'reload') {
if (s.length > 1) this.value = s
}
if (typeof this.value === 'string' && this.value.length) {
cache_query = this.getProp('cache') || this.value.indexOf('base64') != -1 ?
'' : (this.value.indexOf('?') != -1 ? '&' : '?') + Date.now()
}
this.widget.style.setProperty('background-image', `url(${this.value}${cache_query})`)
if (options.sync) this.changed(options)
}
onStreamUpdate(event) {
var [stream, data] = event
if (stream === this.getProp('stream')) {
this.setValue('data:image/jpeg;base64,' + data)
}
}
onRemove() {
if (this.bindedOnStreamUpdate) ipc.off('video', this.bindedOnStreamUpdate)
super.onRemove()
}
}

View file

@ -0,0 +1,49 @@
var {mapToScale} = require('../utils'),
Widget = require('../common/widget')
module.exports = class Led extends Widget {
static defaults() {
return super.defaults({
_led:'led',
range: {type: 'object', value: {min:0,max:1}, help: 'Value to led intensity mapping range'},
logScale: {type: 'boolean', value: false, help: 'Set to `true` to use a logarithmic mapping scale)'},
}, ['target', 'precision', 'bypass'], {})
}
constructor(options) {
// backward compat
if (options.props.widgetId) {
options.props.value = '@{' + options.props.widgetId + '}'
delete options.props.widgetId
}
var html = `
<div class="led">
</div>
`
super({...options, html: html})
this.setValue(this.getProp('range').min)
}
setValue(v, options={}) {
if (typeof v != 'number') return
this.value = v
this.widget.style.setProperty('--opacity', mapToScale(v,[this.getProp('range').min,this.getProp('range').max],[0,1],false,this.getProp('logScale'),true))
if (options.sync) this.changed(options)
}
}

View file

@ -0,0 +1,57 @@
var Fader = require('../sliders/fader')
module.exports = class Meter extends Fader {
static defaults() {
return super.defaults({
_meter:'meter',
range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
origin: {type: 'number', value: 'auto', help: 'See fader\'s `origin`'},
unit: {type: 'string', value: 'auto', help: 'See fader\'s `unit`'},
alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
pips: {type: 'boolean', value: false, help: 'See fader\'s `pips`'},
dashed: {type: 'boolean', value: false, help: 'See fader\'s `dashed`'},
gradient: {type: 'array', value: [], help: 'When set, the meter\'s gauge will be filled with a linear color gradient : each item must be a CSS color string. Example: `[\'blue\', \'red\']`'},
}, ['target', 'precision', 'bypass'], {
css: {type: 'string', value: '', help: [
'Available CSS variables:',
'- `--color-gauge: color;`',
'- `--color-knob: color;`',
'- `--color-pips: color;`',
'- `--gauge-opacity: number;`'
]},
})
}
constructor(options) {
// backward compat
if (options.props.widgetId) {
options.props.value = '@{' + options.props.widgetId + '}'
delete options.props.widgetId
}
options.props.compact = true
options.props.input = false
super(options)
this.widget.classList.add('meter')
this.off(/drag(.*)?/)
}
sendValue() {
// disabled
}
}

View file

@ -0,0 +1,47 @@
var _plots_base = require('./_plots_base')
module.exports = class Plot extends _plots_base {
static defaults() {
return super.defaults({
_plot:'plot',
rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
logScaleX: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the x axis (log10)'},
logScaleY: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis (log10)'},
origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it.'},
dots: {type: 'boolean', value: true, help: ''},
bars: {type: 'boolean', value: false, help: 'Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing)'},
smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
}, ['target', 'precision', 'bypass'], {
value: {type: 'array|string', value: '', help: [
'- `Array` of `y` values',
'- `Array` of `[x, y]` `array` values',
'- `String` `array`',
'- `String` `object` to update specific coordinates only: `{0:1, 4:0}` will change the 1st and 5th points\' coordinates',
]}
})
}
constructor(options) {
// backward compat
if (options.props.points && options.props.points.length) {
options.props.value = options.props.points
delete options.props.points
}
super(options)
}
}

View file

@ -0,0 +1,73 @@
var Widget = require('../common/widget'),
{clip} = require('../utils')
module.exports = class Rbgled extends Widget {
static defaults() {
return super.defaults({}, ['color', 'target', 'precision', 'bypass'], {
value: {type: 'array|string', value: '', help: [
'- `Array`: `[r, g, b]` (`r`, `g` and `b` between `0` and `255`)',
'- `Array`: `[r, g, b, alpha]` (`alpha` between `0` and `255`)',
'- `String`: CSS color',
]}
})
}
constructor(options) {
// backward compat
if (options.props.widgetId) {
options.props.value = '@{' + options.props.widgetId + '}'
delete options.props.widgetId
}
var html = `
<div class="led">
</div>
`
super({...options, html: html})
this.setValue([0,0,0,0])
}
setValue(v, options={}) {
var c = ''
if (Array.isArray(v) && v.length >= 3) {
for (let i in [0,1,2]) {
v[i] = parseInt(clip(v[i],[0,255]))
}
v[3] = clip(v[3] != undefined ? v[3] : 1,[0,1])
c = `rgba(${v[0]}, ${v[1]}, ${v[2]}, ${v[3]})`
} else if (typeof v == 'string') {
c = v
} else {
return
}
this.value = v
this.widget.style.setProperty('--color-led', c)
if (options.sync) this.changed(options)
}
}

View file

@ -0,0 +1,93 @@
var Widget = require('../common/widget'),
morph = require('nanomorph')
class Svg extends Widget {
static defaults() {
return super.defaults({
_svg:'svg',
svg: {type: 'string', value: '', help: [
'Svg xml definition:',
'- will be wrapped in a `<svg></svg>` element',
'- `<path>` commands support a special percent notation (`%x` and `%y`)'
]}
}, ['color', 'target', 'precision', 'bypass'], {})
}
constructor(options) {
var html = `
<div class="svg">
<svg></svg>
</div>
`
super({...options, html: html})
this.height = undefined
this.width = undefined
this.on('resize', this.resizeHandleProxy.bind(this), {element: this.widget})
}
updateSvg(){
if (!this.width || !this.height) return
var svg = this.getProp('svg')
svg = svg.replace(/<\/svg>/gi, 'x')
svg = svg.replace(/([0-9.]+%x)/gi, m=>(parseFloat(m) * this.width / 100).toFixed(2))
svg = svg.replace(/([0-9.]+%y)/gi, m=>(parseFloat(m) * this.height / 100).toFixed(2))
morph(this.widget, DOM.create('<div class="svg"><svg>' + svg + '</svg></div>'))
}
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,59 @@
var {iconify} = require('../../ui/utils'),
Widget = require('../common/widget')
module.exports = class Text extends Widget {
static defaults() {
return super.defaults({
_text: 'text',
vertical: {type: 'boolean', value: false, help: 'Set to `true` to display the text vertically'},
wrap: {type: 'boolean', value: false, help: [
'Set to `true` to wrap long lines automatically.',
'This will not break overflowing words by default, word-breaking can be enabled by adding `word-break: break-all;` to the `css` property',
]},
align: {type: 'string', value: '', help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
}, ['target', 'precision', 'bypass'], {})
}
constructor(options) {
// backward compat
if (options.props.widgetId) {
options.props.value = '@{' + options.props.widgetId + '}'
delete options.props.widgetId
}
super({...options, html: '<div class="text"></div>'})
if (this.getProp('vertical')) this.widget.classList.add('vertical')
if (this.getProp('align') === 'left') this.widget.classList.add('left')
if (this.getProp('align') === 'right') this.widget.classList.add('right')
if (this.getProp('wrap')) this.widget.classList.add('wrap')
this.defaultValue = this.getProp('default') || ( this.getProp('label')===false ?
this.getProp('id'):
this.getProp('label')=='auto'?
this.getProp('id'):
this.getProp('label') )
this.value = this.defaultValue
this.setValue(this.value)
}
setValue(v, options={}) {
this.value = v==null ? this.defaultValue : v
this.widget.innerHTML = iconify(String(this.value).replace(/\n/g,'<br/>'))
if (options.sync) this.changed(options)
}
}

View file

@ -0,0 +1,125 @@
var {clip} = require('../utils'),
_plots_base = require('./_plots_base')
module.exports = class Visualizer extends _plots_base {
static defaults() {
return super.defaults({
_visualizer:'visualizer',
duration: {type: 'number', value: 1, help: 'Defines visualization duration in seconds'},
range: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
origin: {type: 'number', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
logScale: {type: 'boolean', value: false, help: 'Set to `true` to use logarithmic scale for the y axis'},
smooth: {type: 'boolean|number', value: false, help: 'Set to `true` to make the line smooth. Float values are also acceptable (works fine between `0` and `0.5`)'},
pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
}, ['target', 'precision', 'bypass'], {})
}
constructor(options) {
// backward compat
if (options.props.widgetId) {
options.props.value = '@{' + options.props.widgetId + '}'
delete options.props.widgetId
}
super(options)
this.fps = CANVAS_FRAMERATE
this.pips.y.min = Math.abs(this.getProp('range').min) >= 1000? this.getProp('range').min/1000+'k' : this.getProp('range').min
this.pips.y.max = Math.abs(this.getProp('range').max) >= 1000? this.getProp('range').max/1000+'k' : this.getProp('range').max
this.pips.x = false
this.rangeY = this.getProp('range') || {min:0,max:1}
this.logScaleY = this.getProp('logScale')
this.length = Math.round(clip(this.fps * this.getProp('duration'), [8, 4096]))
this.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,273 @@
var {clip} = require('../utils'),
Knob = require('./knob'),
Widget = require('../common/widget'),
doubletab = require('../mixins/double_tap')
var EncoderKnob = class extends Knob {
draginitHandle(e) {
this.percent = clip(this.percent,[0,100])
this.lastOffsetX = e.offsetX
this.lastOffsetY = e.offsetY
if (!(e.traversing || this.getProp('snap'))) return
this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true, draginit:!e.traversing})
}
mousewheelHandle(){}
}
var DisplayKnob = class extends Knob {
}
module.exports = class Encoder extends Widget {
static defaults() {
return super.defaults({
_encoder: 'encoder',
ticks: {type: 'number', value: 'auto', 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: 'auto', 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'
]},
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'},
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) {
var html = `
<div class="encoder">
<div class="wrapper">
</div>
</div>
`
super({...options, html: html})
this.wrapper = DOM.get(this.widget, '.wrapper')[0]
this.ticks = Math.abs(parseInt(this.getProp('ticks')))
this.knob = new EncoderKnob({props:{
label:false,
angle:360,
snap:true,
range:{min:0,max:this.ticks},
pips:false,
}, parent: this})
this.knob.noDraw = true
this.display = new DisplayKnob({props:{
label:false,
angle:360,
range:{min:0,max:this.ticks},
origin:this.ticks/2,
pips:false,
}, parent: this})
this.knob.widget.classList.add('drag-knob')
this.display.widget.classList.add('display-knob')
this.wrapper.appendChild(this.knob.widget)
this.wrapper.appendChild(this.display.widget)
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
this.previousValue = this.ticks/2
this.on('change',(e)=>{
if (e.widget == this) return
e.stopPropagation = true
var value = this.knob.getValue()
var direction
if (value < this.previousValue)
direction = this.getProp('back')
if (value > this.previousValue)
direction = this.getProp('forth')
if ((this.ticks * .75 < value && value < this.ticks) && (0 < this.previousValue && this.previousValue < this.ticks / 4))
direction = this.getProp('back')
if ((0 < value && value < this.ticks / 4) && (this.ticks * .75 < this.previousValue && this.previousValue < this.ticks))
direction = this.getProp('forth')
if (direction && (Math.round(value) != Math.round(this.previousValue))) this.setValue(direction, {sync:true, send:true, dragged: e.options.dragged, draginit: e.options.draginit})
this.previousValue = value
})
this.knob.on('draginit', (e)=>{
if (this.getProp('touchAddress') && this.getProp('touchAddress').length
&& e.target == this.wrapper)
this.sendValue({
address:this.getProp('touchAddress'),
v:1
})
})
this.knob.on('dragend', (e)=>{
if (this.getProp('release') !== '' && this.value !== this.getProp('release')) {
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
this.setValue(this.getProp('release'), {sync:true, send:true, dragged:false})
}
if (
this.getProp('touchAddress') && this.getProp('touchAddress').length
&& e.target == this.wrapper
) {
this.sendValue({
address:this.getProp('touchAddress'),
v:0
})
}
})
if (this.getProp('doubleTap')) {
doubletab(this.wrapper, ()=>{
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
if (this.getProp('release') !== '' && this.value !== this.getProp('release')) {
this.setValue(this.getProp('release'), {sync:true, send:true, dragged:false})
}
})
}
this.wrapper.addEventListener('mousewheel', (e)=>{
if (e.wheelDeltaX || e.wheelDelta == 0) return
var direction = e.wheelDelta / Math.abs(e.wheelDelta)
this.display.setValue(this.display.value + direction)
this.setValue(direction < 0 ? this.getProp('back') : this.getProp('forth'), {sync:true, send:true})
if (this.getProp('release') !== '' && this.value !== this.getProp('release')) {
this.knob.setValue(this.ticks/2)
this.display.setValue(this.ticks/2)
this.setValue(this.getProp('release'), {sync:true, send:true, dragged:false})
}
})
}
setValue(v,options={}) {
if (this.getProp('snap') || (!this.getProp('snap') && !options.draginit)) {
var match = true
if (v === this.getProp('back')) {
this.value = this.getProp('back')
} else if (v === this.getProp('forth')) {
this.value = this.getProp('forth')
} else if (v === this.getProp('release') && this.getProp('release') !== '') {
this.value = this.getProp('release')
} else {
match = false
}
}
if (options.sync && match) this.changed(options)
if (options.send && match && !(!this.getProp('snap') && options.draginit)) this.sendValue()
if (options.dragged || options.draginit) this.updateDisplay(options.draginit)
}
updateDisplay(init){
if (this.getProp('snap')) {
this.display.setValue(this.knob.value)
return
}
if (init) {
this.offset = this.knob.value - this.display.value
} else {
var v = this.knob.value - this.offset,
updateOffset
if (v > this.ticks) {
v = this.ticks - v
updateOffset = true
} else if (v < 0) {
v = v + this.ticks
updateOffset = true
}
this.display.setValue(v)
if (updateOffset) {
this.offset = this.knob.value - this.display.value
}
}
if (this.offset > this.ticks) this.offset = this.ticks - this.offset
if (this.offset < 0) this.offset = this.offset + this.ticks
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
for (var w of [this.knob, this.display]) {
w.onPropChanged('color')
}
return
}
}
onRemove() {
this.knob.onRemove()
this.display.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,323 @@
var {clip} = require('../utils'),
Slider = require('./slider'),
parser = require('../../parser')
module.exports = class Fader extends Slider {
static defaults() {
return super.defaults({
_fader:'fader',
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display the fader horizontally'},
alignRight: {type: 'boolean', value: false, help: 'Set to `true` to invert the pip\'s and fader\'s position'},
pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
input: {type: 'boolean', value: true, help: 'Set to `false` to hide the built-in input'},
meter: {type: 'boolean', value: false, help: [
'Set to true to display a vu-meter next in the fader',
'- the meter\'s `id` will be the same as the widget\'s with `/meter` appended to it',
'- the meter\'s `id` will be the same as the widget\'s with `/meter` appended to it'
]},
compact: {type: 'boolean', value: false, help: 'Set to `true` to display a compact alternative for the widget. Disables default mouse/touch focusing on the value display.'},
dashed: {type: 'boolean', value: false, help: 'Set to `true` to display a dashed gauge'},
snap: {type: 'boolean', value: false, help: 'By default, dragging the widget will modify it\'s value starting from its last value. Setting this to `true` will make it snap directly to the mouse/touch position'},
spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
doubleTap: {type: 'boolean', value: false, help: [
'Set to `true` to make the fader reset to its `default` value when receiving a double tap.',
'Can also be an osc address, in which case the widget will just send an osc message (`/<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', value: false, help: 'Set to `true` to use logarithmic scale for the y axis'},
unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the fader\'s gauge'},
}, [], {
touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
meterAddress: {type: 'string', value:'', help: 'OSC address for the built-in meter'},
css: {type: 'string', value: '', help: [
'Available CSS variables:',
'- `--color-gauge: color;`',
'- `--color-knob: color;`',
'- `--color-pips: color;`',
'- `--gauge-opacity: number;`'
]}
})
}
constructor(options) {
super(options)
this.widget.classList.add('fader')
this.margin = 22
if (this.getProp('horizontal')) {
this.widget.classList.add('horizontal')
this.container.classList.add('horizontal')
}
if (this.getProp('compact')) {
this.widget.classList.add('compact')
this.margin = 0
if (this.getProp('input')) {
this.widget.addEventListener('fast-right-click', (e)=>{
if (e.detail.button == 2 && !EDITING) {
// Mouse only
this.input.focus()
}
})
}
}
if (this.getProp('alignRight') && !this.getProp('horizontal')) {
this.widget.classList.add('align-right')
}
if (this.getProp('meter')) {
var data = {
type:'meter',
id: this.getProp('id') + '/meter',
label:false,
horizontal:this.getProp('horizontal'),
range:this.getProp('range'),
logScale:this.getProp('logScale'),
address:this.getProp('meterAddress') || this.getProp('address') + '/meter',
preArgs:this.getProp('preArgs'),
color:this.getProp('color'),
pips:false,
dashed:true
}
var meter = parser.parse({
data: data,
parentNode: this.wrapper,
parent: this
})
meter.container.classList.add('not-editable')
this.children.push(meter)
this.widget.classList.add('has-meter')
}
if (this.getProp('pips')) {
this.widget.classList.add('has-pips')
var pips = this.wrapper.appendChild(DOM.create('<div class="pips"></div>'))
var pipTexts = {}
for (var k in this.rangeKeys) {
pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
}
var pipsInner = ''
for (var i=0;i<=100;i++) {
if (pipTexts[i]==undefined) continue
var pos = this.getProp('horizontal')?'left':'bottom'
var piptext = `<span>${Math.abs(pipTexts[i])>=1000?pipTexts[i]/1000+'k':pipTexts[i]}</span>`
var add = `
<div class="pip val" style="${pos}:${i}%">${piptext}</div>
`
pipsInner = pipsInner + add
}
pips.innerHTML = pipsInner
}
}
draginitHandle(e) {
super.draginitHandle(...arguments)
this.percent = clip(this.percent,[0,100])
if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
this.percent = this.getProp('horizontal')?
(e.offsetX - this.margin * PXSCALE) / (this.width - (this.margin * PXSCALE * 2)) * 100:
(this.height - e.offsetY - this.margin * PXSCALE) / (this.height - (this.margin * PXSCALE * 2)) * 100
// this.percent = clip(this.percent,[0,100])
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
}
dragHandle(e, data) {
super.dragHandle(...arguments)
this.percent = this.getProp('horizontal')?
this.percent + ( e.movementX/(this.width - this.margin * PXSCALE * 2)) * 100 / e.inertia:
this.percent + (-e.movementY/(this.height - this.margin * PXSCALE * 2)) * 100 / e.inertia
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
}
percentToCoord(percent) {
if (this.getProp('horizontal')) {
return clip(percent / 100,[0,1]) * (this.width - 2 * PXSCALE * this.margin) + this.margin * PXSCALE
} else {
return (this.height - this.margin * PXSCALE) - clip(percent / 100, [0,1]) * (this.height - 2 * PXSCALE * this.margin)
}
}
resizeHandle(event) {
var ratio = CANVAS_SCALING * this.scaling
if (this.getProp('compact') && this.getProp('horizontal')) {
event.height = 1 / ratio
}
super.resizeHandle(event)
if (this.getProp('horizontal')){
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
this.ctx.rotate(-Math.PI/2)
this.ctx.translate(-this.height * ratio, 0)
if (ratio != 1) this.ctx.scale(ratio, ratio)
}
if (this.getProp('gradient')) {
var colors = this.getProp('gradient')
if (Array.isArray(colors) && colors.length > 1) {
try {
var grad = this.ctx.createLinearGradient(0, this.getProp('horizontal') ? 0 : this.height, 0, this.getProp('horizontal') ? this.width : 0)
for (var i in colors) {
grad.addColorStop(i / (colors.length - 1), colors[i])
}
this.colors.gradient = grad
} catch(err) {
this.errors.gradient = err
}
}
}
}
draw() {
var width = this.getProp('horizontal') ? this.height : this.width,
height = !this.getProp('horizontal') ? this.height : this.width
var d = Math.round(this.percentToCoord(this.percent)),
o = Math.round(this.percentToCoord(this.valueToPercent(this.originValue))),
m = Math.round(this.getProp('horizontal') ? this.height / 2 : this.width / 2)
var dashed = this.getProp('dashed')
this.clear()
if (this.getProp('compact')) {
this.ctx.globalAlpha = this.colors.gaugeOpacity || (dashed ? .3 : .2) + 0.2 * Math.abs(d-o) / (d<o?o:height-o)
this.ctx.strokeStyle = this.colors.gradient || this.colors.gauge
this.ctx.beginPath()
this.ctx.moveTo(m, o)
this.ctx.lineTo(m, d)
this.ctx.lineWidth = width + 2 * PXSCALE
if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = 1
this.ctx.beginPath()
this.ctx.fillStyle = this.colors.knob
this.ctx.rect(0, Math.min(d, height - PXSCALE), width, PXSCALE)
this.ctx.fill()
this.clearRect = [0, 0, width, height]
} else {
this.ctx.lineWidth = 6 * PXSCALE
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.colors.light
this.ctx.moveTo(m, this.margin * PXSCALE - 2 * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE + 2 * PXSCALE)
this.ctx.stroke()
this.ctx.lineWidth = 4 * PXSCALE
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.colors.bg
this.ctx.moveTo(m, this.margin * PXSCALE - 1 * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE + 1 * PXSCALE)
this.ctx.stroke()
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.beginPath()
this.ctx.strokeStyle = this.colors.track
this.ctx.moveTo(m, this.margin * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.globalAlpha = 0.7
this.ctx.strokeStyle = this.colors.gauge
this.ctx.moveTo(m, o)
this.ctx.lineTo(m, d)
if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = 1
this.ctx.beginPath()
this.ctx.rect(m - 9 * PXSCALE, d - 15 * PXSCALE, 18 * PXSCALE, 30 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.bg
this.ctx.fill()
this.ctx.beginPath()
this.ctx.rect(m - 8 * PXSCALE, d - 14 * PXSCALE, 16 * PXSCALE, 28 * PXSCALE)
this.ctx.fillStyle = this.colors.raised
this.ctx.fill()
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
this.ctx.rect(m - 7.5 * PXSCALE, d - 13.5 * PXSCALE, 15 * PXSCALE, 27 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.strokeStyle = this.colors.light
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.rect(m - 8 * PXSCALE, d - 14 * PXSCALE, 16 * PXSCALE, PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.light
this.ctx.fill()
this.ctx.beginPath()
this.ctx.rect(m - 4 * PXSCALE, d, 8 * PXSCALE, PXSCALE)
this.ctx.fillStyle = this.colors.knob
this.ctx.fill()
this.clearRect = [width / 2 - 11 * PXSCALE, 0, 22 * PXSCALE, height]
}
}
}

View file

@ -0,0 +1,252 @@
var {clip} = require('../utils'),
Slider = require('./slider')
module.exports = class Knob extends Slider {
static defaults() {
return super.defaults({
_knob:'knob',
pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
input: {type: 'boolean', value: true, help: 'Set to `false` to hide the built-in input'},
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'},
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 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', value: false, help: 'Set to `true` to use logarithmic scale for the y axis'},
unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the knob\'s gauge'},
}, [], {
touchAddress: {type: 'string', value:'', help: 'OSC address for touched state messages: `/touchAddress [preArgs] 0/1`'},
css: {type: 'string', value: '', help: [
'Available CSS variables:',
'- `--color-gauge: color;`',
'- `--color-knob: color;`',
'- `--color-pips: color;`'
]}
})
}
constructor(options) {
super(options)
this.widget.classList.add('knob')
this.widget.classList.add('compact')
this.lastOffsetX = 0
this.lastOffsetY = 0
this.minDimension = 0
this.maxAngle = this.getProp('angle')
// calculate lost height factor
var a = (1 - Math.sin((Math.max(this.maxAngle,247.5) - 180) / 2 * Math.PI / 180)) / 3
this.lostHeightFactor = a / 4
}
draginitHandle(e) {
this.percent = clip(this.percent,[0,100])
this.lastOffsetX = e.offsetX
this.lastOffsetY = e.offsetY
if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
}
dragHandle(e) {
if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) {
this.percent = -100 * (e.movementY / e.inertia) / this.height + this.percent
} else {
this.lastOffsetX = this.lastOffsetX + e.movementX / e.inertia
this.lastOffsetY = this.lastOffsetY + e.movementY / e.inertia
this.percent = this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY))
}
this.percent = this.percent,[0,100]
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
}
coordsToAngle(x,y) {
var xToCenter = x - this.width /2,
yToCenter = y - this.height / 2,
angle = Math.atan2(-yToCenter, -xToCenter) * 180 / Math.PI + 90
return angle<0?360+angle:angle
}
angleToPercent(angle) {
return clip(angle - (360 - this.maxAngle) / 2, [0, this.maxAngle]) / this.maxAngle * 100
}
percentToAngle(percent) {
percent = clip(percent, [0, 100])
return 2 * Math.PI * percent / 100 * (this.maxAngle / 360) // angle relative to maxAngle
+ Math.PI / 2 // quarter circle offset
+ Math.PI * (1 - this.maxAngle / 360) // centering offset depending on maxAngle
}
resizeHandle() {
super.resizeHandle(...arguments)
this.minDimension = Math.min(this.width, this.height)
this.wrapper.style.top = (this.minDimension) * this.lostHeightFactor - (this.getProp('label') === false ? 0 : this.gaugeWidth / 4) + 'px'
}
draw() {
var o = this.percentToAngle(this.valueToPercent(this.originValue)),
d = this.percentToAngle(this.percent),
min = this.percentToAngle(0),
max = this.percentToAngle(100),
dashed = this.getProp('dashed'),
pips = this.getProp('pips'),
gaugeWidth = Math.max(7 * PXSCALE, this.minDimension / 20),
gaugeRadius = this.minDimension / 2 - gaugeWidth / 2 - 2 * PXSCALE,
knobRadius = gaugeRadius - gaugeWidth,
rad = PXSCALE / gaugeRadius / 2
this.ctx.clearRect(0,0,this.width,this.height)
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.colors.light
this.ctx.lineWidth = gaugeWidth
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min - 4 * rad - (pips ? 3 * rad : 0), max + 4 * rad + (pips ? 3 * rad : 0))
this.ctx.stroke()
this.ctx.strokeStyle = this.colors.bg
this.ctx.lineWidth = gaugeWidth - 2 * PXSCALE
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min - 2 * rad, max + 2 * rad)
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([1.5 * PXSCALE, 1.5 * PXSCALE])
this.ctx.strokeStyle = this.colors.track
this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
this.ctx.stroke()
this.ctx.globalAlpha = pips ? 0.5 : 0.7
this.ctx.strokeStyle = this.colors.gauge
this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, o, d, o > d)
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([])
if (pips) {
this.ctx.globalAlpha = 1
this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
for (var pip of this.rangeKeys.concat(this.valueToPercent(this.originValue))) {
let a = this.percentToAngle(pip)
this.ctx.lineWidth = gaugeWidth - 2 * PXSCALE
this.ctx.strokeStyle = this.colors.bg
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, a - 5 * rad, a + 5 * rad)
this.ctx.stroke()
this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
this.ctx.strokeStyle = this.colors.pips
this.ctx.beginPath()
this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, a - 2 * rad, a + 2 * rad)
this.ctx.stroke()
}
}
// knob
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.raised
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.arc(this.width / 2, this.height / 2, knobRadius, 0, Math.PI * 2)
this.ctx.fill()
this.ctx.strokeStyle = this.colors.bg
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.arc(this.width / 2, this.height / 2, knobRadius - PXSCALE * 1.5, 0, Math.PI * 2)
this.ctx.strokeStyle = this.colors.light
this.ctx.stroke()
var g = this.ctx.createLinearGradient(this.width / 2, this.height / 2 - knobRadius / 2,this.width / 2, this.height / 2 + knobRadius / 2)
g.addColorStop(0.5, 'transparent')
g.addColorStop(0, this.colors.light || 'transparent')
this.ctx.strokeStyle = g
this.ctx.stroke()
// cursor
this.ctx.globalAlpha = 1
let r1 = knobRadius - PXSCALE,
r2 = knobRadius / 4,
a = 2 * Math.PI - d
this.ctx.beginPath()
this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
this.ctx.lineWidth = gaugeWidth - 4.5 * PXSCALE
this.ctx.strokeStyle = this.colors.knob
this.ctx.stroke()
}
}

View file

@ -0,0 +1,453 @@
var {clip} = require('../utils'),
Widget = require('../common/widget'),
Fader = require('./fader'),
Input = require('../inputs/input'),
touchstate = require('../mixins/touch_state')
var faderDefaults = Fader.defaults()._props()
var RangeFader = class RangeFader extends Fader {
constructor(options) {
super(options)
this.cancelDraw = options.cancelDraw
}
sendValue() {}
draginitHandle() {
this.percent = clip(this.percent,[
this.valueToPercent(this.rangeValsMin),
this.valueToPercent(this.rangeValsMax)
])
super.draginitHandle(...arguments)
}
draw() {
if (this.cancelDraw || !this.parent.faders) return
var width = this.getProp('horizontal') ? this.height : this.width,
height = !this.getProp('horizontal') ? this.height : this.width
var d = Math.round(this.percentToCoord(this.valueToPercent(this.parent.faders[this.getProp('horizontal')?0:1].value))),
d2 = Math.round(this.percentToCoord(this.valueToPercent(this.parent.faders[this.getProp('horizontal')?1:0].value))),
m = Math.round(this.getProp('horizontal') ? this.height / 2 : this.width / 2)
var dashed = this.getProp('dashed')
this.clear()
if (this.getProp('compact')) {
this.ctx.globalAlpha = this.colors.gaugeOpacity || (dashed ? .3 : .2) + 0.2 * Math.abs(d-d2) / height
this.ctx.strokeStyle = this.colors.gauge
this.ctx.beginPath()
this.ctx.moveTo(m, d2)
this.ctx.lineTo(m, d)
this.ctx.lineWidth = width + 2 * PXSCALE
if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = 1
this.ctx.beginPath()
this.ctx.fillStyle = this.colors.knob
this.ctx.rect(0, Math.min(d, height - PXSCALE), width, PXSCALE)
this.ctx.rect(0, Math.min(d2, height - PXSCALE), width, PXSCALE)
this.ctx.fill()
this.clearRect = [0, 0, width, height]
} else {
this.ctx.lineWidth = 6 * PXSCALE
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.colors.light
this.ctx.moveTo(m, this.margin * PXSCALE - 2 * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE + 2 * PXSCALE)
this.ctx.stroke()
this.ctx.lineWidth = 4 * PXSCALE
this.ctx.beginPath()
this.ctx.globalAlpha = 1
this.ctx.strokeStyle = this.colors.bg
this.ctx.moveTo(m, this.margin * PXSCALE - 1 * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE + 1 * PXSCALE)
this.ctx.stroke()
this.ctx.lineWidth = 2 * PXSCALE
this.ctx.beginPath()
this.ctx.strokeStyle = this.colors.track
this.ctx.moveTo(m, this.margin * PXSCALE)
this.ctx.lineTo(m, height - this.margin * PXSCALE)
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.globalAlpha = 0.7
this.ctx.strokeStyle = this.colors.gauge
this.ctx.moveTo(m, d2)
this.ctx.lineTo(m, d)
if (dashed) this.ctx.setLineDash([PXSCALE, PXSCALE])
this.ctx.stroke()
if (dashed) this.ctx.setLineDash([])
this.ctx.globalAlpha = 1
// high knob bg
this.ctx.beginPath()
this.ctx.rect(m - 9 * PXSCALE, d - 14 * PXSCALE, 18 * PXSCALE, 16 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.bg
this.ctx.fill()
// low knob bg
this.ctx.beginPath()
this.ctx.rect(m - 9 * PXSCALE, d2 - PXSCALE, 18 * PXSCALE, 16 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.bg
this.ctx.fill()
// high knob
this.ctx.beginPath()
this.ctx.rect(m - 8 * PXSCALE, d - 13 * PXSCALE, 16 * PXSCALE, 14 * PXSCALE)
this.ctx.fillStyle = this.colors.raised
this.ctx.fill()
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
this.ctx.rect(m - 7.5 * PXSCALE, d - 12.5 * PXSCALE, 15 * PXSCALE, 13.5 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.strokeStyle = this.colors.light
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.rect(m - 8 * PXSCALE, d - 13 * PXSCALE, 16 * PXSCALE, PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.fillStyle = this.colors.light
this.ctx.fill()
this.ctx.beginPath()
this.ctx.rect(m - 4 * PXSCALE, d, 8 * PXSCALE, PXSCALE)
this.ctx.fillStyle = this.colors.knob
this.ctx.fill()
// low knob
this.ctx.beginPath()
this.ctx.rect(m - 8 * PXSCALE, d2, 16 * PXSCALE, 14 * PXSCALE)
this.ctx.fillStyle = this.colors.raised
this.ctx.fill()
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
this.ctx.rect(m - 7.5 * PXSCALE, d2, 15 * PXSCALE, 13.5 * PXSCALE)
this.ctx.lineWidth = PXSCALE
this.ctx.strokeStyle = this.colors.light
this.ctx.stroke()
this.ctx.beginPath()
this.ctx.rect(m - 4 * PXSCALE, d2, 8 * PXSCALE, PXSCALE)
this.ctx.fillStyle = this.colors.knob
this.ctx.fill()
this.clearRect = [width / 2 - 11 * PXSCALE, 0, 22 * PXSCALE, height]
}
}
}
module.exports = class Range extends Widget {
static defaults() {
return super.defaults({
_range:'range',
range: {type: 'object', value: {min:0,max:1}, help: 'See fader\'s `range`'},
horizontal: {type: 'boolean', value: false, help: 'See fader\'s `horizontal`'},
alignRight: {type: 'boolean', value: false, help: 'See fader\'s `alignRight`'},
input: {type: 'boolean', value: true, help: 'See fader\'s `input`'},
compact: {type: 'boolean', value: false, help: 'See fader\'s `compact`'},
pips: {type: 'boolean', value: true, help: 'See fader\'s `pips`'},
snap: {type: 'boolean', value: false, help: 'See fader\'s `snap`'},
spring: {type: 'boolean', value: false, help: 'See fader\'s `spring`'},
logScale: {type: 'boolean', value: false, help: 'See fader\'s `logScale`'},
}, [], {
touchAddress: {type: 'string', value: '', help: 'See fader\'s `touchAddress`'},
split: {type: 'boolean|object', value: false, help: [
'Set to `true` to send separate osc messages for `low` and `high` handles. The `address` will be the same as the widget\'s with `/low` or `/high` appended to it',
'Can be set as an object to specify a different `address` : `[\'/osc_address_low\', \'/osc_address_high\']`',
'Note: the widget will only respond to its original osc address, not to the splitted version'
]},
css: {type: 'string', value: '', help: [
'Available CSS variables:',
'- `--color-gauge: color;`',
'- `--color-knob: color;`',
'- `--color-pips: color;`',
'- `--gauge-opacity: number;`'
]}
})
}
constructor(options) {
var html = `
<div class="range">
<div class="wrapper"></div>
</div>
`
super({...options, html: html})
this.wrapper = DOM.get(this.widget, '.wrapper')[0]
this.faders = [
new RangeFader({props:{
...faderDefaults,
compact:this.getProp('compact'),
pips:false,
alignRight:false,
horizontal:this.getProp('horizontal'),
height:'100%',
width:'100%',
default:this.getProp('default').length === 2 ? this.getProp('default')[0] : this.getProp('range').min,
snap:this.getProp('snap'),
spring:this.getProp('spring'),
range:this.getProp('range'),
origin:'auto',
precision:this.precision,
logScale:this.getProp('logScale'),
input:false
}, cancelDraw: true, parent: this}),
new RangeFader({props:{
...faderDefaults,
compact:this.getProp('compact'),
pips:this.getProp('pips'),
alignRight:this.getProp('alignRight'),
horizontal:this.getProp('horizontal'),
height:'100%',
width:'100%',
default:this.getProp('default').length === 2 ? this.getProp('default')[1] : this.getProp('range').max,
snap:this.getProp('snap'),
spring:this.getProp('spring'),
range:this.getProp('range'),
origin:'auto',
precision:this.precision,
logScale:this.getProp('logScale'),
input:false
}, cancelDraw: false, parent: this})
]
this.wrapper.appendChild(this.faders[0].widget)
this.wrapper.appendChild(this.faders[1].widget)
this.on('change',(e)=>{
if (e.widget == this) return
e.stopPropagation = true
var v = [
this.faders[0].getValue(),
this.faders[1].getValue()
]
this.setValue(v, e.options)
})
this.touchMap = {}
touchstate(this, {element: this.wrapper, multitouch: true})
this.on('draginit',(e)=>{
var id
if (!this.touchMap[e.pointerId]) {
var ndiff, diff = -1
for (var i in this.faders) {
if (Object.values(this.touchMap).indexOf(i) != -1) continue
var coord = this.faders[i].percentToCoord(this.faders[i].valueToPercent(this.faders[i].value)) - (this.getProp('horizontal') ? -1 : 1) * (i == 0 ? -20 : 20)
ndiff = this.getProp('horizontal')?
Math.abs(e.offsetX - coord) :
Math.abs(e.offsetY - coord)
if (diff == -1 || ndiff < diff) {
id = i
diff = ndiff
}
}
this.touchMap[e.pointerId] = id
} else if (e.traversing) {
id = this.touchMap[e.pointerId]
}
if (!id) return
e.stopPropagation = true
this.faders[id].trigger('draginit', [e])
}, {element: this.wrapper, multitouch: true})
this.on('drag',(e)=>{
var i = this.touchMap[e.pointerId]
if (e.shiftKey) {
this.faders[0].trigger('drag', [e])
this.faders[1].trigger('drag', [e])
} else {
this.faders[i].trigger('drag', [e])
}
}, {element: this.wrapper, multitouch: true})
this.on('dragend',(e)=>{
var i = this.touchMap[e.pointerId]
e.stopPropagation = true
this.faders[i].trigger('dragend', [e])
delete this.touchMap[e.pointerId]
}, {element: this.wrapper, multitouch: true})
if (this.getProp('input')) {
this.input = new Input({
props:{...Input.defaults()._props(),
precision:this.getProp('precision'),
unit:this.getProp('unit'),
vertical: this.getProp('compact') && !this.getProp('horizontal')
},
parent:this, parentNode:this.widget,
})
this.widget.appendChild(this.input.widget)
this.input.on('change', (e)=>{
e.stopPropagation = true
this.setValue(this.input.getValue(), {sync:true, send:true})
this.showValue()
})
}
if (this.getProp('horizontal')) {
this.widget.classList.add('horizontal')
this.container.classList.add('horizontal')
}
if (this.getProp('alignRight') && !this.getProp('horizontal')) {
this.widget.classList.add('align-right')
}
if (this.getProp('compact')) {
this.widget.classList.add('compact')
}
if (this.getProp('pips')) {
this.widget.classList.add('has-pips')
}
this.setValue([
this.faders[0].rangeValsMin,
this.faders[1].rangeValsMax
])
}
setValue(v, options={}) {
if (!v || !v.length || v.length!=2) return
this.faders[0].rangeValsMax = v[1]
this.faders[1].rangeValsMin = v[0]
if (!options.dragged) {
this.faders[0].setValue(v[0])
this.faders[1].setValue(v[1])
}
this.value = [
this.faders[0].getValue(),
this.faders[1].getValue()
]
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
this.faders[1].batchDraw()
this.showValue()
}
showValue() {
if (this.getProp('input')) this.input.setValue(this.value)
}
getSplit() {
return this.getProp('split')?
typeof this.getProp('split') == 'object' && this.getProp('split').length == 2 ?
this.getProp('split')
: [this.getProp('address') + '/low', this.getProp('address') + '/high']
: false
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
for (var w of this.faders) {
w.onPropChanged('color')
}
return
}
}
onRemove() {
this.faders[0].onRemove()
this.faders[1].onRemove()
if (this.input) this.input.onRemove()
super.onRemove()
}
}

View file

@ -0,0 +1,258 @@
var {clip, mapToScale} = require('../utils'),
Canvas = require('../common/canvas'),
touchstate = require('../mixins/touch_state'),
doubletab = require('../mixins/double_tap'),
Input = require('../inputs/input')
class Slider extends Canvas {
constructor(options) {
var html = `
<div class="slider">
<div class="wrapper">
<canvas></canvas>
</div>
</div>
`
super({...options, html: html})
this.wrapper = DOM.get(this.widget, '.wrapper')[0]
this.value = undefined
this.percent = 0
this.unit = this.getProp('unit') ? ' ' + this.getProp('unit') : ''
this.rangeKeys = []
this.rangeVals = []
this.rangeLabels = []
for (var k in this.getProp('range')) {
var key = k=='min'?0:k=='max'?100:parseInt(k),
val = typeof this.getProp('range')[k] == 'object'?
this.getProp('range')[k][Object.keys(this.getProp('range')[k])[0]]:
this.getProp('range')[k],
label = typeof this.getProp('range')[k] == 'object'?
Object.keys(this.getProp('range')[k])[0]:
val
this.rangeKeys.push(key)
this.rangeVals.push(val)
this.rangeLabels.push(label)
}
this.rangeValsMax = Math.max(...this.rangeVals),
this.rangeValsMin = Math.min(...this.rangeVals)
this.originValue = this.getProp('origin')=='auto'?
this.rangeValsMin:
clip(this.getProp('origin'), [this.rangeValsMin,this.rangeValsMax])
this.springValue = this.getProp('default') !== '' ? this.getProp('default') : this.originValue
if (this.getProp('doubleTap')) {
if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
doubletab(this.widget, ()=>{
this.sendValue({v:null, address: this.getProp('doubleTap')})
})
} else {
doubletab(this.widget, ()=>{
this.setValue(this.springValue,{sync:true, send:true, fromLocal:true})
})
}
}
this.wrapper.addEventListener('mousewheel',this.mousewheelHandleProxy.bind(this))
this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.wrapper})
this.on('drag', this.dragHandleProxy.bind(this), {element:this.wrapper})
this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.wrapper})
touchstate(this, {element: this.wrapper})
if (this.getProp('input')) {
this.input = new Input({
props:{
...Input.defaults()._props(),
precision:this.getProp('precision'),
unit:this.getProp('unit'),
vertical: this.getProp('type') == 'fader' && this.getProp('compact') && !this.getProp('horizontal')
},
parent:this, parentNode:this.widget
})
this.widget.appendChild(this.input.widget)
this.input.on('change', (e)=>{
e.stopPropagation = true
this.setValue(this.input.getValue(), {sync:true, send:true})
this.showValue()
})
}
this.setValue(this.springValue)
}
mousewheelHandleProxy() {
this.mousewheelHandle(...arguments)
}
draginitHandleProxy() {
this.draginitHandle(...arguments)
}
dragHandleProxy() {
this.dragHandle(...arguments)
}
dragendHandleProxy() {
this.dragendHandle(...arguments)
}
mousewheelHandle(e) {
if (e.wheelDeltaX) return
e.preventDefault()
e.stopPropagation()
var direction = e.wheelDelta / Math.abs(e.wheelDelta),
increment = e.ctrlKey?0.25:1
this.percent = clip(this.percent + Math.max(increment,10/Math.pow(10,this.precision + 1)) * direction, [0,100])
this.setValue(this.percentToValue(this.percent), {sync:true,send:true,dragged:true})
}
draginitHandle(e, data, traversing) {
}
dragHandle(e, data, traversing) {
}
dragendHandle(e, data, traversing) {
if (this.getProp('spring')) {
this.setValue(this.springValue,{sync:true,send:true,fromLocal:true})
}
}
cacheCanvasStyle(style) {
style = style || window.getComputedStyle(this.canvas)
super.cacheCanvasStyle(style)
this.colors.gauge = style.getPropertyValue('--color-gauge') || this.colors.custom
this.colors.knob = style.getPropertyValue('--color-knob') || this.colors.custom
this.colors.pips = style.getPropertyValue('--color-pips') || this.colors.custom
this.colors.gaugeOpacity = style.getPropertyValue('--gauge-opacity')
}
percentToValue(percent) {
var h = clip(percent,[0,100])
for (var i=0;i<this.rangeKeys.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 (!options.dragged) this.percent = this.valueToPercent(this.value)
if (!this.noDraw) this.batchDraw()
this.showValue()
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
showValue() {
if (this.getProp('input')) this.input.setValue(this.value)
}
onPropChanged(propName, options, oldPropValue) {
if (super.onPropChanged(...arguments)) return true
switch (propName) {
case 'color':
if (this.input) this.input.onPropChanged('color')
return
}
}
onRemove() {
if (this.input) this.input.onRemove()
super.onRemove()
}
}
Slider.dynamicProps = Slider.prototype.constructor.dynamicProps.concat(
'on',
'off'
)
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,152 @@
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 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,87 @@
var _switchers_base = require('./_switchers_base'),
Switch = require('../buttons/switch')
var switchDefaults = Switch.defaults()._props()
module.exports = class Switcher extends _switchers_base {
static defaults() {
return super.defaults({
_switcher: 'switcher',
linkedWidgets: {type: 'string|array', value: '', help: [
'- `String`: a widget\'s `id` whose state changes will be stored',
'- `Array`: a list of widget `id` string'
]},
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display values horizontally'},
values: {type: 'array|object', value: {'Value 1':1,'Value 2':2}, help: [
'Each item represents a bank that stores the values from the widgets listed in `linkedWidgets`',
'- `Array` of possible values to switch between : `[1,2,3]`',
'- `Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
]}
})
}
constructor(options) {
super({...options, html: '<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()
}
}

View file

@ -0,0 +1,108 @@
module.exports = {
clip: function(value,range) {
value = parseFloat(value)
if (isNaN(value)) value = range[0]
return Math.max(Math.min(range[0],range[1]),Math.min(value,Math.max(range[0],range[1])))
},
// map a value from a scale to another input and output must be range arrays
mapToScale: function(value,rangeIn,rangeOut,precision,log,revertlog) {
value = module.exports.clip(value,[rangeIn[0],rangeIn[1]])
value = log ?
revertlog ?
(Math.pow(10,((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])))/9-1/9) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
:Math.log10(((value-rangeIn[0])/(rangeIn[1]-rangeIn[0]))*9+1) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
:((value-rangeIn[0])/(rangeIn[1]-rangeIn[0])) * (rangeOut[1]-rangeOut[0]) + rangeOut[0]
value = Math.max(Math.min(rangeOut[0],rangeOut[1]),Math.min(value,Math.max(rangeOut[0],rangeOut[1])))
if (precision !== false) value = parseFloat(value.toFixed(precision))
return value
},
hsbToRgb: function(hsb) {
var rgb = {}
var h = hsb.h
var s = hsb.s*255/100
var v = hsb.b*255/100
if(s == 0) {
rgb.r = rgb.g = rgb.b = v
} else {
var t1 = v
var t2 = (255-s)*v/255
var t3 = (t1-t2)*(h%60)/60
if(h==360) h = 0
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return rgb
},
rgbToHsb: function(rgb) {
var hsb = {h: 0, s: 0, b: 0}
var min = Math.min(rgb.r, rgb.g, rgb.b)
var max = Math.max(rgb.r, rgb.g, rgb.b)
var delta = max - min
hsb.b = max
hsb.s = max != 0 ? 255 * delta / max : 0
if (hsb.s != 0) {
if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
else hsb.h = 4 + (rgb.r - rgb.g) / delta
} else hsb.h = 0
hsb.h *= 60
if (hsb.h < 0) hsb.h += 360
hsb.s *= 100/255
hsb.b *= 100/255
return hsb
},
math: (()=>{
var math = require('mathjs/dist/math.min.js').create({
matrix: 'Array'
})
math.import({
unpack: function(a) { return Array.isArray(a) ? a.toString() : a },
pad: function(x, padding) {
var str = String(x),
[int, dec] = str.split('.')
while (int.length < padding) {
int = '0' + int
}
return dec ? int + '.' + dec : int
},
length: function(x) { return x.length },
values: function(x) { return Object.values(x) },
keys: function(x) { return Object.keys(x) },
extend: function(x, y) { return Object.assign(x, y) },
timestamp: function() { return Date.now() },
// basic relationnal to keep alphabetical string comparison (v4 change)
equal: function(a, b) { return a == b },
unequal: function(a, b) { return a != b },
smaller: function(a, b) { return a < b },
larger: function(a, b) { return a > b },
smallerEq: function(a, b) { return a <= b },
largerEq: function(a, b) { return a >= b }
}, {override:true})
// set math's parser array index base to zero
math.expression.mathWithTransform = Object.assign({}, math)
return math
})()
}