Merge branch 'master' into v1

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

View file

@ -0,0 +1,131 @@
var html = require('nanohtml'),
raw = require('nanohtml/raw')
class ContextMenu {
constructor(){
this.menu = null
this.root = DOM.get('osc-workspace')[0]
this.clickHandler = (e)=>{
if (this.menu && !this.menu.contains(e.target)) this.close()
}
}
open(e, actions, parent) {
var menu = html`<div class="context-menu"></div>`
for (let action of actions) {
if (Array.isArray(action.action)) {
let item = html`<div class="item has-sub" tabIndex="1">${raw(action.label)}</div>`
menu.appendChild(item)
this.open(e, action.action, item)
} else {
let item = html`<div class="item">${raw(action.label)}</div>`
menu.appendChild(item)
if (action.click) {
item.addEventListener('click', (e)=>{
e.preventDefault()
action.action()
this.close()
})
} else {
item.addEventListener('fast-click', (e)=>{
e.detail.preventOriginalEvent = true
action.action()
this.close()
})
}
}
}
if (parent) parent.appendChild(menu)
if (!parent) {
this.menu = menu
this.root.appendChild(menu)
DOM.each(menu, '.item', (item)=>{
item.addEventListener('mouseenter', ()=>{
DOM.each(item.parentNode, '.focus', (focused)=>{
focused.classList.remove('focus')
})
item.classList.add('focus')
})
item.addEventListener('mouseleave', ()=>{
if (!item.classList.contains('has-sub')) item.classList.remove('focus')
})
})
menu.style.top = e.pageY + 'px'
menu.style.left = e.pageX + 'px'
this.correctPosition(menu)
DOM.each(menu, '.context-menu', (m)=>{
this.correctPosition(m, m.parentNode)
})
}
document.addEventListener('fast-click', this.clickHandler, true)
document.addEventListener('fast-right-click', this.clickHandler, true)
}
close() {
if (this.menu) {
this.menu.parentNode.removeChild(this.menu)
this.menu = null
}
document.removeEventListener('fast-click', this.clickHandler, true)
document.removeEventListener('fast-right-click', this.clickHandler, true)
}
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 = '1rem'
}
if (height + position.top > totalHeight) {
menu.style.top = 'auto'
menu.style.bottom = '0rem'
}
}
}
module.exports = new ContextMenu()

View file

@ -0,0 +1,41 @@
var screenfull = require('screenfull'),
{Popup} = require('./utils'),
locales = require('../locales')
var fullscreen
if (screenfull.isEnabled) {
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

16
src/client/ui/init.js Normal file
View file

@ -0,0 +1,16 @@
require('./zoom')
require('./lobby').create()
// require('./sidepanel')
require('../events/click')
require('./ios')
require('./notifications')
require('./ui-workspace')
// require('./ui-sidepanel')
var UiModal = require('./ui-modal')
module.exports = {
uiModal: new UiModal({selector: 'osc-modal-container'})
}

25
src/client/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

51
src/client/ui/lobby.js Normal file
View file

@ -0,0 +1,51 @@
var html = require('nanohtml')
class Lobby {
constructor() {
this.state = 0
}
create() {
this.html = html`
<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,119 @@
var html = require('nanohtml'),
morph = require('nanomorph')
var DEFAULT_DURATION = 3500
class Toast {
constructor(data) {
this.id = data.id || Date.now()
this.update(data)
}
update(data) {
this.expires = Date.now() + (data.duration || DEFAULT_DURATION)
var toast = html`
<div class="toast ${data.class || ''}">
<i class="fa fa-fw fa-${data.icon || (data.class === 'error' ? 'exclamation' : 'bell')}"></i>
<div class="content">
${data.message}
</div>
</div>
`
if (this.html) {
this.html = morph(this.html, toast)
} else {
this.html = toast
}
}
appendTo(el) {
el.appendChild(this.html)
this.html.style.height = this.html.offsetHeight + 'px'
}
removeFrom(el) {
this.html.classList.add('remove')
setTimeout(()=>{
el.removeChild(this.html)
}, 200)
}
}
class Notifications {
constructor() {
this.container = DOM.get('#notifications')[0]
this.toasts = []
this.loop = null
}
add(data) {
if (data.id) {
var match = this.toasts.filter(x => x.id === data.id)
if (match.length) {
return match[0].update(data)
}
}
var toast = new Toast(data)
toast.appendTo(this.container)
this.toasts.push(toast)
this.startLoop()
}
remove(toast) {
toast.removeFrom(this.container)
this.toasts.splice(this.toasts.indexOf(toast), 1)
if (this.toasts.length === 0) this.stopLoop()
}
startLoop() {
if (this.loop) return
this.loop = setInterval(()=>{
for (var i = this.toasts.length - 1; i > -1; i--) {
if (Date.now() > this.toasts[i].expires) {
this.remove(this.toasts[i])
}
}
},100)
}
stopLoop() {
if (!this.loop) return
clearInterval(this.loop)
this.loop = null
}
}
module.exports = new Notifications()

View file

@ -0,0 +1,19 @@
var chroma = require('chroma-js')
module.exports = (container)=>{
setTimeout(()=>{
var computedStyle = window.getComputedStyle(container),
color = computedStyle.getPropertyValue('--color-fill').trim(),
alpha = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar')),
alphaOn = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar-on'))
if (color) {
container.style.setProperty('--color-scrollbar', chroma(color).alpha(alpha).css())
container.style.setProperty('--color-scrollbar-on', chroma(color).alpha(alphaOn).css())
}
})
}

388
src/client/ui/sidepanel.js Normal file
View file

@ -0,0 +1,388 @@
var state = require('../managers/state'),
session = require('../managers/session'),
editor = require('../editor/'),
{icon} = require('./utils'),
fullscreen = require('./fullscreen'),
notifications = require('./notifications'),
{enableTraversingGestures, disableTraversingGestures} = require('../events/drag'),
locales = require('../locales'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
contextMenu = require('./context-menu')
var sidepanelData = [
{
actions: [
{
label: locales('sidepanel_fs') + (ELECTRON_FULLSCREEN ? ' (F11)' : ''),
action:()=>{
if (fullscreen.isEnabled) fullscreen.toggle()
},
class:'toggle fullscreenToggle' + (!fullscreen.isEnabled || ELECTRON_FULLSCREEN ? ' disabled' : '')
}
]
},
{
label: icon('sliders-h') + '&nbsp; ' + locales('sidepanel_state'),
actions: [
{
label: locales('state_store'),
action:()=>{
state.quickSave()
DOM.get('.quickload')[0].classList.remove('disabled')
notifications.add({
icon: 'sliders-h',
message: locales('state_storesuccess')
})
}
},
{
label: locales('state_recall'),
action: ()=>{
state.quickLoad()
},
class:'disabled quickload'
},
{
label: locales('state_send'),
action: ()=>{
state.send()
notifications.add({
icon: 'sliders-h',
message: locales('state_sendsuccess')
})
}
},
{
label: locales('editor_load'),
action:()=>{
state.browse()
}
},
{
label: locales('editor_save'),
action:()=>{
state.save(state.statePath)
}
},
{
label: raw(icon('ellipsis-h')),
class: 'narrow',
menu: [
{
label: locales('editor_save_as'),
action:()=>{
state.saveAs()
}
},
{
label: locales('state_import'),
click: true,
action:state.import.bind(state)
},
{
label: locales('state_export'),
click: true,
action:state.export.bind(state)
},
]
}
]
},
{
label: icon('magic') + '&nbsp; ' + locales('sidepanel_traversing'),
actions: [
{
label: 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'
},
{
label: 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'
},
{
label: 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'
}
]
},
{
label: icon('edit') + '&nbsp; ' + locales('sidepanel_editor'),
class:'editor-menu',
actions: [
{
label: locales('editor_on'),
action:editor.enable.bind(editor),
class:'enable-editor'
},
{
label: locales('editor_off'),
action:editor.disable.bind(editor),
class:'on disable-editor'
},
{
label: raw(icon('vector-square')),
class:'editor-root disabled narrow',
title: locales('editor_root')
},
{
label: locales('editor_load'),
action:session.browse.bind(session)
},
{
label: locales('editor_save'),
action:()=>{
session.save()
}
},
{
label: raw(icon('ellipsis-h')),
class: 'narrow',
menu: [
{
label: locales('editor_save_as'),
action:()=>{
session.saveAs()
}
},
{
label: locales('editor_import'),
click: true,
action: ()=>{
session.import()
}
},
{
label: locales('editor_export'),
click: true,
action: ()=>{
session.export()
}
}
]
}
]
},
]
if (navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) {
var NoSleep = require('nosleep.js'),
noSleep = new NoSleep(),
noSleepState = false
sidepanelData[0].actions.push({
label: locales('sidepanel_nosleep'),
class: 'toggle',
action:(el)=>{
noSleepState = el.classList.toggle('on')
if (noSleepState) {
noSleep.enable()
} else {
noSleep.disable()
}
}
})
}
var options = html`<ul id="options"></ul>`
for (let i in sidepanelData) {
let data = sidepanelData[i],
item = html`
<li>
<div class="${data.class || ''}">
<div class="actions">
${data.label ? html`<div class="title">${raw(data.label)}</div>` : ''}
</div>
</div>
</li>
`,
wrapper = DOM.get(item, '.actions')[0]
for (let j in data.actions) {
let actionData = data.actions[j],
element = html`<a class="btn ${actionData.class || ''}" title="${actionData.title || ''}">${actionData.label}</a>`
if (actionData.action) element.addEventListener('click', ()=>{actionData.action(element)})
if (actionData.menu) {
element.addEventListener('fast-click', (e)=>{
contextMenu.open(e.detail, actionData.menu)
})
}
wrapper.appendChild(element)
}
options.appendChild(item)
}
var sidepanel = document.getElementById('sidepanel-wrapper'),
sidepanelContainer = document.getElementById('sidepanel')
sidepanel.appendChild(html`
<div class="navigation"><ul><li><a>${PACKAGE.productName.toUpperCase()}</a></li></ul></div>
`)
sidepanel.appendChild(options)
sidepanel.appendChild(html`<div id="editor"></div>`)
// Fullscreen
var fsToggle = DOM.get(sidepanel, '.fullscreenToggle')[0]
if (fullscreen.isEnabled) {
fullscreen.on('change', ()=>{
fsToggle.classList.toggle('on', fullscreen.isFullScreen)
})
}
// open / close / toggle
/*
var sidepaneLock = false
function sidepanelOpen() {
sidepaneLock = true
DOM.get('#sidepanel')[0].classList.remove('hide')
setTimeout(function(){
DOM.each(document, '#open-toggle, #sidepanel', (el)=>{
el.classList.add('sidepanel-open')
})
})
setTimeout(function(){
DOM.get('#container')[0].classList.add('sidepanel-open')
setTimeout(function(){
DOM.dispatchEvent(window, 'resize')
sidepaneLock = false
}, 25)
}, 250)
}
function sidepanelClose() {
if (sidepaneLock) return
DOM.each(document, '#open-toggle, #sidepanel, #container', (el)=>{
el.classList.remove('sidepanel-open')
})
setTimeout(function(){
if (sidepaneLock) return
DOM.get('#sidepanel')[0].classList.add('hide')
}, 250)
setTimeout(function(){
DOM.dispatchEvent(window, 'resize')
}, 25)
}
function sidepanelToggle() {
if (sidepanelContainer.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 sidepanelWidth
$('osc-panel-container sidepanel-handle').draggable({
cursor:'col-resize',
start: ()=>{
sidepanelWidth = parseInt(sidepanelContainer.offsetWidth) / PXSCALE
sidepanelContainer.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: ()=>{
sidepanelContainer.classList.remove('resizing')
}
})
module.exports = {
open: sidepanelOpen,
close: sidepanelClose,
toggle: sidepanelToggle
}
*/
module.exports = {
open: ()=>{},
close: ()=>{},
toggle: ()=>{}
}

View file

@ -0,0 +1,193 @@
var UiWidget = require('./ui-widget'),
html = require('nanohtml'),
Tab, Root, Modal
class UiDragResize extends UiWidget {
constructor(options) {
Tab = require('../widgets/containers/tab')
Root = require('../widgets/containers/root')
Modal = require('../widgets/containers/modal')
super(options)
this.container = html`
<div id="drag-resize">
<div class="position-handle"></div>
<div class="helper"></div>
<div class="no-widget-select handle nw" data-action="left,top"></div>
<div class="no-widget-select handle e" data-action="width"></div>
<div class="no-widget-select handle s" data-action="height"></div>
<div class="no-widget-select handle se" data-action="width,height"></div>
</div>
`
this.initLeft = 0
this.initTop = 0
this.initWidth = 0
this.initHeight = 0
this.left = 0
this.top = 0
this.width = 0
this.height = 0
this.mounted = false
this.handles = DOM.get(this.container, '.handle')
this.dragging = null
this.on('draginit', (event)=>{
var node = event.firstTarget
if (!this.handles.includes(node)) return
this.initLeft = this.left
this.initTop = this.top
this.initWidth = this.width
this.initHeight = this.height
this.container.classList.add('dragging')
this.dragging = node.getAttribute('data-action').split(',')
event.traversing = false
}, {element: this.container})
this.on('drag', (event)=>{
if (!this.dragging) return
for (var k of this.dragging) {
switch (k) {
case 'left':
case 'width':
this[k] += event.movementX / PXSCALE
break
case 'top':
case 'height':
this[k] += event.movementY / PXSCALE
break
}
}
this.updateCss(true)
}, {element: this.container})
this.on('dragend', (event)=>{
var node = event.firstTarget
if (!this.handles.includes(node)) return
this.container.classList.remove('dragging')
this.left = Math.max(0, this.left)
this.top = Math.max(0, this.top)
this.trigger(this.dragging.indexOf('left') > -1 ? 'move' : 'resize', this)
this.dragging = null
}, {element: this.container})
// handles appear on top of modal widgets
// very special case fix here...
this.watchedModalWidget = null
this.checkModalState = (e)=>{
if (e.widget !== this.watchedModalWidget) return
console.log(e.widget.value)
this.container.style.display = e.widget.value ? 'none' : ''
}
}
clear() {
if (!this.mounted) return
if (this.watchedModalWidget) {
// reset modal widget fix
this.watchedModalWidget.off('change', this.checkModalState)
this.watchedModalWidget = null
this.container.style.display = ''
}
this.container.parentNode.removeChild(this.container)
this.mounted = false
}
create(widgets) {
this.clear()
var widget = widgets[0]
if (widget instanceof Modal) {
// modal widget fix
this.watchedModalWidget = widget
widget.on('change', this.checkModalState)
if (widget.getValue()) this.container.style.display = 'none'
}
if (
widget instanceof Tab ||
widget instanceof Root ||
!widget.getProp('visible')
) return
var handlesVisibility = [
!(widget instanceof Tab) && widget.parent.getProp('layout') === 'default', // nw
widget.parent.getProp('layout') !== 'vertical', // e
widget.parent.getProp('layout') !== 'horizontal', // s
]
handlesVisibility.push(handlesVisibility[1] && handlesVisibility[2]) // se
for (var i in handlesVisibility) {
this.handles[i].style.display = handlesVisibility[i] ? '' : 'none'
}
var parent = widget.parentNode,
lefts = widgets.map(w => w.container.offsetLeft),
tops = widgets.map(w => w.container.offsetTop),
rights = widgets.map(w => w.container.offsetLeft + w.container.offsetWidth),
bottoms = widgets.map(w => w.container.offsetTop + w.container.offsetHeight)
this.left = Math.min(...lefts) / PXSCALE
this.top = Math.min(...tops) / PXSCALE
this.width = (Math.max(...rights) - Math.min(...lefts)) / PXSCALE
this.height = (Math.max(...bottoms) - Math.min(...tops)) / PXSCALE
this.updateCss()
parent.appendChild(this.container)
this.mounted = true
}
updateCss(grid) {
for (var k of ['top', 'left', 'width', 'height']) {
var val = this[k]
if (k === 'width' || k === 'height') val = Math.max(10 * PXSCALE, val)
if (grid) val = Math.round(val / GRIDWIDTH) * GRIDWIDTH
this.container.style.setProperty('--' + k, val + 'rem')
}
}
}
module.exports = UiDragResize

View file

@ -0,0 +1,120 @@
var UiWidget = require('./ui-widget'),
{categories} = require('../widgets/'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
{icon, Popup} = require('../ui/utils')
class UiInspectorField extends UiWidget {
constructor(options) {
super(options)
this.name = options.name
this.widget = options.widget
this.value = options.value
this.default = options.default
this.container = html`<osc-inspector-field></osc-inspector-field>`
this.label = this.container.appendChild(html`<label>${this.name}</label>`)
if (this.name === 'type') this.createTypeSelect()
else this.createInput()
}
createTypeSelect() {
if (this.widget.props.type == 'tab' || this.widget.props.type == 'root') {
this.container.appendChild(html`
<textarea class="no-keybinding" name="${this.name}" rows="1" disabled>${this.value}</textarea>
`)
return
}
this.createInput()
var select = html`<select class="no-keybinding" name="${this.name}"/>`
for (let cname in categories) {
var optGroup = html`<optgroup label="${cname}"></optgroup>`
for (let wtype of categories[cname]) {
optGroup.appendChild(html`<option ${wtype == this.value ? 'selected' : ''} value="${wtype}">${wtype}</option>`)
}
select.appendChild(optGroup)
}
var wrapper = html`<osc-inspector-select></osc-inspector-select>`
wrapper.appendChild(select)
this.container.appendChild(wrapper)
}
createInput() {
var stringValue = typeof this.value !== 'string' ?
JSON.stringify(this.value, null, ' ').replace(/\n\s\s\s\s/g, ' ').replace(/\n\s\s(\}|\])/g, ' $1') : this.value
var input = html`<textarea class="no-keybinding" name="${this.name}" rows="${stringValue.split('\n').length}">${stringValue}</textarea>`
this.container.appendChild(input)
if (this.default.choices) {
let wrapper = html`<osc-inspector-select></osc-inspector-select>`,
select = wrapper.appendChild(html`<select class="no-keybinding" name="${this.name}"/>`)
for (let choice of this.default.choices) {
select.appendChild(html`<option ${choice == this.value ? 'selected' : ''} value="${choice}">${choice}</option>`)
}
this.container.appendChild(wrapper)
}
if (this.name.includes('color')) {
let picker = html`<input class="osc-inspector-color" type="color" name="${this.name}" value="${this.value}"/>`
this.container.appendChild(picker)
}
if (this.default.type.includes('boolean')) {
let toggle = html`
<osc-inspector-checkbox class="${this.widget.getProp(this.name) ? 'on' : ''}">
${raw(icon('check'))}
</osc-inspector-checkbox>
`
toggle.addEventListener('click', ()=>{
if (this.name === 'label' && !this.widget.getProp(this.name) === true) {
// special case
input.value = 'auto'
} else {
input.value = !this.widget.getProp(this.name)
}
DOM.dispatchEvent(input, 'change')
})
this.container.appendChild(toggle)
}
}
}
module.exports = UiInspectorField

View file

@ -0,0 +1,188 @@
var UiWidget = require('./ui-widget'),
UiInspectorField = require('./ui-inspector-field'),
morph = require('nanomorph'),
{widgets, defaults} = require('../widgets/'),
{deepCopy} = require('../utils'),
html = require('nanohtml')
class UiInspector extends UiWidget {
constructor(options) {
super(options)
this.mounted = false
this.foldedCategories = []
this.container.addEventListener('fast-click', (e)=>{
if (e.target.classList.contains('category-header')) {
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.container.addEventListener('change', this.onChange.bind(this))
this.container.addEventListener('keydown', this.onKeydown.bind(this))
this.container.addEventListener('input', this.textAutoHeight.bind(this))
this.container.addEventListener('focus', this.textAutoHeight.bind(this))
this.lock = false
}
clear() {
this.container.innerHTML = ''
this.mounted = false
}
inspect(widgets) {
var content = html`<div></div>`
var widget = widgets[0],
props = defaults[widget.props.type],
multi = widgets.length > 1
// this.form.appendChild(html`
// <div class="separator">
// <span class="${this.selectedWidgets.length > 1 ? 'accent' : ''}">
// Widget${multi ? 's' : ''}: ${multi ? this.selectedWidgets.length + ' selected': widget.getProp('id')}
// </span>
// </div>
// `)
let category
for (let propName in props) {
if (propName === 'tabs' || propName === 'widgets') continue
let field,
shared = true
for (var w of widgets) {
if (defaults[w.props.type][propName] === undefined) {
shared = false
}
}
if (!shared) continue
if (propName.indexOf('_') === 0 && propName !== '_props') {
if (category) content.appendChild(category)
category = html`<osc-inspector-category class="${this.foldedCategories.indexOf(props[propName]) > -1 ? 'folded' : ''}"></osc-inspector-category>`
field = html`<div class="category-header" data-name="${props[propName]}">${props[propName]}</div>`
} else if (widget.props[propName] === undefined) {
continue
} else {
// if (widget.parent !== widgetManager && widget.parent.getProp('type') === 'strip') {
// // special case for widgets in strips
// if (propName === 'top' || propName === 'left' || propName === (widget.parent.getProp('horizontal') ? 'height' : 'width')) continue
// }
field = new UiInspectorField({
parent: this,
widget: widget,
name: propName,
value: widget.props[propName],
default: defaults[w.props.type][propName]
}).container
if (!field) continue
}
if (category) {
category.appendChild(field)
} else {
content.appendChild(field)
}
}
if (category) content.appendChild(category)
if (this.mounted) {
morph(this.container.firstChild, content)
} else {
this.container.appendChild(content)
}
this.mounted = true
}
onChange(event) {
if (this.lock) return
this.lock = true
var input = event.target
input.blur()
var v
var str = input.value.replace(/[‟”]/g, '"').replace(/[‘’]/g, '\'') // convert invalid quote characters
try {
v = JSON.parseFlex(str)
if (typeof v === 'string') {
// escape backslashes in simple strings only
v = JSON.parseFlex(str.replace(/\\/g, '__BACKSLASH__'))
v = v.replace(/__BACKSLASH__/g, '\\')
}
} catch(err) {
v = str
}
this.trigger('update', {
propName: input.name,
value: v
})
this.lock = false
}
onKeydown(event) {
var input = event.target
if (event.keyCode === 13 && !event.shiftKey) {
event.preventDefault()
DOM.dispatchEvent(input, 'change')
}
}
textAutoHeight(event) {
var input = event.target
input.setAttribute('rows',0)
input.setAttribute('rows', input.value.split('\n').length)
}
}
module.exports = UiInspector

97
src/client/ui/ui-modal.js Normal file
View file

@ -0,0 +1,97 @@
var UiWidget = require('./ui-widget'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
{iconify} = require('../ui/utils')
class UiModalWindow {
constructor(options) {
this.container = html`
<osc-modal-window class="${options.class || ''}">
<inner>
${options.content}
</inner>
</osc-modal-window>
`
if (options.label) {
this.container.appendChild(html`<label>${raw(iconify(options.label))}</label>`)
}
this.opened = false
}
open(z) {
this.opened = true
this.container.classList.add('on')
this.container.style.zIndex = z
}
close() {
this.opened = false
this.container.classList.remove('on')
}
}
class UiModal extends UiWidget {
constructor(options) {
super(options)
this.modals = {}
this.openedModals = []
}
create(id, options) {
if (this.modals[id]) this.destroy(id)
this.modals[id] = new UiModalWindow(options)
this.container.appendChild(this.modals[id].container)
}
destroy(id) {
if (!this.modals[id]) return
this.close(id)
this.container.removeChild(this.modals[id].container)
delete this.modals[id]
}
open(id) {
if (!this.modals[id]) return
if (this.openedModals.includes(id)) this.close(id)
this.openedModals.push(id)
this.modals[id].open(this.openedModals.length)
}
close(id) {
if (!this.modals[id] || !this.openedModals.includes(id)) return
this.openedModals.splice(this.openedModals.indexOf(id), 1)
this.modals[id].close()
}
}
module.exports = UiModal

View file

@ -0,0 +1,128 @@
var html = require('nanohtml')
class UiSelectArea {
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 = document.body.appendChild(html`<div class="select-area hidden"></div>`)
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 = UiSelectArea

View file

@ -0,0 +1,112 @@
var UiWidget = require('./ui-widget')
class UiSidePanel extends UiWidget {
constructor(options) {
super(options)
this.resizeDirection = this.container.classList.contains('left') ? 1 : -1
this.resizeHandle = DOM.get(this.container, '.resize-handle')[0]
this.toggleButton = DOM.get(this.container, '.toggle-button')[0]
this.content = DOM.get(this.container, 'osc-panel-inner')[0]
this.minWidth = 250
this.width = 250
this.disabled = true
this.minimized = false
this.init = false
this.on('drag', (event)=>{
this.width += this.resizeDirection * event.movementX / PXSCALE
this.container.style.width = this.width + 'rem'
}, {element: this.resizeHandle})
this.on('dragend', (event)=>{
this.width = parseInt(this.container.offsetWidth) / PXSCALE
DOM.dispatchEvent(window, 'resize')
}, {element: this.resizeHandle})
this.toggleButton.addEventListener('click', ()=>{
if (this.disabled) return
if (this.minimized) this.restore()
else this.minimize()
})
}
enable() {
this.container.classList.remove('disabled')
this.disabled = false
if (!this.minimized) this.open()
}
disable() {
this.container.classList.add('disabled')
this.disabled = false
this.close()
}
minimize() {
if (this.minimized) return
this.minimized = true
this.close()
}
restore() {
if (!this.minimized) return
this.minimized = false
this.open()
}
open() {
this.container.style.width = this.width + 'rem'
this.container.style.minWidth = this.minWidth + 'rem'
this.container.classList.remove('minimized')
DOM.dispatchEvent(window, 'resize')
}
close() {
this.container.style.width = 0
this.container.style.minWidth = 0
this.container.classList.add('minimized')
DOM.dispatchEvent(window, 'resize')
}
}
var leftUiSidePanel = new UiSidePanel({selector: 'osc-panel-container.right'}),
rightUiSidePanel = new UiSidePanel({selector: 'osc-panel-container.left'})
module.exports = {
left: leftUiSidePanel,
right: rightUiSidePanel
}

159
src/client/ui/ui-tree.js Normal file
View file

@ -0,0 +1,159 @@
var UiWidget = require('./ui-widget'),
html = require('nanohtml'),
doubleClick = require('../events/double-click'),
Sortable = require('sortablejs'),
morph = require('nanomorph'),
Panel, widgetManager
class UiTree extends UiWidget {
constructor(options) {
Panel = require('../widgets/containers/panel')
widgetManager = require('../managers/widgets')
super(options)
this.mounted = false
this.list = this.container.appendChild(html`<ol style="--depth: 1"></ol`)
this.dragDummy = html`<span></span>`
this.expanded = {root: true}
this.container.addEventListener('fast-click', (event)=>{
var node = event.target
if (node.classList.contains('toggle')) {
var exp = node.parentNode.classList.toggle('expanded')
if (exp) {
this.expanded[node.parentNode.getAttribute('data-id')] = true
} else {
delete this.expanded[node.parentNode.getAttribute('data-id')]
}
}
})
doubleClick(this.container, (event)=>{
var node = event.target
if (node.classList.contains('container')) {
var exp = node.classList.toggle('expanded')
if (exp) {
this.expanded[node.getAttribute('data-id')] = true
} else {
delete this.expanded[node.getAttribute('data-id')]
}
}
}, {ignoreEditorCapture: true})
this.sortables = []
this.sortCallback = (event)=>{
var widget = widgetManager.widgets[event.to.parentNode.getAttribute('data-widget')]
if (!widget) return
this.trigger('sorted', {
widget: widget,
oldIndex: event.oldIndex,
newIndex: event.newIndex
})
}
}
clear() {
this.list.innerHTML = ''
this.mounted = false
for (var s of this.sortables) {
s.destroy()
}
this.sortables = []
}
updateTree(selectedWidgets) {
for (var s of this.sortables) {
s.destroy()
}
this.sortables = []
var content = this.parseWidgets(widgetManager.getWidgetById('root')[0], selectedWidgets)
// morph DOM
if (this.mounted) {
morph(this.list.firstChild, content)
} else {
this.list.appendChild(content)
}
// sortable lists
DOM.each(this.list, 'ol', (el)=>{
this.sortables.push(new Sortable(el, {
group: {
name: 'group-' + el.parentNode.getAttribute('data-widget'),
pull: false,
put: false
},
onEnd: this.sortCallback,
setData: (dataTransfer)=>{
dataTransfer.setDragImage(this.dragDummy, 0, 0)
},
}))
})
this.mounted = true
}
select() {
// hint selection in folded containers
DOM.each(this.list, '.contains-editing', (element)=>{
element.classList.remove('contains-editing')
})
var selected = DOM.get(this.list, '.editing')[0]
if (selected) {
var node = selected.parentNode
while (node && node !== this.list) {
if (node.classList.contains('container')) {
node.classList.add('contains-editing')
}
node = node.parentNode
}
}
}
parseWidgets(widget, selectedWidgets, depth = 1) {
var selected = selectedWidgets.includes(widget),
id = widget.getProp('id'),
node = html`<li class="${selected ? 'editing' : ''} ${!widget.getProp('visible') ? 'invisible' : ''}"
data-widget="${widget.hash}"
data-id="${id}"">
${id}</li>`
if (widget instanceof Panel) {
node.insertBefore(html`<span class="toggle no-widget-select"></span>`, node.childNodes[0])
node.classList.add('container')
if (this.expanded[id]) node.classList.add('expanded')
var sublist = node.appendChild(html`<ol style="--depth:${++depth};"></ol>`)
for (let child of widget.children) {
sublist.appendChild(this.parseWidgets(child, selectedWidgets, depth))
}
}
return node
}
}
module.exports = UiTree

View file

@ -0,0 +1,16 @@
var EventEmitter = require('../events/event-emitter')
class UiWidget extends EventEmitter {
constructor(options) {
super()
this.container = options.selector ? DOM.get(options.selector)[0] : options.element
this.parent = options.parent
}
}
module.exports = UiWidget

View file

@ -0,0 +1,16 @@
var UiWidget = require('./ui-widget'),
setScrollbarColor = require('./scrollbar-color')
class UiWorksapce extends UiWidget {
constructor(options) {
super(options)
setScrollbarColor(this.container)
}
}
module.exports = new UiWorksapce({selector: 'osc-workspace'})

350
src/client/ui/utils.js Normal file
View file

@ -0,0 +1,350 @@
var popupSingleton = null,
uploadSingleton = null,
locales = require('../locales'),
html = require('nanohtml'),
raw = require('nanohtml/raw'),
ipc = require('../ipc'),
EventEmitter = require('../events/event-emitter'),
doubleTap = require('../widgets/mixins/double_tap')
module.exports = {
Popup: class Popup extends EventEmitter {
constructor(options) {
super()
if (options.closable) {
if (popupSingleton) {
popupSingleton.close()
popupSingleton = null
}
popupSingleton = this
}
this.closable = options.closable
this.escKey = options.closable || options.escKey
this.enterKey = options.enterKey
this.content = options.content
this.title = options.title
this.state = 0
this.html = html`
<div class="popup show">
<div class="popup-wrapper">
<div class="popup-title ${this.closable? 'closable' : ''}">
<span class="title">
${options.icon ? raw(module.exports.icon(options.icon)) : ''}
${this.title}
</span>
${this.closable? html`<span class="closer">${raw(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)
}
if (!options.hide) 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)
this.trigger('close')
}
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)
this.trigger('open')
}
},
loading: function(title){
return new module.exports.Popup({
title: title,
content: html`<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 = html`<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()
},
remoteBrowse: function(options, callback) {
var save = options.save,
saveInputFocus = undefined
var popup = new module.exports.Popup({
closable: true,
title: locales(save ? 'remotesave_save' : 'remotesave_open'),
hide: true
})
var container = DOM.get(popup.html, '.popup-content')[0],
browser = html`<div class="file-browser"></div>`,
ariane = html`<div class="ariane"></div>`,
list = html`<form class="file-list"></form>`,
saveInput = html`<input type="text" class="save-as no-keybinding" placeholder="${options.extension ? '*.' + options.extension : ''}" ${options.save ? '' : 'disabled'}/>`,
actions = html`
<div class="file-actions">
${saveInput}
<div class="btn cancel">${raw(module.exports.icon('times'))} Cancel</div>
${
save ?
html`<div class="btn submit save">${raw(module.exports.icon('save'))} Save</div>` :
html`<div class="btn submit open">${raw(module.exports.icon('folder-open'))} Open</div>`
}
</div>
`
var files = [],
path = ''
var extRe = options.extension ? new RegExp('.*\\.' + options.extension + '$') : /.*/
if (save) {
saveInput.addEventListener('change', ()=>{
if (!saveInput.value.match(extRe)) saveInput.value += '.' + options.extension
})
saveInput.addEventListener('focus', ()=>{
saveInputFocus = true
})
list.addEventListener('change', ()=>{
saveInputFocus = false
var choice = DOM.get(list, ':checked')[0]
if (choice && choice.classList.contains('file')) {
saveInput.value = choice.value
}
})
}
doubleTap(list, submit, {click: true})
function submit(){
var choice = DOM.get(list, ':checked')[0]
if (!choice && (!save || !saveInput.value) && !options.loadDir) return
if (choice && choice.classList.contains('folder') && (!save || !saveInputFocus)) {
ipc.send('listDir', {path: [path, choice.value]})
} else {
if (save) {
if (files.some(x=>x.name===saveInput.value)) {
if (!confirm(locales('remotesave_overwrite'))) return
}
callback([path, saveInput.value])
popup.close()
} else {
callback([path, choice ? choice.value : ''])
popup.close()
}
}
}
actions.addEventListener('click', (e)=>{
if (e.target.classList.contains('submit')) {
submit()
} else if ((e.target.classList.contains('cancel'))){
popup.close()
}
})
function keyDownHandler(e){
if (e.keyCode === 13) {
if (save) {
document.addEventListener('keyup', keyUpHandler)
} else {
submit()
}
} else if (e.target === saveInput) {
return
} else if (e.keyCode === 8) {
list.childNodes[0].firstElementChild.checked = true
submit()
} else if (e.key.length === 1) {
var letter = e.key.toLowerCase(),
current = DOM.get(list, ':checked')[0],
minIndex = -1,
index = -1
if (current) minIndex = DOM.index(current.parentNode)
for (let i in files) {
if (files[i].name[0].toLowerCase() === letter && !list.childNodes[i].firstElementChild.checked) {
if (index === -1) index = i
if (minIndex !== -1 && i < minIndex) continue
index = i
break
}
}
if (index !== -1) {
list.childNodes[index].firstElementChild.click()
list.childNodes[index].firstElementChild.focus()
}
}
}
function keyUpHandler(e){
if (e.keyCode === 13) {
setTimeout(submit, 100)
document.removeEventListener('keyup', keyUpHandler)
}
}
document.addEventListener('keydown', keyDownHandler)
ipc.on('listDir', (data)=>{
ariane.textContent = path = data.path
files = data.files.filter(x=>x.folder || x.name.match(extRe))
function alphaSort(a, b){
// convert to strings and force lowercase
a = typeof a.name === 'string' ? a.name.toLowerCase() : a.name.toString()
b = typeof b.name === 'string' ? b.name.toLowerCase() : b.name.toString()
return a.localeCompare(b)
}
var fo = files.filter(x=>x.folder),
fi = files.filter(x=>!x.folder)
fo.sort(alphaSort)
fi.sort(alphaSort)
files = fo.concat(fi)
files.unshift({
name: '..',
folder: true
})
browser.removeChild(list)
list.innerHTML = ''
for (let i in files) {
var file = files[i]
list.appendChild(html`
<div class="file">
<input type="radio" value="${file.name}" name="file" class="${file.folder ? 'folder' : 'file'}"/>
<div class="label"><span>${raw(module.exports.icon(file.folder ? 'folder' : 'osc'))} ${file.name}</span></div>
</div>
`)
}
browser.insertBefore(list, actions)
if (save && saveInputFocus === undefined) {
saveInput.focus()
} else {
list.childNodes[0].firstElementChild.focus()
}
}, {context: popup})
popup.on('close', ()=>{
ipc.off('listDir', null, popup)
document.removeEventListener('keydown', keyDownHandler)
document.removeEventListener('keyup', keyUpHandler)
})
browser.appendChild(ariane)
browser.appendChild(list)
browser.appendChild(actions)
container.appendChild(browser)
ipc.send('listDir', {extension: options.extension, path: options.directory ? [options.directory] : null})
popup.open()
}
}

29
src/client/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')
}
}, {passive: false})
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')
}
}, {passive: true})