-BrowserStack provides remote browsers for debbuging.
+BrowserStack provides remote browsers for debugging.
diff --git a/resources/docs/docs/custom-module/custom-module.md b/resources/docs/docs/custom-module/custom-module.md
index f36dcb0c..985c5eed 100644
--- a/resources/docs/docs/custom-module/custom-module.md
+++ b/resources/docs/docs/custom-module/custom-module.md
@@ -1,17 +1,35 @@
# Custom module
+Using the server's `custom-module` option, users can load a custom javascript module that filters incoming and outgoing OSC / MIDI messages.
+
## Writing a custom module
-Using the `-c / --custom-module` command-line switch, users can load a javascript file to tune the way Open Stage Control behaves regarding osc.
```js
-// Do whatever you want, initialize some variables, declare some functions, ...
+// Do whatever you want
+// initialize variables
+// declare functions
+// listen to app events
+// load modules
+// etc
module.exports = {
init: function(){
- // this will be executed once when the osc server starts
+ // this will be executed once when the osc server starts after
+ // connections are set up
+ // it is called for the main module only
+ },
+
+ stop: function(){
+ // this will be executed once when the osc server stops
+ // it is called for the main module only
+ },
+
+ reload: function(){
+ // this will be executed after the custom module is reloaded
+ // it is called for the main module only
},
oscInFilter:function(data){
@@ -40,7 +58,12 @@ module.exports = {
// return data if you want the message to be and sent
return {address, args, host, port}
- }
+ },
+
+ unload: function(){
+ // this will be executed before the custom module is reloaded
+ // it is called for all modules, including other loaded modules
+ },
}
@@ -53,7 +76,7 @@ The module is executed in a restricted context, only a few globals are available
----
#### `app`
-[`Event Emitter`](https://nodejs.org/api/events.html#events_class_eventemitter), useful for monitoring the events sent by the different clients. Event names can be found in [callbacks.js](https://github.com/jean-emmanuel/open-stage-control/blob/master/src/server/callbacks.js), callbacks are called with 2 arguments: `data` (object) and `client` (object: `{address, id}`)
+[`Event Emitter`](https://nodejs.org/api/events.html#events_class_eventemitter), useful for monitoring the events sent by the different clients. Event names can be found in [callbacks.js](https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/src/server/node/ipc/callbacks.mjs), callbacks are called with 2 arguments: `data` (object) and `client` (object: `{address, id}`)
----
@@ -64,14 +87,16 @@ Send osc/midi message to connected clients. `host` and `port` can be specified t
- `host` (optional): `string` ip address, valid hostname or `"midi"`
- `port` (optional): `integer` port number or `string` midi device name
- `address`: osc address
-- `args`: value or `{type: "OSC_TYPE_LETTER", value: VALUE}` `object`
-- `options` (optional): set to `{clientId: id}` to define which client receives the message (where `id` is the client's id as retreived from `app` events or `oscOutFilter`)
+- `args`: value or `{type: "OSC_TYPE_LETTER", value: VALUE}` `object` (objects that don't match this format will simply be turned to a JSON string).
+- `options` (optional): set to `{clientId: id}` to define which client receives the message (where `id` is the client's id as retrieved from `app` events or `oscOutFilter`)
+
+For convenience, `host` and `port` can be provided both as single string argument joined with a colon.
----
#### `send(host, port, address, ...args)`
-Send osc/midi to a target.
+Send osc/midi to a target (see `receive()`).
----
@@ -87,40 +112,109 @@ Returns the server's http addresses.
----
-#### `options`
-
-`Array` containing the extra options passed to `--custom-module` after the filename
-
-----
-
-#### `loadJSON(path)`
+#### `loadJSON(path, errorCallback)`
Loads a json file (path is relative to the custom module location)
+- `path`: `string`, path to file (any extension allowed, but the content must be valid JSON)
+- `errorCallback` (optional): `function`, called with the error as argument if the file can't be loaded
+
+
----
-#### `saveJSON(path, object)`
+#### `saveJSON(path, data, errorCallback)`
Saves an object/array to a json file (path is relative to the custom module location)
+- `path`: `string`, path to file (any extension allowed)
+- `data`: `object`, `array` or any value that can be encoded to JSON
+- `errorCallback` (optional): `function`, called with the error as argument if the file can't be loaded
+
----
#### `require(path)`
-Load another javascript module. Returns the value of `module.exports` defined in this module. If `path` is a relative path, it will be resolved against its parent module's path. See [Managing Big Modules](../managing-big-modules)
+Load another javascript module. Returns the value of `module.exports` defined in this module. If `path` is a relative path, it will be resolved against its parent module's path. See [Managing Big Modules](../managing-big-modules).
+
+This function is different from node's native `require` function, it's merely a way to split a custom module into separate files.
----
+#### `nativeRequire(moduleName)`
+
+This function can be used to load native node modules or locally installed modules (e.g. with npm) if a `node_modules` folder is found in the custom module's location.
+
+??? "Installing node modules: resources"
+ - https://nodejs.dev/
+ - https://nodejs.dev/learn/an-introduction-to-the-npm-package-manager
+ - https://nodejs.dev/learn/the-package-json-guide
+
+----
+
+#### `tcpServer`
+
+Raw access to the server's [TCP backend](https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/src/server/node/osc/tcp.mjs). Can be used to monitor the state of TCP connections:
+
+```js
+for (var ip in tcpServer.clients) {
+ tcpServer.clients[ip].port.on('ready', ()=>{
+ console.log(`TCP connection established with ${ip}:${tcpServer.clients[ip].remotePort}`)
+ })
+ tcpServer.clients[ip].port.on('close', ()=>{
+ console.log(`TCP connection lost with ${ip}:${tcpServer.clients[ip].remotePort}`)
+ })
+}
+```
+
+
+#### `restartMidiBackend()`
+
+This function can be used to restart the midi backend (if already running) without restarting the server
+
#### Other javascript globals
+
- `console`
- `setTimeout`
- `clearTimeout`
- `setInterval`
- `clearInterval`
+- `__dirname`
+- `__filename`
+- `process`
+- `global`
----
## Autoreload
-Custom modules (including submodules loaded with `require()`) are reloaded automatically when they are modified. Upon reload, timers (`setTimeout` and `setInterval`) and event listeners (added to the `app` object) are reset.
+Custom modules (including submodules loaded with `require()`) are reloaded automatically when they are modified. Upon reload, timers (`setTimeout` and `setInterval`) and event listeners (added to the `app` object) are reset. After each reload the `module.exports.reload()` function (if any) is called.
+
+The `global` object persists accross reloads.
+
+??? "Reloading native modules"
+
+ When using modules loaded with `nativeRequire()`, you may need to tell the custom module how to unload some components to allow reloading using the `module.exports.unload` definition. For example, if a port is bound using the `http` module, you'll need to unbind it otherwise the custom module will fail to bind it again when reloading:
+
+ ```js
+
+ var http = nativeRequire('http'),
+ server = http.createServer((req, res)=>{
+ res.writeHead(200)
+ res.end('Hello world')
+ })
+
+ server.listen(5555, 'localhost')
+
+
+ module.exports = {
+
+ unload: function() {
+
+ server.close()
+ // otherwise you'd get "Error: listen EADDRINUSE: address already in use 127.0.0.1:5555"
+
+ }
+
+ }
+ ```
diff --git a/resources/docs/docs/custom-module/examples.md b/resources/docs/docs/custom-module/examples.md
index dfd3908f..d903870c 100644
--- a/resources/docs/docs/custom-module/examples.md
+++ b/resources/docs/docs/custom-module/examples.md
@@ -178,6 +178,65 @@ module.exports = {
}
+```
+
+## Auto-save client state
+
+```js
+// store state in a variable
+var state = {}
+
+// keep track of connected clients
+var clients = []
+
+app.on('sessionOpened', (data, client)=>{
+
+ // client connected (and in a session)
+ if (!clients.includes(client.id)) clients.push(client.id)
+
+ // when a client opens a session, send the state
+ // but only if it's the only connected client (otherwise, let the regular sync happen)
+ if (clients.length === 1) {
+ receive('/STATE/SET', state, {clientId: clients[0]})
+ }
+
+})
+
+app.on('close', (data, client)=>{
+
+ // client disconnected
+ if (clients.includes(client.id)) clients.splice(clients.indexOf(client.id))
+
+})
+
+// request 1st client's state every 10 seconds
+setInterval(()=>{
+
+ if (clients.length > 0) {
+ receive('/STATE/GET', '127.0.0.1:8888', {clientId: clients[0]})
+ }
+
+}, 10000)
+
+
+module.exports = {
+
+ oscOutFilter: function(data) {
+
+ if (data.address === '/STATE/GET') {
+ // update state variable when the client responds
+ state = data.args[0].value
+
+ // bypass the osc message
+ return
+ }
+
+ return data
+
+ }
+
+}
+
```
## MIDI routing
@@ -236,3 +295,177 @@ module.exports = {
}
```
+
+
+## Read file
+
+```js
+
+var fs = nativeRequire('fs')
+
+module.exports = {
+
+ oscOutFilter:function(data){
+ // Filter outgoing osc messages
+
+ var {address, args, host, port} = data
+
+ if (address === '/file') {
+
+ fs.readFile(args[0].value, 'utf8' , (err, data) => {
+ if (err) {
+ console.error(err)
+ return
+ }
+ receive('/html', data)
+ })
+
+ return // bypass original message
+
+ }
+
+
+ // return data if you want the message to be processed
+ return {address, args, host, port}
+
+ }
+
+
+}
+```
+
+## Display RTSP Stream
+
+```js
+// requires ffmpeg installed on the system
+// and rtsp-ffmpeg installed in the custom module's folder (by running npm install rtsp-ffmpeg)
+// see https://github.com/agsh/rtsp-ffmpeg#ffmpeg for available options
+
+var rtsp = nativeRequire('rtsp-ffmpeg')
+
+var stream = new rtsp.FFMpeg({
+ input: 'rtsp://freja.hiof.no:1935/rtplive/_definst_/hessdalen03.stream',
+})
+
+stream.on('data', (data)=>{
+
+ // send frame to image widget with address set to "/stream"
+ receive('/stream', 'data:image/jpeg;base64,' + data.toString('base64'))
+
+})
+
+module.exports = {
+
+ unload: ()=>{
+ stream.stop()
+ }
+
+}
+```
+
+## Custom module merger
+```js
+var submodules = [
+ require('./custom_modA.js'),
+ require('./custom_modB.js'),
+ // etc
+]
+
+
+module.exports = {
+ init: function(){
+ for (var m of submodules) {
+ if (m.init) m.init()
+ }
+ },
+ reload: function(){
+ for (var m of submodules) {
+ if (m.reload) m.reload()
+ }
+ },
+ oscInFilter: function(data){
+
+ for (var m of submodules) {
+ if (m.oscInFilter) data = m.oscInFilter(data)
+ if (!data) return
+ }
+
+ return data
+
+ },
+ oscOutFilter: function(data){
+
+ for (var m of submodules) {
+ if (m.oscOutFilter) data = m.oscOutFilter(data)
+ if (!data) return
+ }
+
+ return data
+ }
+}
+```
+
+## Dynamic widget creation
+```js
+function create_widgets() {
+ receive('', '', '/EDIT', 'root', {
+ widgets: [{
+ type: 'panel',
+ id: 'my_panel',
+ layout: 'vertical',
+ width: '100%',
+ height: '200%',
+ widgets: [
+ {
+ type: 'text',
+ id: 'notice',
+ value: 'Hello, world!',
+ width: '100%',
+ },
+ {
+ type: 'button',
+ id: 'button',
+ address: '/foo',
+ preArgs: [1],
+ },
+ ]
+ }]
+ })
+}
+
+module.exports = {
+ reload: function(){
+ // Create widgets whenever the custom modules is edited
+ create_widgets()
+ },
+}
+
+// Create widgets whenever an existing session is loaded
+app.on('sessionOpened', ()=>{
+ create_widgets()
+})
+
+// And when a new session is created
+app.on('sessionSetPath', (e)=>{
+ if (e.path === '') {
+ create_widgets()
+ }
+})
+```
+
+
+## Simple bridge
+
+```js
+module.exports = {
+
+ oscInFilter: function(data) {
+
+ // pass through incoming messages directly to another application
+ send('127.0.0.1', 12345, data.address, ...args)
+
+ return data // let original message reach clients / widgets
+ }
+
+}
+```
diff --git a/resources/docs/docs/customization/css-tips.md b/resources/docs/docs/customization/css-tips.md
index 5803809a..95e7c236 100644
--- a/resources/docs/docs/customization/css-tips.md
+++ b/resources/docs/docs/customization/css-tips.md
@@ -3,7 +3,7 @@
## Browser inspector
-Hit ++f12++ to open the developers tools panel. The html/css inspector helps retreiving the class names needed to style specific parts of the widgets: hit ++ctrl+shift+c++ or click on the inspect icon () and click on a element in the interface to reveal its html code.
+Hit ++f12++ to open the developers tools panel. The html/css inspector helps retrieving the class names needed to style specific parts of the widgets: hit ++ctrl+shift+c++ or click on the inspect icon () and click on a element in the interface to reveal its html code.
## Inline syntax
@@ -11,7 +11,7 @@ Hit ++f12++ to open the developers tools panel. The html/css inspector helps ret
For simple use cases, the `css` property can be written as a HTML inline styles (without any CSS selector). CSS rules will apply to the widget element.
```css
-opacity: 0.5; /* make the widget's transparent */
+opacity: 0.5; /* make the widget transparent */
font-size: 120%; /* increase font-size */
```
@@ -27,12 +27,12 @@ CSS selectors can be used to apply styles to specific elements:
*/
}
-.label {
- /* style for the .label elements */
+label {
+ /* style for the label elements */
}
-> .label {
- /* style for the direct child .label element */
+> label {
+ /* style for the direct child label element */
}
```
@@ -50,7 +50,7 @@ Multiple classes can be added (one per `class` statement). Custom classes are al
## Layering: `z-index`
-Z-Axis ordering can be set using the `z-index` rule. Absolutely positionned widgets (when `top` or `left` is different from `auto`) have `z-index:10;` by default.
+Z-Axis ordering can be set using the `z-index` rule. Widgets positioned at absolute coordinates (when `top` or `left` is different from `auto`) have `z-index:10;` by default.
## Responsive sizing
@@ -87,6 +87,14 @@ Media queries can also be used:
## CSS variables
-[CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) declared in the [default theme](https://github.com/jean-emmanuel/open-stage-control/blob/master/src/scss/themes/default.scss) can be overriden.
+[CSS variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) declared in the [default theme](https://github.com/jean-emmanuel/open-stage-control/blob/master/src/scss/themes/default.scss) can be overridden.
Widgets also rely on CSS variables for the style properties (colors, padding, etc). These are documented in the widgets' `css` property description.
+
+# Loading images
+
+Image urls are resolved in this order:
+- in the session's directory
+- in theme's directory
+- in the server's `remote-root` directory if the option is set
+- as absolute paths
diff --git a/resources/docs/docs/customization/themes.md b/resources/docs/docs/customization/themes.md
index bf08c98d..0af1d8fe 100644
--- a/resources/docs/docs/customization/themes.md
+++ b/resources/docs/docs/customization/themes.md
@@ -33,4 +33,4 @@ Theme files are reloaded automatically when they are modified.
## SCSS
-If you want to use the [SCSS](https://sass-lang.com/documentation/syntax) syntax to write your theme, follow the [Running from sources](../../getting-started/running-from-sources) instructions, create a `.scss` file in `src/browser/scss/themes/` and run `npm run watch-css`. The theme will be watched and compiled automatically to a css file located in `app/browser/themes/` (css files in this directory can be selected from the theme option by their name, without .css suffix).
+If you want to use the [SCSS](https://sass-lang.com/documentation/syntax) syntax to write your theme, follow the [Running from sources](../../getting-started/running-from-sources) instructions, create a `.scss` file in `src/scss/themes/` and run `npm run watch-css`. The theme will be watched and compiled automatically to a css file located in `app/assets/themes/` (css files in this directory can be selected from the theme option by their name, without .css suffix).
diff --git a/resources/docs/docs/getting-started/introduction.md b/resources/docs/docs/getting-started/introduction.md
index 314a3cec..bcff82e9 100644
--- a/resources/docs/docs/getting-started/introduction.md
+++ b/resources/docs/docs/getting-started/introduction.md
@@ -1,11 +1,8 @@
Welcome to Open Stage Control documentation. Along these pages you'll learn how to setup OSC on your system and everything you need to start building your own control interface.
-!!! info "Still using v0 ?"
- The documentation for this version is available [here](https://v0.openstagecontrol.ammd.net).
-
## Overview
-Open Stage Control consists in 3 modules: the server, the launcher and the client.
+Open Stage Control consists of 3 modules: the server, the launcher and the client.
The **server** is the core of the software, it is responsible for sending and receiving all osc/midi messages, and act as a web server that serves the clients web application. It is written in Javascript and runs with Electron, a cross-platform framework based on Chromium. By default, the server always opens a client window when it starts but it can be run in *headless* mode, without any window.
@@ -20,15 +17,15 @@ The **server** can run on all [platforms supported by Electron](https://www.elec
The **client** is compatible with the following browsers:
-- Firefox: version `75`
-- Chromium / Chrome: version `60`
+- Firefox: version `75` and higher
+- Chromium / Chrome: version `75` and higher
-iOS devices must be of version `10.3` or higher.
+iOS devices must be of version `11` or higher.
## Installation
-??? example "Linux 64bit"
+=== "Linux 64bit"
**Ubuntu / Debian**
@@ -44,19 +41,28 @@ iOS devices must be of version `10.3` or higher.
- Extract it in the location of your choice
- The file inside it named `open-stage-control` is the app's main executable
-??? example "Mac 64bit"
+=== "Mac 64bit"
- - [Download](/download) `open-stage-control-VERSION-osx.zip`
+ - [Download](/download) `open-stage-control-VERSION-osx-x64.zip`
- Extract it in the location of your choice
- Drag `open-stage-control.app` in your `Application` folder
-??? example "Windows 64bit"
+
+=== "Mac Silicon (arm)"
+
+ - [Download](/download) `open-stage-control-VERSION-osx-arm.zip`
+ - Extract it in the location of your choice
+ - Drag `open-stage-control.app` in your `Application` folder
+
+ See [https://disable-gatekeeper.github.io/](https://disable-gatekeeper.github.io/) to workaround the "damaged and can't be opened" error.
+
+=== "Windows 64bit"
- [Download](/download) `open-stage-control-VERSION-win32-x64.zip`
- Extract it in the location of your choice
- The file inside it named `open-stage-control.exe` is the app's main executable
-??? example "Other systems"
+=== "Other systems"
- Install [Node.js](https://nodejs.org/en/download/package-manager/)
- Download `open-stage-control-VERSION-node.zip`
diff --git a/resources/docs/docs/getting-started/running-from-sources.md b/resources/docs/docs/getting-started/running-from-sources.md
index 58c19463..dd4a90c0 100644
--- a/resources/docs/docs/getting-started/running-from-sources.md
+++ b/resources/docs/docs/getting-started/running-from-sources.md
@@ -12,7 +12,7 @@ Running the app from the sources slightly differs from using prebuilt binaries:
**Download**
```bash
-git clone https://github.com/jean-emmanuel/open-stage-control
+git clone https://framagit.org/jean-emmanuel/open-stage-control.git
cd open-stage-control/
# uncomment next line if you want the latest release
# instead of the current development version
@@ -22,8 +22,9 @@ npm run build
```
!!! tip "Raspberry systems"
- Run this instead of `npm install` if the architecture is `armv7l`
+ Run one of these instead of `npm install` (you can get the system's `arch` by running `uname -m` in a terminal)
```
+ npm install --arch=arm64
npm install --arch=armv7l
```
@@ -44,6 +45,10 @@ npm start [ -- options]
!!! info ""
A double hyphen (`--`) is used here to tell npm that the options are to be passed to the app.
+
+!!! warning "MIDI support"
+ When running from sources, MIDI support won't be enabled unless the [MIDI configuration procedure](../../midi/midi-configuration/) for "other systems" is followed.
+
## Build documentation
In order to make the local documentation available through the server's `--docs` option and the launcher's `Documentation` menu action, an extra step is needed.
@@ -82,8 +87,23 @@ This will build the app in `dist/open-stage-control-PLATFORM-ARCH`.
Building the app for windows from a linux system requires wine to be installed.
-## Debian/Ubuntu installer
+## Debian / Ubuntu and RPM installers
-```
-npm run deb64
-```
+=== "Debian / Ubuntu"
+
+ ```
+ npm run deb64
+ ```
+
+=== "RPM"
+
+ ```
+ npm run rpm
+ ```
+
+
+## Build script on Mac Silicon
+
+This user-contributed script can be used to build open stage control on recent Macs:
+
+https://github.com/rewgs/osc-as
diff --git a/resources/docs/docs/getting-started/server-configuration.md b/resources/docs/docs/getting-started/server-configuration.md
index 09c51688..63fa6ca8 100644
--- a/resources/docs/docs/getting-started/server-configuration.md
+++ b/resources/docs/docs/getting-started/server-configuration.md
@@ -27,6 +27,8 @@ The **server** can be configured with many options, either from a terminal or wi
Path to a custom module file (.js).
+ **WARNING:** custom module can access the file system, use at your own risk.
+
!!! quote ""
#### `port`
@@ -64,7 +66,7 @@ The **server** can be configured with many options, either from a terminal or wi
!!! quote ""
#### `debug`
- Print sent and receiced messages in the console. This may impact performances and should not be enabled in production.
+ Print sent and received messages in the console. This may impact performance and should not be enabled in production.
@@ -168,6 +170,25 @@ The following options can only be set from a terminal.
Override default config file location (contains session history and launcher config). Defaults to `cache-dir/config.json`.
+
+!!! quote ""
+ #### `client-position`
+
+ Define the built-in client window position, must be a pair of integers separated by a comma (`x,y`).
+
+
+
+!!! quote ""
+ #### `client-size`
+
+ Define the built-in client window size, must be a pair of integers separated by a comma (`width,height`).
+
+!!! quote ""
+ #### `no-qrcode`
+
+ Disable qrcode when the server starts.
+
+
!!! quote ""
#### `help`
@@ -176,7 +197,7 @@ The following options can only be set from a terminal.
!!! quote ""
#### `docs`
- Serve documentation website locally and open it with the system\'s default browser
+ Serve documentation website locally and open it with the system's default browser
!!! quote ""
diff --git a/resources/docs/docs/midi/midi-configuration.md b/resources/docs/docs/midi/midi-configuration.md
index fe306c37..feb3984a 100644
--- a/resources/docs/docs/midi/midi-configuration.md
+++ b/resources/docs/docs/midi/midi-configuration.md
@@ -3,10 +3,10 @@
=== "Linux / Windows / OSX"
- Since version `1.7.0`, Open Stage Control comes bundled with built-in MIDI support if you're using the 64bit package for Linux, OSX or Windows.
+ Open Stage Control comes bundled with built-in MIDI support if you're using the official package for Linux, OSX or Windows.
-=== "Other systems"
+=== "Other systems / Node"
Enabling MIDI support on other systems or when building Open Stage Control from sources requires additional softwares to be installed on the server's system:
@@ -16,8 +16,10 @@
??? example "Linux"
+ Install `python3-rtmidi` from your distribution's package repository, or if it's not available:
+
- Install `python3` and `python3-pip` from your distribution's package repository
- - Install `python-rtmidi` from a terminal by executing this command
+ - Run this command in a terminal
```bash
python3 -m pip install python-rtmidi --upgrade
```
@@ -56,7 +58,7 @@
The server's `midi` option accepts the following parameters, separated by spaces.
!!! warning ""
- If an option contains space characters, it must be enquoted.
+ If an option contains space characters, it must be quoted.
**`list`**
@@ -64,7 +66,7 @@ Print the available MIDI ports to the console when the server starts. This actio
**`device_name:input,output`**
-Create a virtual MIDI device that will translate OSC messsages to MIDI messages
+Create a virtual MIDI device that will translate OSC messages to MIDI messages
- `device_name` is an arbitrary identifier that can be used as a target by widgets (see [Widget setup](#widget-setup)). It doesn't have to match any device's real name.
- `input` / `output` can be port numbers or strings (as reported by the `list` action). If a string is specified, the first port whose name contains the string will be used (comparison is case-insensitive).
@@ -77,10 +79,27 @@ Enable parsing of system exclusive messages (disabled by default).
Enable parsing of midi time code messages (disabled by default).
+**`rpn`**
+
+Enable sending and receiving [RPN/NRPN](https://en.wikipedia.org/wiki/NRPN) controls on as single `/rpn` / `/nrpn` messages instead of 3 or 4 control changes that constitute them.
+
+
+**`active_sensing`**
+
+Enable parsing of midi active sensing messages (disabled by default). Active sensing messages will be received as sysex.
+
**`pc_offset`**
Send program changes with a `-1` offset to match some software/hardware implementations
+**`note_off_velocity`**
+
+Use `/note_on` for noteOn messages and `/note_off` for noteOff messages instead of the defaut `/note` and velocity 0 for note off.
+
+**`auto_note_off`**
+
+Prevent converting outgoing noteOn messages with velocity 0 to noteOff messages.
+
**`device_name:virtual`** (*Linux / Mac only*): creates a virtual midi device with one input port and one output port
@@ -90,7 +109,9 @@ Send program changes with a `-1` offset to match some software/hardware implemen
**`path=/path/to/python`**
-Indicates where to find python binary in case open stage control doesn't (`Error: spawn python3 ENOENT`). *Only use this if you know what you are doing.*
+*Only use this if you know what you are doing. This option should not be set when using the official Linux / Windows / OSX packages.*
+
+Indicates where to find python binary in case open stage control doesn't (`Error: spawn python3 ENOENT`).
## Widget setup
@@ -106,7 +127,7 @@ Its `address` and `preArgs` properties must be set according to Open Stage Contr
## Debug
-Enabling the server's `debug` options will print some extra informations (sent/received midi messages, midi setup informations, etc)
+Enabling the server's `debug` options will print some extra information (sent/received midi messages, midi setup information, etc)
## Example configuration
diff --git a/resources/docs/docs/midi/midi-messages.md b/resources/docs/docs/midi/midi-messages.md
index 132e8404..e189dcfe 100644
--- a/resources/docs/docs/midi/midi-messages.md
+++ b/resources/docs/docs/midi/midi-messages.md
@@ -5,7 +5,7 @@
#### `/note channel note velocity`
-NoteOn event or noteOff if velocity equals `0`.
+NoteOn event or noteOff if velocity equals `0`. Incoming noteOff events will be received as `/note` with velocity 0 if `note_off_velocity` is not set during [setup](../midi-configuration).
- `channel`: integer between 1 and 16
- `note`: integer between 0 and 127
@@ -23,6 +23,12 @@ NoteOn event or noteOff if velocity equals `0`.
----
+#### `/note_off channel note velocity`
+
+NoteOff event with any velocity. Incoming noteOff events will be received as `/note_off` if `note_off_velocity` is set during [setup](../midi-configuration).
+
+----
+
#### `/control channel cc value`
Control change event.
@@ -101,3 +107,24 @@ Polyphonic key pressure event.
- `pressure`: integer between 0 and 127
----
+
+
+#### `/rpn channel rpn value`
+
+Registered Parameter Number event.
+
+- `channel`: integer between 1 and 16
+- `rpn`: integer between 0 and 16383
+- `value`: integer between 0 and 16383
+
+----
+
+#### `/nrpn channel nrpn value`
+
+Non-Registered Parameter Number event.
+
+- `channel`: integer between 1 and 16
+- `nrpn`: integer between 0 and 16383
+- `value`: integer between 0 and 16383
+
+----
diff --git a/resources/docs/docs/remote-control.md b/resources/docs/docs/remote-control.md
index f3e983ce..a25fb9db 100644
--- a/resources/docs/docs/remote-control.md
+++ b/resources/docs/docs/remote-control.md
@@ -1,6 +1,6 @@
# Remote control
-When osc messages are received, the default behavior is to update the value of all widgets that match the address and preArgs. Additionally, Open Stage Control responds to some general osc commands.
+When osc messages are received, the default behavior is to update the value of all widgets that match the address and preArgs. Additionally, Open Stage Control clients respond to some general osc commands.
!!! note "Multi-client setup"
These commands are interpreted by each client connected to the server so there might be more than one reply. Using a custom module is the only way to send a message to a single client.
@@ -11,8 +11,7 @@ When osc messages are received, the default behavior is to update the value of a
#### `/EDIT id properties options`
-Apply a set of options to an existing widget by replacing the old ones with the new ones.
-
+Apply a set of options to an existing widget by replacing the old ones with the new ones. This ignores the widget's `lock` property. If sent by a custom module using `receive()`, this command will not be prevented by the server's `read-only` option.
- `id`: `string`, widget's `id`
- `properties`: `string`, [JSON5](https://github.com/json5/json5) stringified object defining the new properties to merge
@@ -20,10 +19,6 @@ Apply a set of options to an existing widget by replacing the old ones with the
- `options` (optional): `string`, [JSON5](https://github.com/json5/json5) stringified object defining extra option flags:
- `noWarning`: set to `true` to prevent further warning when exiting.
-!!! danger "Warning"
- Editing widgets is cpu expensive; for small and recurrent changes, consider using [osc listeners](./widgets/advanced-syntaxes.md) instead.
-
-
----
#### `/EDIT/MERGE id properties options`
@@ -117,10 +112,20 @@ Same as `/GET` but uses the widget's address instead of `/GET` to reply.
----
-#### `/NOTIFY message`
+#### `/NOTIFY icon message`
Sends a notification message to the client.
+- `icon`: icon for the notification, for example : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)
+- `message`: message content
+
+
+----
+
+#### `/LOG message`
+
+Print message in the client's console.
+
----
#### `/SET id value`
@@ -154,11 +159,12 @@ Sends back the app's state to specified target
----
-#### `/STATE/SET state`
+#### `/STATE/SET state send`
Set widgets' state
- `state`: `string`, json stringified object (`"widget_id": value` pairs)
+- `send` (optional): `boolean`, set to `false` to prevent widgets from sending their values when the state is applied
@@ -175,6 +181,13 @@ Save the state of all widgets in the temporary slot.
Reload saved state from the temporary slot.
+
+----
+
+#### `/STATE/SEND`
+
+Make all widgets send their current value.
+
----
#### `/STATE/OPEN path.state`
@@ -185,10 +198,15 @@ Open state file `path.state`.
#### `/STATE/SAVE path.state`
-Save state session to `path.state`. If `path.state` is omitted, current session's path is used.
+Save state session to `path.state`.
----
+#### `/SESSION/CREATE`
+
+Create a new empty session. Unsaved changes will be lost.
+
+----
#### `/SESSION/OPEN path.json`
Open session file `path.json`.
@@ -198,3 +216,22 @@ Open session file `path.json`.
#### `/SESSION/SAVE path.json`
Save current session to `path.json`. If `path.json` is omitted, current session's path is used.
+
+----
+
+#### `/TABS tab_id1 tab_id2 ...`
+
+Open the tabs designated by the id parameters.
+
+----
+
+#### `/SCRIPT code`
+
+Run code as if it where executed by a script widget.
+
+
+----
+
+#### `/RELOAD`
+
+Reload page in the browser.
diff --git a/resources/docs/docs/tutorials/change-property-with-osc.md b/resources/docs/docs/tutorials/change-property-with-osc.md
new file mode 100644
index 00000000..1c9a83c8
--- /dev/null
+++ b/resources/docs/docs/tutorials/change-property-with-osc.md
@@ -0,0 +1,149 @@
+# Change a widget property with an osc message
+
+By default, widgets only expose their value to incoming messages, but there are multiple ways to allow changing any widget property using osc messages as well. In this tutorial we'll explore the different possibilities for exposing the `visible` property of a widget to incoming messages, but it applies to any other property.
+
+## 1. Using a variable widget
+
+Create a variable widget and set up its `address` (and `preArgs` if needed) so that it receives the messages you want to use, and then in your other widget's `visible` property, use the [inheritance syntax](../widgets/advanced-syntaxes.md#inheritance-idproperty) to retrieve the variable's value:
+
+
+=== "Inheritance syntax"
+ ```
+ @{variable_id}
+ ```
+=== "Inheritance syntax + Javascript"
+ ```js
+ JS{
+ // bonus, in case you don't want to use the variable's value as-is
+ if (@{variable_id} > 0.5) {
+ return true
+ } else {
+ return false
+ }
+ }
+ ```
+
+Now the variable's value will determine the visibility of the widget. The `visible` property expects a boolean value (`true` for visible, `false` for invisible) but any [truthy](https://developer.mozilla.org/en-US/docs/Glossary/truthy) / [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) will do (e.g. `1` for visible, `0` for invisible is a sensible choice).
+
+## 2. Using the OSC listener syntax
+
+The [OSC listener syntax](../widgets/advanced-syntaxes.md#osc-listeners-oscaddress-default-usepreargs) might be a more straightforward solution for simple use cases. Writing this in a widget's `visible` property:
+
+
+=== "Relative address"
+ ```
+ OSC{show}
+ ```
+
+will listen for messages on address `/widget_address/show` and return the last received value.
+
+
+If we write this instead:
+
+=== "Absolute address"
+ ```
+ OSC{/show}
+ ```
+
+the address will be `/show` and won't be prefixed with the widget's address as before.
+
+
+It is often needed to specify the initial state of the listener (before it receives any message), this is done via the second argument of the listener syntax:
+
+
+=== "Default value (true)"
+ ```
+ OSC{show, true}
+ ```
+=== "Default value (truthy)"
+ ```
+ OSC{show, 1}
+ ```
+=== "Default value (false)"
+ ```
+ OSC{show, false}
+ ```
+=== "Default value (falsy)"
+ ```
+ OSC{show, 0}
+ ```
+
+If the widget has any preArgs set, the osc listener will inherit them by default, this means that for a message to change the listener's value it will not only have to match its address but also the widget's `preArgs`, this can be prevented using the third argument of the listener syntax:
+
+=== "Ignore preArgs"
+ ```
+ OSC{show, 1, false}
+ ```
+
+
+## 3. Using custom variables
+
+The [custom variable syntax](../widgets/advanced-syntaxes.md#custom-variables-varvariablename-default) connects regular properties and scripting properties (`onCreate`, `onValue`, etc), writing this in the `visible` property:
+
+```
+VAR{show}
+```
+
+will create a custom variable named `show` scoped to the widget (custom variables do not use a global namespace and multiple widgets may use the same names for their custom variables without conflict). This custom variable can be read and set from any widget scripting property using the [`getVar()` / `setVar()`](../widgets/scripting.md#getvarid-name) functions.
+
+For instance, we could use a variable widget as osc receiver like in the first example of this tutorial and use it's `onValue` script to change the custom variable's value (instead of using the inheritance syntax):
+
+```js
+// variable widget onValue
+// simply pass received value to the custom variable
+setVar('widget_id', 'show', value)
+```
+
+
+The custom variable's initial state can be specified:
+
+```
+VAR{show, 1}
+```
+
+## 4. Using /EDIT commands
+
+The [`/EDIT`](../remote-control.md) remote control command can be used to modify any widget property in the session, for instance:
+
+```
+/EDIT widget_id '{visible: false}'
+```
+
+Will hide the widget with id `widget_id`. Note that this is different from the 3 techniques described above in that it actually modifies the session and changes the property value in a destructive way (the property is rewritten, not just its state). When quitting the session after using it a warning indicating the session has unsaved changes will be shown, this can be prevented by appending a extra argument to the message:
+
+```
+/EDIT widget_id '{visible: false}' '{noWarning: true}'
+```
+
+Note that the arguments after `widget_id` are sent as strings ([JSON5](https://github.com/json5/json5)-encoded objects), this is because sending plain javascript object over osc is not possible.
+
+## Bonus: custom module
+
+Any of these techniques can be used in conjunction with a [custom module](../custom-module/custom-module.md). Using the `receive()` function allows simulating incoming osc messages and can be used to trigger property changes:
+
+=== "Variable widget"
+ ```js
+ var visible = true
+ receive('/variable_id', visible)
+ // or if variable widgets has preArgs
+ receive('/variable_id', preArg1, preArg2, visible)
+ ```
+=== "OSC listener"
+ ```js
+ var visible = true
+ receive('/widget_address/show', visible)
+ // or if listener has preArgs
+ receive('/widget_address/show', preArg1, preArg2, visible)
+ ```
+=== "Custom variable"
+ ```js
+ var visible = true
+ receive('/SCRIPT', `setVar('widget_id', 'show', ${visible})`)
+ ```
+=== "/EDIT command"
+ ```js
+ var visible = true
+ // what's really cool here is that you don't need to stringify objects arguments
+ // receive() will take care of that for you
+ receive('/EDIT', 'widget_id', {visible: visible}}, {noWarning: true})
+ ```
diff --git a/resources/docs/docs/tutorials/first-steps.md b/resources/docs/docs/tutorials/first-steps.md
new file mode 100644
index 00000000..71df540c
--- /dev/null
+++ b/resources/docs/docs/tutorials/first-steps.md
@@ -0,0 +1,252 @@
+# First Steps with Open Stage Control
+
+*Contributed by H. James Harkins, Feb. 2023*
+
+Let's walk through the basic steps to build a simple interface in Open Stage Control, send information to another app, and deploy the interface to remote (even mobile) devices.
+
+Before beginning, you should already have installed Open Stage Control -- see the [Introduction](../getting-started/introduction.md).
+
+Also: This document provides sample patches for SuperCollider, Pure Data and Max/MSP, to receive control data from the Open Stage Control interface. If you do not have any of these tools, I suggest to install [Pure Data](https://puredata.info/downloads/pure-data) because it has the smallest footprint.
+
+## The Launcher
+
+Use your system's application launcher, open the Open Stage Control app. Here, you can configure options for the interface server.
+
+For now, go to the first box ("send") and type in `127.0.0.1:57120`. This will tell the server to send Open Sound Control messages to the same machine where the server is running, on port 57120.
+
+NOTE: For your own applications, you can use any port that is not in use. For this example, I chose 57120 because it is SuperCollider's default UDP port (and I set the Pure Data and Max patches to use the same port, to simplify.)
+
+You don't need to set any other options at this time.
+
+### Addresses and ports
+
+Many users approaching Open Sound Control for the first time get confused about ports. You need to be aware of the FROM and TO addresses. The "send" field in the Launcher should reference the address TO which messages should be sent. In this demo, we are assuming that Open Stage Control and the target app are running on the same machine. So the TO address is localhost: `127.0.0.1`. The "send" box should use the port *on which the target app is receiving messages*. This is typically under control of the target app: 1/ SuperCollider opens 57120 by default; 2/ Pd's [netreceive] object, and Max's [udpreceive], both require the TO port as an argument. So the TO port is your choice, as long as they match.
+
+Open Stage Control sends messages FROM the IP address of the machine where Open Stage Control is running, and from port 8080 (or localhost = `127.0.0.1` if on the same machine). Thus, if the receiving app will filter incoming messages based on address, the filtering address should be the FROM address, port 8080. The target app can also update Open Stage Control's display by sending messages back to exactly this address. So you will see later, in the demo patches, that messages are sent to `127.0.0.1:8080` so that the user's interaction with the target app appears in Open Stage Control as well.
+
+## Starting the server
+
+Click the "play" button near the top left of the window. You should see status messages in the launcher window such as:
+
+```
+(INFO) Server started, app available at
+ http://127.0.0.1:8080
+ http://your.ip.ad.dress:8080
+```
+
+And a new, mostly empty, window will open. This new, larger window is the *client*.
+
+## The client
+
+The client allows you to edit and perform your interface.
+
+The interface design is called a *session*. To create a new session, go to the "three-dots" menu at the top left, and choose Session > New session.
+
+Two new panels are displayed: a project browser, and an object inspector (to set properties). The empty space in the middle is the editor, where you will build the interface.
+
+Let's start with a toggle button. Right-click in the empty editor panel in the middle, and navigate to Add widget > Basics > button. For this demo, we don't need to change anything else: the button defaults to toggle behavior, and the display text is not important for now (although you can change it in the inspector, if you want).
+
+And let's add one more control, to the right of this: Right-click, Add widget > Sliders > fader.
+
+
+
+When a widget is selected, you can move it by dragging the top-left handle, and resize it by dragging the bottom-right handle. Let's use these handles to position the fader to the right of the button, and stretch it to be horizontal instead of vertical.
+
+
+
+Notice, however, that the fader's value handle is still vertical. To fix this, look in the Inspector at the right, expand "Fader style," and check the "horizontal" checkbox.
+
+
+
+
+
+By the way: I suggest to keep the widgets closer to the top left, so that they are still visible on a phone screen (later).
+
+When designing an interface for production, you would change other object properties as well. In particular, the Open Sound Control addresses `/button_1` and `/fader_1` are not very descriptive. You would probably want to assign different command paths, in the "osc" tab. As this is just an introduction, we won't do that now.
+
+## Receiving the data
+
+At this time, the interface can already be used: three-dots menu > Editor > "Enabled" (click to disable the editor). (The controls will respond also when the editor is enabled, but you have to click an extra time to select the widget before changing its value.)
+
+To see the effect, launch one of the following apps and open the given patch. The Open Stage Control button should open and close the envelope, and the fader should control frequency. The patches also send control data from their own GUIs back to Open Stage Control, so all of the controls should be synced in both directions.
+
+NOTE: In Pure Data and Max, the default slider/fader range is 0-127, integers. Open Stage Control uses the range 0.0 - 1.0 by default. If you just create a slider and connect it, you won't see much action. In the example patches, the slider's properties have been modified to take a 0.0 - 1.0 floating-point range, matching the data from Open Stage Control.
+
+NOTE: Because all of the patches bind to the same UDP port, you can open only one at a time. You could, if you like, change the port number in one patch, and add that port by specifying multiple "send" targets in the Launcher, e.g. `127.0.0.1:57120 127.0.0.1:7374`.
+
+NOTE: These patches are provided as a courtesy to get you started more quickly. Maintaining, extending or developing them is outside the scope of the Open Stage Control community.
+
+!!! Example "Choose your app"
+
+ === "Pure Data"
+
+ Copy the code below, and save it into a text file `osc-first-steps.pd`. Then open it in Pure Data.
+
+ ```
+ #N canvas 436 127 562 502 12;
+ #X obj 86 51 loadbang;
+ #X msg 86 76 \; pd dsp 1;
+ #X obj 253 51 netreceive -u -b 57120;
+ #X obj 253 76 oscparse;
+ #X obj 253 101 list trim;
+ #X obj 253 126 route fader_1 button_1;
+ #X msg 253 190 4 \$1;
+ #X obj 253 215 pow;
+ #X obj 253 240 * 200;
+ #X obj 253 265 lop~ 3;
+ #X msg 328 265 \$1 100;
+ #X obj 328 304 line~;
+ #X obj 279 356 *~;
+ #X obj 279 381 *~ 0.1;
+ #X obj 266 424 dac~;
+ #X text 38 139 Open Stage Control \; "First Steps" tutorial \; hjh
+ 2023;
+ #X obj 253 304 osc~ 200;
+ #X obj 328 159 tgl 15 0 empty empty empty 17 7 0 10 #fcfcfc #000000
+ #000000 0 1;
+ #X obj 256 159 hsl 60 15 0 1 0 0 empty empty empty -2 -8 0 10 #fcfcfc
+ #000000 #000000 0 1;
+ #X obj 70 251 unpack f s;
+ #X obj 70 325 oscformat;
+ #X msg 137 283 set \$1;
+ #X obj 70 424 netsend -u -b;
+ #X obj 93 356 loadbang;
+ #X msg 93 381 connect 127.0.0.1 8080;
+ #X obj 70 226 r sendback;
+ #X msg 379 200 \; sendback \$1 button_1;
+ #X msg 379 233 \; sendback \$1 fader_1;
+ #X connect 0 0 1 0;
+ #X connect 2 0 3 0;
+ #X connect 3 0 4 0;
+ #X connect 4 0 5 0;
+ #X connect 5 0 18 0;
+ #X connect 5 1 17 0;
+ #X connect 6 0 7 0;
+ #X connect 7 0 8 0;
+ #X connect 8 0 9 0;
+ #X connect 9 0 16 0;
+ #X connect 10 0 11 0;
+ #X connect 11 0 12 1;
+ #X connect 12 0 13 0;
+ #X connect 13 0 14 0;
+ #X connect 13 0 14 1;
+ #X connect 16 0 12 0;
+ #X connect 17 0 10 0;
+ #X connect 17 0 26 0;
+ #X connect 18 0 6 0;
+ #X connect 18 0 27 0;
+ #X connect 19 0 20 0;
+ #X connect 19 1 21 0;
+ #X connect 20 0 22 0;
+ #X connect 21 0 20 0;
+ #X connect 23 0 24 0;
+ #X connect 24 0 22 0;
+ #X connect 25 0 19 0;
+ ```
+
+ === "Max/MSP"
+
+ Copy the text below. In Max, choose File > New from clipboard.
+
+ ```
+ ----------begin_max5_patcher----------
+ 949.3oc0XkraaCCD8rCP9GHDxo.GWRJpEWzaEnW6gdrInfVlwgoxjBRTYEMe
+ 6khTx0HgVlwP1MFAwBZnjl2algyBe9zSFELS9.qJ.7YvOAiF8rVxHirFIi5D
+ LJXI8grbZk4ACVxppnKXAiaWTwdPYV3SWSmyJ+EBbFZ0h74lkjyt8BDdkzBp
+ J6FtXwuJYYJq1wwjIvw.LJt4RRh4F7DH3ptWRTujKxYJCJvqIUVq5Di5Dako
+ drfY+7AAfqLK8mSOo4p9x3AfwypUJoXiTNtWFSBaHIJB1bIM5iDiEr603+sD
+ tddQESLGfvZGj9ODHElBc5s8f5gnTqEHdKbG4l6vcleYxkKYB0aI32KXBvOT
+ ZuM3qRgpTlCtL3a7xJkVJqn5x.fpVIK4zbvEfat8F.FhCW8cx4BVlrVX9XgN
+ LK3DerKv0BLHoGNyRUNWuC1k6DG0GtsHEAM9wXCGvvsC6qykTkF3E0pdnC5e
+ JtjtjozoXXB5rbSbNruv+t0p3OYjhlr6lFkbwhblSSCoOSCBkLIZksAS5988
+ 4R2Qa.uIP7pgeWxWt3BPVNO62.kDXABfVOmKcZe5MuOJzj3iDEYLSsUAfGtX
+ d1SyoYu3D3vdi4mNIQiXhcKKIp622W5a3fmh97W.57xNSIOsO9jfab.gSmZH
+ xfW+shuPPy2G0jN2oyCk5AYiwFZNs4liCx1TfwMeS7HKTaAWBb27t3sQ3wff
+ YTwh8RuVmgzIQc2pQrGTGaqQEAOFZyJ6wr7M3lIauNbqWd3o5+ivZz14KNM7
+ XNpNxcPMzCh21gX3wPL845p5vItnZpGL0NVHYvGRxzB5dwyR1vLgIdzHc693
+ ihQBKj26hl9LufceaX3GNm5l3ZoVULvpy4X03+tL.djn11rKJhrECPnaCP3l
+ 8yia+e+bD.Zdv32w.QIHryjWgdTjxFBfR1sQ+eOw31uroFyqOpKC7ZV3UVhJ
+ YcYV2Wr6vq.qgw4rJEWPUboX8mx9Pa1l6s9Zl21C88JTIKaFeu+wJ7GBDefP
+ 7dDAwGVadpWpCNX5KwG8EMXpyqHpzAScdE8fiFT8g1p9HCl9B8gejCbBgjMr
+ aDcvxGfh2iPn4DL7HnB9w.Bn8TZQjeIplNXwdHuxTYfEZXTneY9SFNFR7lgC
+ jBQdovgK+AB5kBcWMssCJZQwcrxp1WwpKcSi2JMg1ois2yE16ssnETxti28J
+ 1SpNfVp6IToaHrtz.wfGha6VNXoTuQQTy61t1v1FUa5KUP0SaUPs7xz+5omn
+ ef+B9C+QQC
+ -----------end_max5_patcher-----------
+ ```
+
+ === "SuperCollider"
+
+ Copy/paste the code below into a new code document. Run the entire block to start. It will clean up when you close the GUI window.
+
+ ```
+ // OSC response part
+ (
+ var addr = NetAddr("127.0.0.1", 8080); // FROM address
+ var freqRange = ControlSpec(200.0, 800.0, \exp);
+ var button, slider;
+
+ OSCdef(\button, { |msg|
+ defer { button.value = msg[1] };
+ if(x.notNil) { x.set(\gate, msg[1]) };
+ }, '/button_1', addr);
+
+ OSCdef(\slider, { |msg|
+ defer { slider.value = msg[1] };
+ if(x.notNil) { x.set(\freq, freqRange.map(msg[1])) };
+ }, '/fader_1', addr);
+
+ w = Window("Open Stage Control", Rect(800, 200, 400, 100)).front;
+ w.layout = HLayout(
+ button = Button(),
+ slider = Slider().orientation_(\horizontal)
+ );
+ w.alwaysOnTop = true; // may not take effect in all window managers
+
+ button.states = [["off"], ["playing", Color.black, Color(0.7, 1, 0.7)]];
+ button.action = { |view|
+ if(x.notNil) { x.set(\gate, view.value) };
+ addr.sendMsg('/button_1', view.value);
+ };
+
+ slider.action = { |view|
+ if(x.notNil) { x.set(\freq, freqRange.map(view.value)) };
+ addr.sendMsg('/fader_1', view.value);
+ };
+
+ w.onClose = {
+ if(x.notNil) { x.free };
+ OSCdef(\button).free;
+ OSCdef(\slider).free;
+ };
+
+ // audio part
+ // if this fails (if you have an issue with audio devices),
+ // you won't hear anything but the onscreen GUIs
+ // will reflect changes from Open Stage Control
+ s.waitForBoot {
+ x = { |freq = 200, amp = 0.1, gate = 0|
+ var eg = EnvGen.kr(Env.asr(0.1, 1, 0.1), gate);
+ (SinOsc.ar(Lag.kr(freq, 0.1)) * amp * eg).dup
+ }.play;
+ };
+ )
+ ```
+
+## Deploying the interface
+
+The whole point of Open Stage Control is to make the interface available on other devices, especially mobile devices.
+
+The interface will not be visible to other clients, however, until you save it to disk: three-dots menu > Session > Save, and give the file a name such as `open-stage-demo` (you don't need to type the `.json` extension).
+
+Now -- remember those status messages in the launcher window? On another device (computer, phone or tablet), go to the `http://192.168.xxx.yyy:8080` address. The device should be on the same (W)LAN. (If there is another remote address, it may or may not work, depending on your network.) Supported browsers are Firefox v. 75 and higher, or Chromium/Chrome v. 60 and higher.
+
+This should open an empty client window, similar to the one you saw before.
+
+From here, you can open the session that you just saved: three-dots menu *in the webpage* > Session > Open Recent (yes, this is synced from the server!). This should display the controls created in that session, and the controls should function the same as in the other client window.
+
+And that is... it! Basic usage is as simple as that.
+
+For convenience, if there is a session you know that you will use often, and you don't want to load it in the webpage by hand every time, you can choose the file under "load" in the initial Launcher window. This is also useful for public deployments with audience participation, where you don't want audience members to have to load manually.
+
+When not using Open Stage Control, you can also stop the server from the launcher window (stop button, top-left).
diff --git a/resources/docs/docs/tutorials/first-steps/fader-style.png b/resources/docs/docs/tutorials/first-steps/fader-style.png
new file mode 100644
index 00000000..a09ecd9c
Binary files /dev/null and b/resources/docs/docs/tutorials/first-steps/fader-style.png differ
diff --git a/resources/docs/docs/tutorials/first-steps/horizontal-fader.png b/resources/docs/docs/tutorials/first-steps/horizontal-fader.png
new file mode 100644
index 00000000..82916a6d
Binary files /dev/null and b/resources/docs/docs/tutorials/first-steps/horizontal-fader.png differ
diff --git a/resources/docs/docs/tutorials/first-steps/resized-fader.png b/resources/docs/docs/tutorials/first-steps/resized-fader.png
new file mode 100644
index 00000000..e69acf21
Binary files /dev/null and b/resources/docs/docs/tutorials/first-steps/resized-fader.png differ
diff --git a/resources/docs/docs/tutorials/first-steps/two-widgets.png b/resources/docs/docs/tutorials/first-steps/two-widgets.png
new file mode 100644
index 00000000..62fa2a74
Binary files /dev/null and b/resources/docs/docs/tutorials/first-steps/two-widgets.png differ
diff --git a/resources/docs/docs/user-interface/client.md b/resources/docs/docs/user-interface/client.md
index 7c53bfab..2133c01f 100644
--- a/resources/docs/docs/user-interface/client.md
+++ b/resources/docs/docs/user-interface/client.md
@@ -7,6 +7,8 @@
- Open: browse session files on the server
- Open recent: open a recent session on the server
- Save / Save as: save session file on the server
+ - Fragment mode: when enabled, the session will be saved as a fragment file (only the root's first child will be saved)
+ - Save backup: save a copy of current session with a incremented suffix appended to the file name
- Import: import a session file from the client's filesystem
- Export: export a session file to the client's filesystem
- State
@@ -18,17 +20,22 @@
- Import: import a state file from the client's filesystem
- Export: export a state file to the client's filesystem
- Editor
- - Enable: togggle editor's state
+ - Enable: toggle editor's state
- Grid: toggle grid
- Project tree: toggle project tree's visibility
- Inspector: toggle inspector's visibility
- Relative units (%): when enabled, newly created widgets will have their position and size set in percents.
+- Console
+ - Enable: toggle console's state
+ - Clear console: remove logged messages from the console
+- Virtual keyboard: (desktop only) toggle virtual keyboard (displayed only when a text input is in focus, except for code editors in the inspector)
- Fullscreen: toggle fullscreen
+- Notifications: toggle visibility of notifications
- Prevent sleep (mobile only): attempt to prevent device from going to sleep when idle
## 2. Sidepanels
-The sidepanels are only visible when the editor is active, they can be resized and/or hidden. Both are describe in the [editor](./editor.md) section.
+The sidepanels are only visible when the editor is active, they can be resized and/or hidden. Both are described in the [editor](./editor.md) section.
## 3. Session
@@ -36,7 +43,7 @@ It is the main component, it contains all the widgets and takes all the availabl
## 4. Notifications
-Notifications appear in the lower right corner, they are usually used to convey server status informations.
+Notifications appear in the lower right corner, they are usually used to convey server status information and can be dismissed with a single click.
## 5. Modals
@@ -46,21 +53,43 @@ Modals are virtual popup windows that may contain various content: file browser,
## Keyboard shortcuts
-=== "Linux / Windows"
+=== "Linux"
| Shortcut | Description |
|---|---|
+ | ++ctrl+"Mousewheel"++ | change global zoom (pixel scaling) |
+ | ++ctrl+0++ | reset global zoom |
| ++ctrl+e++ | enable/disable editor |
+ | ++ctrl+k++ | show/hide console |
+ | ++ctrl+l++ | clear console |
| ++ctrl+s++ | save session |
| ++ctrl+shift+s++ | save session as... |
| ++ctrl+o++ | open a session file |
| ++ctrl+w++ | close client |
+=== "Windows"
+
+ | Shortcut | Description |
+ |---|---|
+ | ++ctrl+"Mousewheel"++ | change global zoom (pixel scaling) |
+ | ++ctrl+0++ | reset global zoom |
+ | ++ctrl+e++ | enable/disable editor |
+ | ++ctrl+k++ | show/hide console |
+ | ++ctrl+l++ | clear console |
+ | ++ctrl+s++ | save session |
+ | ++ctrl+shift+s++ | save session as... |
+ | ++ctrl+o++ | open a session file |
+ | ++alt+f4++ | close client |
+
=== "Mac"
| Shortcut | Description |
|---|---|
+ | ++cmd+"Mousewheel"++ | change global zoom (pixel scaling) |
+ | ++cmd+0++ | reset zoom |
| ++cmd+e++ | enable/disable editor |
+ | ++cmd+k++ | show/hide console |
+ | ++cmd+l++ | clear console |
| ++cmd+s++ | save session |
| ++cmd+shift+s++ | save session as... |
| ++cmd+o++ | open a session file |
diff --git a/resources/docs/docs/user-interface/editor.md b/resources/docs/docs/user-interface/editor.md
index 6a8a1584..bfa62544 100644
--- a/resources/docs/docs/user-interface/editor.md
+++ b/resources/docs/docs/user-interface/editor.md
@@ -1,6 +1,6 @@
## Widget selection
-Clicking on a widget, on a tab label or on an item in the project tree selects the widgets for edition:
+Clicking on a widget, on a tab label or on an item in the project tree selects the widgets for editing:
- All its editable properties are shown in the inspector panel
- The corresponding item in the project tree is highlighted
@@ -9,6 +9,7 @@ Clicking on a widget, on a tab label or on an item in the project tree selects t

+To interact with a widget directly without selecting it, either use the middle mouse button or hold ++shift+win++ (++shift+cmd++ on Mac).
## Menu
@@ -28,6 +29,7 @@ Right clicking on a widget displays a menu with the following actions
- `Clone` : create a clone widget targetting the copied widget
- `Add widget`: create a new widget in selected container
- `Add tab`: create a new tab in selected container
+- `Export`: export as fragment file
- `Delete`: delete selected tab or widget
@@ -36,13 +38,21 @@ Right clicking on a widget displays a menu with the following actions
Selected widget's properties are displayed and can be modified in the inspector. The [properties reference](../widgets/properties-reference.md) lists the available properties for each widget type.
- Property fields are all multiline (press `shift + enter` for new line).
-- Properties are written in JSON, with some flexibility brought by the [JSON5](https://github.com/json5/json5) format. For example, doubles quotes around object keys are not mandatory.
+- Properties are written in JSON, with some flexibility brought by the [JSON5](https://github.com/json5/json5) format. For example, double quotes around object keys are not mandatory.
- Clicking on a property name spawns a help modal window
+- Properties are divided into multiple categories that can be toggled with a click. ++alt+"Click"++ on a category closes the other categories before toggling selected category.
+Some properties (for example `onValue`) have a special code editor with syntax highlighting and many keyboard shortcuts (available by clicking on the "Help" button). In these properties, pressing `enter` will not submit pending changes but instead insert a new line at the cursor position (as you would expect in a regular editor). To submit pending changes, press ++ctrl+enter++ (or ++cmd+enter== on Mac) or click outside the editor.
+
+Widgets can be locked for edition by enabling their `lock` property. When locked, a widget can't be modified by the editor but it remains possible to delete it or to move it from a container to another in the project tree.
## Project tree
-The project tree displays the whole widget structure of the session. Widgets can be reordered within a container with drag-and-drop.
+The project tree displays the whole widget structure of the session. Widgets can be reordered or moved to another container with drag-and-drop.
+
+The "Filter" input allows filtering displayed widgets by their `id`. It's also possible to only display a single type of widget by typing `type:fader` for example.
+
+Invisible widgets are displayed with a lower opacity and their name in italic. Locked widgets are displayed with a lock icon after their name.
## Widget resizing / dragging
@@ -71,7 +81,7 @@ Multiple widgets can be edited at once.
| ++ctrl+i++ | Toggle inspector. |
| ++"Click"++ | Widget selection. |
| ++ctrl+"Click"++ | Multi-widget selection. Widgets can be toggled from selection by clicking on them individually.|
- | ++shift+"Click"+"Drag"++ | Draw a selection rectangle and attempt to select widgets in it (starts by selecting the widget under the cursor). If ++ctrl++ is pressed too, current selection is kept and will be merged with the new one if possible. |
+ | ++shift+"Click"+"Drag"++ | Draw a selection rectangle and attempt to select widgets in it. If ++ctrl++ is pressed too, current selection is kept and will be merged with the new one if possible. |
| ++ctrl+z++ | Undo |
| ++ctrl+y++ }}`
+This syntax creates a custom variable in the widget that can be read and modified from any widget's script property (see [scripting](./scripting.md#getvarid-name)). Changes made to this variable using `setVar()` in scripts will be applied automatically where `VAR{}` is used.`
-This syntax allows writing formulas in [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript). The code will be compiled as a function and executed in a restricted context.
+## File imports: `IMPORT{file_name}`
+
+This allows loading the content of an external file in a property. If used in a `JS{}` of `#{}` block, it will be seen as a string variable containing the raw content of the file. Changes made to the file be applied automatically.
+
+File paths are resolved in this order:
+
+- in the session's directory
+- in theme's directory
+- in the server's `remote-root` directory if the option is set
+- as absolute paths
+
+!!! warning
+ [Fragments](../fragments/) and session files already loaded with fragment widgets should not be imported using this syntax.
+
+## Javascript: `JS{ }`
+
+This syntax allows defining a property using [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript). The code will be compiled as a function and executed in a restricted context.
- if no `return` statement is found, the formula will return an empty string
- javascript [strict mode](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Strict_mode) is always enabled
- `setTimeout` and `setInterval` functions are not available
-A property *cannot* contain multiple `JS{{}}` blocks
+A property *cannot* contain multiple `JS{}` blocks
#### Available variables
- `console`: javascript console
- `locals`: object for storing/reading arbitrary values. Changing its properties *does not* trigger any synchronisation even if the value is used somewhere else.
- `globals`: same as `locals` but shared between all widgets, contains a few useful variables:
- - `screen`: client screen dimensions (`{width, height}`)
+ - `screen`: client screen informations (`{width, height, orientation}`)
- `env`: client options (ie: url query options),
- `ip`: client's ip address,
- `url`: server url,
- `platform`: operating system as seen by the client
-
-In this context, `@{} / OSC{}` are seen as variables, they are simply replaced as the value they hold. When they change, the whole block will be evaluated again.
+ - `session`: session file path
+ - `clipboard`: instance of navigator [Clipboard](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard)
Parsing errors can be read in the console (++ctrl+k++).
!!! warning
Modifying values in `locals` or `globals` **does not** trigger anything if they are used somewhere else.
+#### Using in advanced syntaxes
+
+In this context, `@{}`, `VAR{}` and `OSC{}` syntaxes are seen as variables. When they change, the whole block will be evaluated again.
+
+!!! danger "Do not mutate"
+ When these syntaxes return objects or arrays, mutating said objects will affect the underlying variables in memory and may lead to unexpected behavior.
+
+ The `@{}` syntax, when used for anything else than the widget's value, will always return a copy of the property and is not affected by this.
+
## Javascript: `#{ }`
-This is a shorthand for the `JS{{}}` syntax, the only difference being that `` is automatically prepended with a `return` statement.
+This is a shorthand for the `JS{}` syntax, the only difference being that `` is automatically prepended with a `return` statement.
A property *can* contain multiple `#{}` blocks.
!!! note "Compilation order"
- `#{}` blocks are compiled after `JS{{}}` blocks
+ `#{}` blocks are compiled after `JS{}` blocks
diff --git a/resources/docs/docs/widgets/canvas.md b/resources/docs/docs/widgets/canvas.md
new file mode 100644
index 00000000..dffea008
--- /dev/null
+++ b/resources/docs/docs/widgets/canvas.md
@@ -0,0 +1,195 @@
+# Canvas widget
+
+The canvas widget allows creating custom widgets with user-defined drawings and touch reactions.
+
+It has dedicated scripting properties (`onTouch`, `onDraw` and `onResize`) that work like the `onValue` property : they are used to defined scripts that will be executed when specific events occurs.
+
+This widget requires a good understanding of the javascript [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) and of the javascript programming language in general.
+
+## Canvas properties
+
+### `valueLength`
+
+This property must be set to the number of values held by the widget : 1 for a simple slider, 2 for an XY pad, etc. Attempts to set the widget's value with a different number of values will be ignored.
+
+```js
+set("this", 1) // works if valueLength == 1
+set("this", [1, 2]) // works if valueLength == 2
+```
+
+### `autoClear`
+
+This is a convenience option that clears the canvas context and calls [`beginPath`](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/beginPath) before each drawing. When this property is set to `false`, the canvas must be cleared manually.
+
+### `continuous`
+
+If this property is enabled, the widget will be redrawn at a fixed rate even if not interacted with (see [`onDraw`](#onDraw)).
+
+
+### `onTouch`
+
+This script is executed when the widget is touched, when it is released, and during the movement of the pointer while the widget is touched.
+
+This script has access to the same variables and functions as the `onValue` property (except the event-specific ones), plus the following:
+
+- `value`: widget value
+- `width`: canvas width in pixels
+- `height`: canvas height in pixels
+- `event`: object containing the following:
+ - `type`: `"start"`, `"move"` or `"stop"`
+ - `target`: id of the widget under the pointer, `"this"` if it's the canvas widget itself, `null` if no widget is under the pointer
+ - `targetName`: name attribute of the html element under the pointer
+ - `targetTagName`: tag name of the html element under the pointer
+ - `offsetX`, `offsetY`: touch coordinates in pixels, relative to the html element under the pointer
+ - `movementX`, `movementY`: movement of the pointer in pixels since the last event
+ - `pageX`, `pageY`: touch coordinates in pixels, relative to the page
+ - `pointerId`: unique identifier used to differentiate fingers in multitouch situation
+ - `altKey`, `ctrlKey`, `shiftKey`: keyboard modifier states
+ - `force`: amount of pressure applied to the touch surface between `0` and `1` (see [Touch.force](https://developer.mozilla.org/en-US/docs/Web/API/Touch/force)). Equals `0` if the API is not supported or if no pressure information is found.
+ - `radiusX`, `radiusY`, `rotationAngle`: see [Touch.rotationAngle](https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle)
+ - (iOS only) `altitudeAngle`, `azimuthAngle`: see [Touch.altitudeAngle](https://w3c.github.io/touch-events/#dom-touch-altitudeangle)
+ - (iOS only) `touchType`: "direct" or "stylus"
+
+
+!!! note "Extra html elements"
+ Elements added using the `html` property can be touched as well, `event.targetName` can be used to determine which element is touched.
+
+
+### `onDraw`
+
+This script is executed when the widget should be redrawn, which is when it's touched and when it receives a value.
+
+This script has access to the same variables and functions as the `onValue` property (except the event-specific ones), plus the following:
+
+- `value`: widget value
+- `width`: canvas width in pixels
+- `height`: canvas height in pixels
+- `ctx`: [canvas rendering context](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D) of the widget
+- `cssVars`: object containing the computed value of some of the widget's style properties such as `colorWidget`, `alphaFill`, `padding`, etc
+
+In this script, all osc messages emissions are prevented and changing the value of a widget won't trigger widget synchronisation / scripts / advanced syntaxes updates.
+
+### `onResize`
+
+This script is executed when the widget has resized, before it is redrawn.
+
+This script has access to the same variables and functions as the `onValue` property (except the event-specific ones), plus the following:
+
+- `value`: widget value
+- `width`: canvas width in pixels
+- `height`: canvas height in pixels
+- `cssVars`: object containing the computed value of some of the widget's style properties such as `colorWidget`, `alphaFill`, `padding`, etc
+
+## Example: XY pad
+
+Let's create a simple xy pad, with a value made of two numbers between 0 and 1. We set `valueLength` to `2` to make sure the widget only accepts incoming messages with two values (x and y).
+
+First, we use the `onTouch` property to store the touch coordinates in the `locals` object. We also call `set()` to store these in the widget's value (this way, the widget can send messages and sync with other widgets).
+
+```js
+// onTouch
+
+// store normalized coordinates
+if (event.type == "start") {
+ locals.x = event.offsetX / width
+ locals.y = event.offsetY / height
+} else {
+ // when the pointer is moving, increment coordinates
+ // because offsetX and offsetY may not be relevant
+ // if the pointer hovers a different widgets
+ locals.x += event.movementX / width
+ locals.y += event.movementY / height
+}
+
+// update widget value and send
+set("this", [locals.x, locals.y])
+```
+
+Then, we use the `onDraw` property to draw a circle at the touch coordinates.
+
+```js
+// onDraw
+
+// draw circle at touch coordinates
+ctx.arc(value[0] * width, value[1] * height, 6, 0, Math.PI * 2)
+// use colorFill property as stroke color
+ctx.strokeStyle = cssVars.colorFill
+// draw stroke
+ctx.stroke()
+```
+
+Finally, we use the `onValue` property to apply limits to the values.
+
+```js
+// onValue
+
+// apply limits
+var x = Math.max(0, Math.min(1, value[0])),
+ y = Math.max(0, Math.min(1, value[1]))
+
+// re-update widget value without retriggering script or sending message
+set("this", [x, y], {sync: false, send: false})
+
+// the widget will automatically send its value if
+// this script was triggered by a user interaction
+// no need to call send() here but we could, for example
+// if we want to split the value in to multiple messages
+```
+
+## Example: multi slider
+
+Let's build a row of 20-sliders with a single widget. We first set `valueLength` to... 20 !
+
+```js
+// onTouch
+
+// store normalized coordinates
+if (event.type == "start") {
+ locals.x = event.offsetX / width
+ locals.y = event.offsetY / height
+} else {
+ // when the pointer is moving, increment coordinates
+ // because offsetX and offsetY may not be relevant
+ // if the pointer hovers a different widgets
+ locals.x += event.movementX / width
+ locals.y += event.movementY / height
+}
+
+
+// which slider are we touching ?
+var n = parseInt(locals.x * value.length)
+n = Math.max(0, Math.min(n, value.length-1))
+
+// update value at slider's index
+// 1 - locals.y because y axis is from top to bottom in js canvas
+value[n] = 1 - locals.y
+
+// update widget value and send
+set("this", value)
+```
+
+```js
+// onDraw
+
+ctx.fillStyle = cssVars.colorFill
+ctx.globalAlpha = cssVars.alphaFillOn
+
+var sliderWidth = width / value.length - 1
+for (var i in value){
+ ctx.beginPath()
+ ctx.rect(i * width / value.length, height, sliderWidth, - value[i] * height)
+ ctx.fill()
+}
+```
+
+```js
+// onValue
+
+// apply limits
+for (var i in value) {
+ value[i] = Math.max(0, Math.min(1, value[i]))
+}
+
+// re-update widget value without retriggering script or sending message
+set("this", value, {sync: false, send: false})
+```
diff --git a/resources/docs/docs/widgets/fragments.md b/resources/docs/docs/widgets/fragments.md
new file mode 100644
index 00000000..69e3b473
--- /dev/null
+++ b/resources/docs/docs/widgets/fragments.md
@@ -0,0 +1,15 @@
+# Fragments
+
+Fragments allow breaking sessions into multiple files and reusable components made of multiple widgets.
+
+## Fragment files
+
+
+When right-clicking on a widget in the editor mode, it is possible to export it as a fragment file.
+
+Fragment files have the same extension as session files (`.json`) and can be opened like regular sessions. When doing so, keep in mind that only the first child of the root widget will be saved. It is possible to save a fragment file as a session file (and vice versa) by toggling the `Fragment mode` in the main menu.
+
+
+## Fragment widgets
+
+Fragment widgets work like clone widget except their source widget are loaded from fragment files or session files. When the sources files are modified, the fragment widgets are updated automatically.
diff --git a/resources/docs/docs/widgets/general-mechanics.md b/resources/docs/docs/widgets/general-mechanics.md
index febc9529..631bdd0b 100644
--- a/resources/docs/docs/widgets/general-mechanics.md
+++ b/resources/docs/docs/widgets/general-mechanics.md
@@ -58,3 +58,5 @@ From a client to another, widgets are automatically synchronized if they share t
- `address`
- `preArgs`
- `targets`
+
+Client synchronization can be disabled globally with the `clientSync` [client option](../client-options.md). Widgets with `bypass` set to `true` will not send synchronization messages to other clients.
diff --git a/resources/docs/docs/widgets/properties-reference.md b/resources/docs/docs/widgets/properties-reference.md
deleted file mode 100644
index 2762594b..00000000
--- a/resources/docs/docs/widgets/properties-reference.md
+++ /dev/null
@@ -1,792 +0,0 @@
-
-
-## Common
-
-??? api "Generic properties#"
- Properties shared by all widgets
-
-
-
-
-=== "widget"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | type#
| `string` | "auto" | Widget type |
- | id#
| `string` | "auto" | Widgets sharing the same `id` will act as clones and update each other's value(s) without sending extra osc messages. |
- | visible#
| `boolean` | true | Set to `false` to hide the widget. |
- | interaction#
| `boolean` | true | Set to `false` to disable pointer interactions. |
-
-
-=== "geometry"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | left#
| `number`|
`string` | "auto" | 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#
| `number`|
`percentage` | "auto" | 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#
| `number`|
`percentage` | "auto" | Widget width |
- | height#
| `number`|
`percentage` | "auto" | Widget height |
- | expand#
| `boolean`|
`number` | "false" | If parent's layout is `vertical` or `horizontal`, set this to `true` to stretch the widget to use available space automatically. |
-
-
-=== "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorText#
| `string` | "auto" | Text color. Set to "auto" to inherit from parent widget. |
- | colorWidget#
| `string` | "auto" | Widget's default accent color. Set to "auto" to inherit from parent widget. |
- | colorStroke#
| `string` | "auto" | Stroke color. Set to "auto" to use `colorWidget`. |
- | colorFill#
| `string` | "auto" | Fill color. Set to "auto" to use `colorWidget`. |
- | alphaStroke#
| `number` | "auto" | Stroke color opacity. |
- | alphaFillOff#
| `number` | "auto" | Fill color opacity (off). |
- | alphaFillOn#
| `number` | "auto" | Fill color opacity (on). |
- | lineWidth#
| `number` | "auto" | Stroke width. |
- | padding#
| `number` | "auto" | Inner spacing. |
- | html#
| `string` | "" | Custom html content to be inserted in the widget (before the widget's content).
The code is automatically wrapped in <div class="html"></div>
Allowed HTML tags:
h1-6, blockquote, p, a, ul, ol, nl, li,
b, i, strong, em, strike, code, hr, br, div,
table, thead, img, caption, tbody, tr, th, td, pre
Allowed attributes:
<*>: class, style, title
<img>: src, width, height |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke` |
-
-
-=== "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `*` | "" | Define the widget's value depending on other widget's values / properties using the advanced property syntax |
- | default#
| `*` | "" | If set, the widget will be initialized with this value when the session is loaded. |
- | linkId#
| `string`|
`array` | "" | 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) |
- | script#
| `script` | "" | Script executed whenever the widget's value updates. See documentation. |
-
-
-=== "osc"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | address#
| `string` | "auto" | OSC address for sending / receiving messages, it must start with a slash (`/`)
By default ("auto"), the widget's id is used: `/widget_id` |
- | preArgs#
| `*`|
`array` | "" | A value or array of values that will be prepended to the OSC messages. |
- | typeTags#
| `string` | "" | Defines the osc argument types, one letter per argument (including preArgs)
- If empty, the types are infered automatically from the values (with numbers casted to floats by default)
- If there are more arguments than type letters, the last type is used for the extra arguments
See http://opensoundcontrol.org/spec-1_0 for existing typetags |
- | decimals#
| `integer` | 2 | Defines the number of decimals to send. |
- | target#
| `string`|
`array`|
`null` | "" | This defines the targets of the widget's OSC messages
- A `string` or `array` of strings formatted as follow: `ip:port` or `["ip:portA", "ip:portB"]`
- If midi is enabled, targets can be `midi:device_name`
- If no target is set, messages can still be sent if the server has default targets |
- | ignoreDefaults#
| `boolean` | false | Set to `true` to ignore the server's default targets |
- | bypass#
| `boolean` | false | Set to `true` to prevent the widget from sending any osc message |
-## Basics
-
-??? api ""
- On / off button.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--color-text-on`: `colorTextOn` |
- | colorTextOn#
| `string` | "auto" | Defines the widget's text color when active. |
- | label#
| `string`|
`boolean` | "auto" | Set to `false` to hide completely
- Insert icons using the prefix ^ followed by the icon's name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)
- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal` |
- | vertical#
| `boolean` | false | Set to `true` to display the text vertically |
- | wrap#
| `boolean` | false | Set to `true` to wrap long lines automatically. |
-
- === "button"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | on#
| `*` | 1 | Set to `null` to send send no argument in the osc message |
- | off#
| `*` | 0 | Set to `null` to send send no argument in the osc message. Must be different from `on`. |
- | mode#
| `string` | "toggle" | Interraction mode:
- `toggle` (classic on/off switch)
- `push` (press & release)
- `tap` (no release)
Choices: `toggle`, `push`, `tap` |
- | doubleTap#
| `boolean` | false | Set to `true` to make the button require a double tap to be pushed instead of a single tap |
-
-??? api "switch#"
- Value selector button.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--color-text-on`: `colorTextOn` |
- | colorTextOn#
| `string` | "auto" | Defines the widget's text color when active. |
- | layout#
| `string` | "vertical" | Defines how items should be laid out
Choices: `vertical`, `horizontal`, `grid` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
-
- === "switch"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | values#
| `array`|
`object` | \{
"Value 1": 1,
"Value 2": 2
} | `Array` of possible values to switch between : `[1,2,3]`
`Object` of `"label":value` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won't be kept |
- | mode#
| `string` | "tap" | Interraction mode:
- `tap`: activates when the pointer is down but prevents further scrolling
- `slide`: same as `tap` but allows sliding between values
- `click`: activates upon click only and allows further scrolling
Choices: `tap`, `slide`, `click` |
-
-??? api "dropdown#"
- Native dropdown menu.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | label#
| `string`|
`boolean` | "auto" | Displayed text (defaults to current value). Keywords `%key` and `%value` will be replaced by the widget's selected key/value. |
- | icon#
| `boolean` | "true" | Set to `false` to hide the dropdown icon |
- | align#
| `string` | "center" | Set to `left` or `right` to change text alignment (otherwise center)
Choices: `center`, `left`, `right` |
-
- === "dropdown"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | values#
| `array`|
`object` | \{
"Value 1": 1,
"Value 2": 2
} | `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 |
-
-??? api ""
- Drag and drop menu with a circular or grid layout.
-
- === "geometry"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | size#
| `number`|
`array` | 200 | - If `layout` is `circular`: diameter (in px)
- Else: square size or `[width, height]` array |
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | label#
| `string`|
`boolean` | "auto" | Displayed text (defaults to current value). Keywords `%key` and `%value` will be replaced by the widget's selected key/value. |
- | icon#
| `boolean` | "true" | Set to `false` to hide the dropdown icon |
- | textAlign#
| `string` | "center" | Set to `left` or `right` to change text alignment (otherwise center)
Choices: `center`, `left`, `right` |
- | menuAlignV#
| `string` | "center" | Set to `top` or `bottom` to change menu alignment (otherwise center)
Choices: `center`, `top`, `bottom` |
- | menuAlignH#
| `string` | "center" | Set to `left` or `right` to change menu alignment (otherwise center)
Choices: `center`, `left`, `right` |
- | layout#
| `string` | "circular" | Defines whether the menu's layout should be rendered in a circle or in a box
Choices: `circular`, `horizontal`, `vertical`, `grid` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
-
- === "menu"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | toggle#
| `boolean` | false | Set to `true` to make the menu stay opened after mouse/touch release |
- | doubleTap#
| `boolean` | false | Set to `true` to make the menu require a double tap to be opened instead of a single tap |
- | values#
| `array`|
`object` | [
1,
2,
3
] | `Array` of possible values to switch between : `[1,2,3]`
`Object` of label:value pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won't be kept |
- | weights#
| `array` | "" | `Array` of `number` defining the weights of each value in `values`
Ignored when `mode` is `grid` |
-
-??? api "input#"
- Text input.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | align#
| `string` | "center" | Set to `left` or `right` to change text alignment (otherwise center)
Choices: `center`, `left`, `right` |
- | unit#
| `string` | "" | Unit will be appended to the displayed widget's value (it doesn't affect osc messages) |
-
- === "input"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | asYouType#
| `boolean` | false | Set to `true` to make the input send its value at each keystroke |
- | validation#
| `string` | "" | Regular expression: if the submitted value doesn't match the regular expression, it will be reset to the last valid value.
If leading and trailing slashes are omitted, they will be added automatically and the flag will be set to "gm"
Examples:
- `^[0-9]*$` accepts digits only, any number of them
- `/^[a-zs]{0,10}$/i` accept between 0 and 10 alphabetic characters and spaces (case insensitive) |
-
-??? api "file#"
- File/Folder selector (server-side).
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | align#
| `string` | "center" | Set to `left` or `right` to change text alignment (otherwise center)
Choices: `center`, `left`, `right` |
- | hidePath#
| `boolean` | false | Set to `true` to only display the filename (the whole path will still be used as value) |
-
- === "file"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | directory#
| `string` | "auto" | Default browsing directory |
- | extension#
| `string` | "*" | Only display files with this extension |
- | allowDir#
| `boolean` | false | Allow selecting a folder (by pressing "open" when no file is selected) |
-## Containers
-
-??? api "panel#"
- Widgets or Tabs container.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorBg#
| `string` | "auto" | Panel background color. Set to "auto" to inherit from parent widget. |
- | layout#
| `string` | "default" | Defines how children are laid out.
Choices: `default`, `vertical`, `horizontal`, `grid` |
- | justify#
| `string` | "start" | If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.
Choices: `start`, `end`, `center`, `space-around`, `space-between` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
- | contain#
| `boolean` | true | If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel. |
- | scroll#
| `boolean` | true | Set to `false` to disable scrollbars |
- | innerPadding#
| `boolean` | true | Set to `false` to make the `padding` property apply only between children and not at the container's inner boundaries. |
- | verticalTabs#
| `boolean` | false | Set to `true` to display for vertical tab layout |
-
- === "panel"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | variables#
| `*` | "@\{parent.variables}" | Defines one or more arbitrary variables that can be inherited by children widgets |
- | traversing#
| `boolean` | false | 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 |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `integer` | "" | Defines currently selected tab in the widget
A tab can be opened only by setting its parent's value |
-
- === "children"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgets#
| `array` | [] | Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously. |
- | tabs#
| `array` | [] | Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously |
-
-??? api "modal#"
- A toggle button that opens a popup panel. Cannot contain tabs directly.
-
- === "geometry"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | popupWidth#
| `number`|
`percentage` | "80%" | Modal popup's size |
- | popupHeight#
| `number`|
`percentage` | "80%" | Modal popup's size |
- | popupLeft#
| `number`|
`percentage` | "auto" | Modal popup's position |
- | popupTop#
| `number`|
`percentage` | "auto" | Modal popup's position |
- | relative#
| `boolean` | false | Set to `true` to make the modal's position relative to the button's position. |
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorBg#
| `string` | "auto" | Panel background color. Set to "auto" to inherit from parent widget. |
- | layout#
| `string` | "default" | Defines how children are laid out.
Choices: `default`, `vertical`, `horizontal`, `grid` |
- | justify#
| `string` | "start" | If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.
Choices: `start`, `end`, `center`, `space-around`, `space-between` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
- | contain#
| `boolean` | true | If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel. |
- | scroll#
| `boolean` | true | Set to `false` to disable scrollbars |
- | innerPadding#
| `boolean` | true | Set to `false` to make the `padding` property apply only between children and not at the container's inner boundaries. |
- | label#
| `string`|
`boolean` | "auto" | Set to `false` to hide completely
- Insert icons using the prefix ^ followed by the icon's name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)
- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal` |
- | popupLabel#
| `string`|
`boolean` | "auto" | Alternative label for the modal popup |
- | popupPadding#
| `number` | "auto" | Modal's inner spacing. |
-
- === "modal"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | variables#
| `*` | "@\{parent.variables}" | Defines one or more arbitrary variables that can be inherited by children widgets |
- | traversing#
| `boolean` | false | 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 |
- | doubleTap#
| `boolean` | false | Set to `true` to make the modal require a double tap to open instead of a single tap |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `integer` | "" | Defines the modal's state:`0` for closed, `1` for opened |
-
- === "children"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgets#
| `array` | [] | Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously. |
- | tabs#
| `array` | [] | Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously |
-
-??? api "clone#"
- Widget replication with overridable properties.
-
- === "clone"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgetId#
| `string` | "" | `id` of the widget to clone |
- | props#
| `object` | \{} | Cloned widget's properties to override |
-
-??? api "matrix#"
- Generic matrix for creating rows/columns of widgets.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorBg#
| `string` | "auto" | Panel background color. Set to "auto" to inherit from parent widget. |
- | layout#
| `string` | "horizontal" | Defines how children are laid out.
Choices: `horizontal`, `vertical`, `grid` |
- | justify#
| `string` | "start" | If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.
Choices: `start`, `end`, `center`, `space-around`, `space-between` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
- | contain#
| `boolean` | true | If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel. |
- | scroll#
| `boolean` | true | Set to `false` to disable scrollbars |
- | innerPadding#
| `boolean` | true | Set to `false` to make the `padding` property apply only between children and not at the container's inner boundaries. |
-
- === "matrix"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | variables#
| `*` | "@\{parent.variables}" | Defines one or more arbitrary variables that can be inherited by children widgets |
- | traversing#
| `boolean` | false | 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 |
- | widgetType#
| `string` | "button" | Defines the type of the widgets in the matrix |
- | quantity#
| `number` | 4 | Defines the number of widgets in the matrix |
- | start#
| `integer` | 0 | First widget's index |
- | props#
| `object` | \{} | Defines a set of property to override the widgets' defaults.
JS{{}} and #{} blocks in this field are resolved with an extra variable representing each widget's index: `$` (e.g. `#{$}`)
Note: by default, the widgets inherit from the matrix' `id` and osc properties (`id` and `address` are appended with `/$`) |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `integer` | "" | Defines currently selected tab in the widget
A tab can be opened only by setting its parent's value |
-
- === "children"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgets#
| `array` | [] | Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously. |
- | tabs#
| `array` | [] | Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously |
-
-??? api "keyboard#"
- Piano keyboard.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorWhite#
| `string` | "auto" | White keys color. |
- | colorBlack#
| `string` | "auto" | Black keys color. |
-
- === "keyboard"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | keys#
| `number` | 25 | Defines the number keys |
- | start#
| `number` | 48 | MIDI note number to start with (default is C4)
Standard keyboards settings are: `[25, 48]`, `[49, 36]`, `[61, 36]`, `[88, 21]` |
- | traversing#
| `boolean` | true | Set to `false` to disable traversing gestures |
- | on#
| `*` | 1 | Set to `null` to send send no argument in the osc message |
- | off#
| `*` | 0 | Set to `null` to send send no argument in the osc message |
- | velocity#
| `boolean` | false | Set to `true` to map the touch coordinates between `off` (top) and `on` (bottom). Requires `on` and `off` to be numbers |
- | mode#
| `string` | "push" | Interraction mode:
- `push` (press & release)
- `toggle` (on/off switches)
- `tap` (no release)
Choices: `push`, `toggle`, `tap` |
-
-??? api "patchbay#"
- Connect inputs to outputs.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | The inputs/ouputs width can be adjusted by using the `.nodes` selector:
`.nodes { width: 25% }` |
-
- === "patchbay"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | inputs#
| `array`|
`object` | [
"input_1",
"input_2"
] | - `Array` of input names : `['input_1', 'input_2']`
- `Object` of `"label_1": "input_1"` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won't be kept
Patchbay inputs can be connected to one or more outputs and will send messages of the following form when they are connected/disconnected:
`/patchbay_address input_x output_x output_y etc`
If no output is connected to the input, the message will be `/patchbay_address input_x`
The inputs values can be consumed with the property inheritance syntax: `@{patchbay_id/input_1}` returns an array of output names connected to `input_1` |
- | outputs#
| `array`|
`object` | [
"output_1",
"output_2"
] | List of output values the inputs can connect to (see `inputs`). |
-
-??? api "root#"
- Main (unique) container
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorBg#
| `string` | "auto" | Panel background color. Set to "auto" to inherit from parent widget. |
- | layout#
| `string` | "default" | Defines how children are laid out.
Choices: `default`, `vertical`, `horizontal`, `grid` |
- | justify#
| `string` | "start" | If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.
Choices: `start`, `end`, `center`, `space-around`, `space-between` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
- | contain#
| `boolean` | true | If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel. |
- | scroll#
| `boolean` | true | Set to `false` to disable scrollbars |
- | innerPadding#
| `boolean` | true | Set to `false` to make the `padding` property apply only between children and not at the container's inner boundaries. |
- | verticalTabs#
| `boolean` | false | Set to `true` to display for vertical tab layout |
-
- === "root"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | variables#
| `*` | "@\{parent.variables}" | Defines one or more arbitrary variables that can be inherited by children widgets |
- | traversing#
| `boolean` | false | 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 |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `integer` | "" | Defines currently selected tab in the widget
A tab can be opened only by setting its parent's value |
-
- === "children"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgets#
| `array` | [] | Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously. |
- | tabs#
| `array` | [] | Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously |
-
-??? api "tab#"
- Tabbed panel widget
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | colorBg#
| `string` | "auto" | Panel background color. Set to "auto" to inherit from parent widget. |
- | layout#
| `string` | "default" | Defines how children are laid out.
Choices: `default`, `vertical`, `horizontal`, `grid` |
- | justify#
| `string` | "start" | If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.
Choices: `start`, `end`, `center`, `space-around`, `space-between` |
- | gridTemplate#
| `string`|
`number` | "" | If `layout` is `grid`, can be either a number of columns of a value css grid-template definition. |
- | contain#
| `boolean` | true | If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel. |
- | scroll#
| `boolean` | true | Set to `false` to disable scrollbars |
- | innerPadding#
| `boolean` | true | Set to `false` to make the `padding` property apply only between children and not at the container's inner boundaries. |
- | verticalTabs#
| `boolean` | false | Set to `true` to display for vertical tab layout |
- | label#
| `string`|
`boolean` | "auto" | Set to `false` to hide completely
- Insert icons using the prefix ^ followed by the icon's name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)
- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal` |
-
- === "tab"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | variables#
| `*` | "@\{parent.variables}" | Defines one or more arbitrary variables that can be inherited by children widgets |
- | traversing#
| `boolean` | false | 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 |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `integer` | "" | Defines currently selected tab in the widget
A tab can be opened only by setting its parent's value |
-
- === "children"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | widgets#
| `array` | [] | Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously. |
- | tabs#
| `array` | [] | Each element of the array must be a tab object. A panel cannot contain widgets and tabs simultaneously |
-## Frames
-
-??? api "frame#"
- Embed a page in a frame (local network only).
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `string` | "" | External web page URL. |
-
-??? api "svg#"
- Svg parser.
-
- === "svg"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | svg#
| `string` | "" | Svg xml definition (will be wrapped in a `< svg />` element) |
-
-??? api "html#"
- Simple HTML parser.
-
-??? api "image#"
- Load a image (url or base64-encoded).
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | size#
| `string` | "cover" | CSS background-size |
- | position#
| `string` | "center" | CSS background-position |
- | repeat#
| `string` | "no-repeat" | CSS background-repeat |
-
- === "image"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | cache#
| `boolean` | true | 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 |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `string` | "" | - File `url` or `path` (relative to the session file location by default, falling back to absolute path)
- Base64 encoded image : `data:image/...` |
-## Graphs
-
-??? api "plot#"
- XY coordinates plot.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | dots#
| `boolean` | false | Draw dots on the line |
- | bars#
| `boolean` | false | Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing) |
- | pips#
| `boolean` | true | Set to `false` to hide the scale |
-
- === "plot"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | filters#
| `array` | "" | Each item must be an object with the following properties
- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak", "bandpass" or "notch", default: "peak")
- `freq`: number (filter's resonant frequency, default: 1000)
- `q`: number (Q factor, default: 1)
- `gain`: number (default: 0)
- `on`: boolean (default: true)
See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode |
- | pips#
| `boolean` | true | Set to false to hide the scale |
- | rangeX#
| `object` | \{
"min": 20,
"max": 22000
} | Defines the min and max values for the x axis (in Hz, logarithmic scale) |
- | rangeY#
| `object` | \{
"min": -6,
"max": 6
} | Defines the min and max values for the y axis (in dB) |
- | origin#
| `number`|
`boolean` | "auto" | Defines the y axis origin. Set to `false` to disable it |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `array`|
`string` | "" | - `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 |
-
-??? api "eq#"
- Draws logarithmic frequency response from an array of filter objects.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | dots#
| `boolean` | false | Draw dots on the line |
- | bars#
| `boolean` | false | Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing) |
- | pips#
| `boolean` | true | Set to `false` to hide the scale |
-
- === "eq"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | filters#
| `array` | "" | Each item must be an object with the following properties
- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak", "bandpass" or "notch", default: "peak")
- `freq`: number (filter's resonant frequency, default: 1000)
- `q`: number (Q factor, default: 1)
- `gain`: number (default: 0)
- `on`: boolean (default: true)
See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode |
- | pips#
| `boolean` | true | Set to false to hide the scale |
- | rangeX#
| `object` | \{
"min": 20,
"max": 22000
} | Defines the min and max values for the x axis (in Hz, logarithmic scale) |
- | rangeY#
| `object` | \{
"min": -6,
"max": 6
} | Defines the min and max values for the y axis (in dB) |
- | origin#
| `number`|
`boolean` | "auto" | Defines the y axis origin. Set to `false` to disable it |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `array`|
`string` | "" | - `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 |
-
-??? api "visualizer#"
- Display its value over time.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | dots#
| `boolean` | false | Draw dots on the line |
- | bars#
| `boolean` | false | Set to `true` to use draw bars instead (disables `logScaleX` and forces `x axis` even spacing) |
- | pips#
| `boolean` | true | Set to `false` to hide the scale |
-
- === "visualizer"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | filters#
| `array` | "" | Each item must be an object with the following properties
- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak", "bandpass" or "notch", default: "peak")
- `freq`: number (filter's resonant frequency, default: 1000)
- `q`: number (Q factor, default: 1)
- `gain`: number (default: 0)
- `on`: boolean (default: true)
See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode |
- | pips#
| `boolean` | true | Set to false to hide the scale |
- | rangeX#
| `object` | \{
"min": 20,
"max": 22000
} | Defines the min and max values for the x axis (in Hz, logarithmic scale) |
- | rangeY#
| `object` | \{
"min": 0,
"max": 1
} | Defines the min and max values for the y axis |
- | origin#
| `number` | "auto" | Defines the y axis origin. Set to `false` to disable it |
- | duration#
| `number` | 1 | Defines visualization duration in seconds |
- | framerate#
| `number` | 30 | Defines visualization framerate |
- | logScaleY#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale for the y axis (base 10). Set to a `number` to define the logarithm's base. |
- | freeze#
| `boolean` | false | Set to `true` to freeze current view and ignore incoming values |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `array`|
`string` | "" | - `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 |
-## Indicators
-
-??? api "led#"
- Intensity display.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | borderRadius#
| `string` | "" | Css border-radius property. |
-
- === "led"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | mode#
| `string` | "intensity" | Defines how value is interpreted (see `value`)
Choices: `intensity`, `color` |
- | range#
| `object` | \{
"min": 0,
"max": 1
} | Value range |
- | alphaRange#
| `object` | \{
"min": 0,
"max": 1
} | Alpha range (if `mode` is `color`) |
- | logScale#
| `boolean` | false | If `mode` is `intensity`, set to `true` to use logarithmic scale. |
-
- === "value"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | value#
| `number`|
`array`|
`string` | "" | If `mode` is `intensity`:
- `Number`: `intensity` between `range.min` and `range.max`
If `mode` is `color`:
- `Array`: `[r, g, b]` (`r`, `g` and `b` between `range.min` and `range.max`)
- `Array`: `[r, g, b, alpha]` (`alpha` between `alphaRange.min` and `alphaRange.max`)
- `String`: CSS color |
-
-??? api "text#"
- Display text.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | vertical#
| `boolean` | false | Set to `true` to display the text vertically |
- | wrap#
| `boolean` | false | Set to `true` to wrap long lines automatically. |
- | align#
| `string` | "center" | Css text-align property.
Choices: `center`, `left`, `right` |
-## Pads
-
-??? api "xy#"
- Two-dimensional slider.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | pointSize#
| `integer` | 20 | Defines the points' size |
- | ephemeral#
| `boolean` | false | When set to `true`, the point will be drawn only while touched. |
- | pips#
| `boolean` | true | Set to `false` to hide the scale |
-
- === "xy"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | snap#
| `boolean` | false | 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#
| `boolean` | false | When set to `true`, the widget will go back to its default value when released |
- | rangeX#
| `object` | \{
"min": 0,
"max": 1
} | Defines the min and max values for the x axis |
- | rangeY#
| `object` | \{
"min": 0,
"max": 1
} | Defines the min and max values for the y axis |
- | logScaleX#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale. |
- | logScaleY#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale. |
- | doubleTap#
| `boolean`|
`string` | false | 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: `/ ` |
- | sensitivity#
| `number` | 1 | Defines the pad's sensitivity when `snap` is `false` |
-
-??? api "rgb#"
- Color picker with optional alpha slider.
-
- === "rgb"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | snap#
| `boolean` | false | 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#
| `boolean` | false | When set to `true`, the widget will go back to its default value when released |
- | range#
| `object` | \{
"min": 0,
"max": 255
} | Defines the widget's output scale. |
- | alpha#
| `boolean` | false | Set to `true` to enable alpha channel |
- | rangeAlpha#
| `object` | \{
"min": 0,
"max": 1
} | Defines the widget's output scale for the alpha channel. |
-
-??? api "multixy#"
- Multi-point XY pad.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | pointSize#
| `integer` | 20 | Defines the points' size |
- | ephemeral#
| `boolean` | false | When set to `true`, the points will be drawn only chile touched. |
- | pips#
| `boolean` | true | Set to `false` to hide the scale |
-
- === "multixy"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | points#
| `integer`|
`array` | 2 | 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']`) |
- | snap#
| `boolean` | false | 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#
| `boolean` | false | When set to `true`, the widget will go back to its default value when released |
- | rangeX#
| `object` | \{
"min": 0,
"max": 1
} | Defines the min and max values for the x axis |
- | rangeY#
| `object` | \{
"min": 0,
"max": 1
} | Defines the min and max values for the y axis |
- | logScaleX#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale. |
- | logScaleY#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale. |
- | sensitivity#
| `number` | 1 | Defines the pad's sensitivity when `snap` is `false` |
-## Sliders
-
-??? api "fader#"
- Vertical / horizontal slider.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--alpha-pips`: `alphaPips`
- `--alpha-pips-text`: `alphaPipsText`
- `--knob-size`: `knobSize` |
- | design#
| `string` | "default" | Design style
Choices: `default`, `round`, `compact` |
- | knobSize#
| `number` | "auto" | Fader knob size |
- | horizontal#
| `boolean` | false | Set to `true` to display the fader horizontally |
- | pips#
| `boolean` | false | Set to `true` to show range breakpoints (ignored if `design` is `compact`) |
- | dashed#
| `boolean`|
`array` | false | Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]` |
- | gradient#
| `array`|
`object` | [] | When set, the meter's gauge will be filled with a linear color gradient
- each item must be a CSS color string.
- as an `object`: each key must be a number between 0 and 1
- each item must be a CSS color string.
Examples: `['blue', 'red']`, {'0': 'blue', '0.9': 'blue', '1': 'red'} |
-
- === "fader"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | snap#
| `boolean` | false | 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#
| `boolean` | false | When set to `true`, the widget will go back to its `default` value when released |
- | doubleTap#
| `boolean` | false | Set to `true` to make the fader reset to its `default` value when receiving a double tap.
Can also be an osc address, in which case the widget will just send an osc message (`/ `) |
- | range#
| `object` | \{
"min": 0,
"max": 1
} | 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#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale. Set to `-1` for exponential scale. |
- | sensitivity#
| `number` | 1 | Defines the fader's sensitivity when `snap` is `false` |
- | steps#
| `string`|
`number`|
`array` | "" | Restricts the widget's value:
- `auto`: use values defined in `range`
- `number`: define a number of evenly spaced steps
- `array`: use arbitrary values |
- | origin#
| `number` | "auto" | Defines the starting point's value of the fader's gauge |
-
-??? api "knob#"
- Rotative knob slider.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--alpha-pips`: `alphaPips`
- `--alpha-pips-text`: `alphaPipsText` |
- | design#
| `string` | "default" | Design style
Note: "solid" design uses "colorStroke" for the central knob color.
Choices: `default`, `solid`, `line` |
- | pips#
| `boolean` | false | Set to `true` to show the scale's breakpoints |
- | dashed#
| `boolean`|
`array` | false | Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]` |
- | angle#
| `number` | 270 | Defines the angle's width of the knob, in degrees |
-
- === "knob"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | mode#
| `string` | "vertical" | - `circular`: relative move in circular motion
- `snap`: snap to touch position and move in vertical motion
- `vertical`: relative move in vertical motion
Choices: `vertical`, `circular`, `snap` |
- | spring#
| `boolean` | false | When set to `true`, the widget will go back to its `default` value when released |
- | doubleTap#
| `boolean` | false | 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 (`/ `) |
- | range#
| `object` | \{
"min": 0,
"max": 1
} | 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#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale. Set to `-1` for exponential scale. |
- | sensitivity#
| `number` | 1 | Defines the knob's sensitivity when `mode` is not `snap` |
- | steps#
| `string`|
`number`|
`array` | "" | Restricts the widget's value:
- `auto`: use values defined in `range`
- `number`: define a number of evenly spaced steps
- `array`: use arbitrary values |
- | origin#
| `number` | "auto" | Defines the starting point's value of the knob's gauge |
-
-??? api "encoder#"
- A knob that sends a relative direction infomation instead of an absolute value.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--alpha-pips`: `alphaPips`
- `--alpha-pips-text`: `alphaPipsText` |
-
- === "encoder"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | mode#
| `string` | "circular" | - `circular`: relative move in circular motion
- `snap`: snap to touch position and move in vertical motion
- `vertical`: relative move in vertical motion
Choices: `circular`, `snap`, `vertical` |
- | spring#
| `boolean` | false | When set to `true`, the widget will go back to its `default` value when released |
- | doubleTap#
| `boolean` | false | Set to `true` to make the fader reset to its `default` value when receiving a double tap.
Can also be an osc address, in which case the widget will just send an osc message (`/ `) |
- | range#
| `object` | \{
"min": 0,
"max": 1
} | 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#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale. Set to `-1` for exponential scale. |
- | sensitivity#
| `number` | 1 | When set between 0 and 1, reduces the encoder's verbosity |
- | ticks#
| `number` | "" | Defines the granularity / verbosity of the encoder (number of step for a 360° arc) |
- | back#
| `*` | -1 | Defines which value is sent when rotating the encoder anticlockwise |
- | forth#
| `*` | 1 | Defines which value is sent when rotating the encoder clockwise |
- | release#
| `number` | "" | 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 |
-
-??? api "range#"
- A fader with two heads for setting a range.
-
- === "style"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | css#
| `string` | "" | CSS rules. See documentation.
Available css variables:
- `--color-background`: `colorBg`
- `--color-widget`: `colorWidget`
- `--color-fill`: `colorFill`
- `--color-stroke`: `colorStroke`
- `--color-text`: `colorText`
- `--widget-padding`: `padding`
- `--line-width`: `lineWidth`
- `--alpha-fill-on`: `alphaFillOn`
- `--alpha-fill-off`: `alphaFillOff`
- `--alpha-stroke`: `alphaStroke`
- `--alpha-pips`: `alphaPips`
- `--alpha-pips-text`: `alphaPipsText`
- `--knob-size`: `knobSize` |
- | design#
| `string` | "default" | Design style
Choices: `default`, `round`, `compact` |
- | knobSize#
| `number` | "auto" | Fader knob size |
- | horizontal#
| `boolean` | false | Set to `true` to display the fader horizontally |
- | pips#
| `boolean` | false | Set to `true` to show range breakpoints (ignored if `design` is `compact`) |
- | dashed#
| `boolean`|
`array` | false | Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]` |
- | gradient#
| `array`|
`object` | [] | When set, the meter's gauge will be filled with a linear color gradient
- each item must be a CSS color string.
- as an `object`: each key must be a number between 0 and 1
- each item must be a CSS color string.
Examples: `['blue', 'red']`, {'0': 'blue', '0.9': 'blue', '1': 'red'} |
-
- === "range"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | snap#
| `boolean` | false | 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#
| `boolean` | false | When set to `true`, the widget will go back to its `default` value when released |
- | doubleTap#
| `boolean` | false | Set to `true` to make the fader reset to its `default` value when receiving a double tap.
Can also be an osc address, in which case the widget will just send an osc message (`/ `) |
- | range#
| `object` | \{
"min": 0,
"max": 1
} | 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#
| `boolean`|
`number` | false | Set to `true` to use logarithmic scale. Set to `-1` for exponential scale. |
- | sensitivity#
| `number` | 1 | Defines the fader's sensitivity when `snap` is `false` |
- | steps#
| `string`|
`number`|
`array` | "" | Restricts the widget's value:
- `auto`: use values defined in `range`
- `number`: define a number of evenly spaced steps
- `array`: use arbitrary values |
- | origin#
| `number` | "auto" | Defines the starting point's value of the fader's gauge |
-## Scripts
-
-??? api "script#"
- Evaluates a script each time it receives a value.
-
- === "script"
-
- | property | type |default | description |
- | --- | --- | --- | --- |
- | event#
| `string` | "value" | Define which events trigger the script's execution.
Choices: `value`, `keyboard` |
- | script#
| `script` | "" | Script executed whenever the widget's receives the defined event. See documentation. |
- | keyBinding#
| `string`|
`array` | "" | Key combo `string` or `array` of strings (see KeyboardJS documentation) |
- | keyRepeat#
| `boolean` | true | Set to `false` to prevent keydown repeats when holding the key combo pressed |
- | keyType#
| `string` | "keydown" | Determines which key event trigger the script's execution
Choices: `keydown`, `keyup`, `both` |
-
-??? api "variable#"
- Receives / stores a value, to be used in scripts (using the get function) or in properties (using the @{} syntax).
diff --git a/resources/docs/docs/widgets/scripting.md b/resources/docs/docs/widgets/scripting.md
index 9f0a3a75..c02e975c 100644
--- a/resources/docs/docs/widgets/scripting.md
+++ b/resources/docs/docs/widgets/scripting.md
@@ -1,19 +1,37 @@
# Scripting
-The `script` property allows widgets to run [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) code when their value update.
+Widgets can run [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) scripts upon specific events. These scripts are written in special properties under the scripting category.
-!!! info "It's slightly different from the [javascript property syntax ](../advanced-syntaxes/#javascript-js-code)"
+!!! warning "Advanced syntaxes"
+ Most [advanced syntaxes](../advanced-syntaxes/) should be avoided as much as possible in scripting properties:
- - no `JS{{}}` wrapper, just the code
- - `@{}`, `OSC{}`, `JS{{}}` and `#{}` blocks are replaced with their literal value before the script's compilation, therefore **it is recommended to avoid these syntaxes** and use `getProp()` and `get()` instead.
+ - `@{}`: use `get()` and `getProp()` instead
+ - `OSC{}`: use `get()` instead (using another widget as receiver)
+ - `VAR{}`: use `getVar()`instead
+ - `JS{}` and `#{}` are useless (scripting properties are already interpreted as javascript code) unless you want to generate code procedurally
-## Event-dependent variables
+ The editor will always fail to recognize these syntaxes as they don't comply with the javacript language specification, even if the resulting code is valid.
-Depending on what triggered the script's execution, a few variables are available to help determine the execution conditions.
+## Events
-**Event: value**
+### `onCreate`
-- `id` (`string`): id of the widget that's reponsible for the value update
+This script is called when the widget is created. If the widget has children, it will be executed after the children are created.
+
+!!! warning "Modifying parent container"
+ Modifying a non-dynamic property on a parent container from this script **will not work**.
+
+The following variables are available in this context:
+
+- `value`: widget's value
+
+### `onValue`
+
+This script is called when the widget's value updates and when it receives a value.
+
+The following variables are available in this context:
+
+- `id` (`string`): id of the widget that's responsible for the value update
- `value`: widget's value
- `touch`: see [Touch state](#touch-state)
@@ -24,7 +42,73 @@ Depending on what triggered the script's execution, a few variables are availabl
value[getIndex(id)]
```
-**Event: keyboard** (script widget only)
+??? infos "Touch state (deprecated)"
+
+ *This feature is deprecated, use `onTouch` instead*
+
+ When some widgets are touched or released, a special value event can be caught to trigger custom actions.
+
+ If the variable `touch` is not `undefined`, this means it holds the widget's current touch state:
+
+ - `0/1` for the widget's touch state (`fader`, `knob` and `xy`, `range` and `multixy`)
+ - `[i, 0/1]` if the widget is multi touch (`range` and `multixy`). In this case `i` is the touched handle's index, starting with `0`.
+
+ ```js
+ if (touch !== undefined) {
+ // send multi touch state
+ if (touch.length) send('/touch_address', touch[0], touch[1])
+ // send global touch state
+ else send('/touch_address', touch)
+ } else {
+ // do something with the value ?
+ }
+ ```
+
+ To avoid unwanted script executions, touch state events will only be caught if the script contains the word `touch` and if `onTouch` is empty.
+
+
+### `onTouch`
+
+This script is executed when the widget is touched, and when it is released.
+
+This script has access to the same variables and functions as the `script` property (except the event-specific ones), plus the following:
+
+- `value`: widget value
+- `event`: object containing the following:
+ - `type`: `"start"` or `"stop"`
+ - `handle`: `undefined` if the event concerns the widget, `integer` if it concerns one of it's handles (`multixy` and `range` widgets only)
+
+[Canvas](../canvas/) and containers expose more informations in their `onTouch` script.
+
+??? infos "Containers onTouch"
+
+ Containers (root, panel, etc) can monitor touch events happening inside them, it works like with [Canvas](../canvas/#ontouch), with a few differences:
+
+ - `event.firstTarget` will return the id of the first touched widget
+ - setting `event.preventDefault` to `true` will prevent the event from reaching widgets in the container ('start' and 'move' events only)
+ - setting `event.allowScroll` to `true` will allow touch scrolling where it would normally be prevented ('start' event only)
+ - setting `event.inertia` will affect 'move' events (works like widget `sensitivity` in reverse (1 = normal, 10 = slow move))
+ - `width` and `height` are undefined
+
+ Containers with `traversing` enabled change how touch events are emitted:
+
+ - a new 'stop' event is emitted whenever the pointer exits a touchable widget while pressed.
+ - a new 'start' event is emitted whenever the pointer enters a touchable widget while pressed.
+
+
+### `onDraw`
+
+See [canvas](../canvas/).
+
+### `onKeyboard`
+
+*Script widget only*
+
+This script is executed when the key(s) defined in the widget's `keyBinding` property are pressed.
+
+
+The following variables are available in this context:
+
- `type` (`string`): `keydown` or `keyup`
- `key` (`string`): key name,
@@ -34,38 +118,41 @@ Depending on what triggered the script's execution, a few variables are availabl
- `alt` (`boolean`): `true` if alt key is pressed
- `meta` (`boolean`): `true` if meta key is pressed
-## Touch state
-When some widgets are touched or released, a special event can be catched to trigger custom actions.
+### `onPreload`
-If the variable `touch` is not `undefined`, this means it holds the widget's current touch state:
+This script is specific to the root widget, it's called before any other widget is created and can be used to create global variables / functions accessible in other scripts.
-- `0/1` for the widget's touch state (`fader`, `knob` and `xy`, `range` and `multixy`)
-- `[i, 0/1]` if the widget is multi touch (`range` and `multixy`). In this case `i` is the touched handle's index, starting with `0`.
-
-```js
-if (touch !== undefined) {
- // send multi touch state
- if (touch.length) send('/touch_address', touch[0], touch[1])
- // send global touch state
- else send('/touch_address', touch)
-} else {
- // do something with the value ?
-}
-```
-
-To avoid unwanted script executions, touch state events will only be catched if the script contains the word `touch`.
+In this script, all osc messages emissions are prevented and changing the value of a widget won't trigger widget synchronisation / scripts / advanced syntaxes updates.
## Available variables
-Besides the variables available in the [javascript property syntax ](./advanced-syntaxes.md#available-variables) and the ones listed above, the following variables and functions are accessible in this context.
+The following variables and functions are accessible in this context.
+
+
+- `console`: javascript console
+- `locals`: object for storing/reading arbitrary values. Changing its properties *does not* trigger any synchronisation even if the value is used somewhere else.
+- `globals`: same as `locals` but shared between all widgets, contains a few useful variables:
+ - `screen`: client screen informations (`{width, height, orientation}`)
+ - `env`: client options (ie: url query options),
+ - `ip`: client's ip address,
+ - `url`: server url,
+ - `platform`: operating system as seen by the client
+ - `session`: session file path
+ - `clipboard`: instance of navigator [Clipboard](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard)
+- `Image`: javascript's [Image](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image) constructor
+
+
+!!! note "this"
+ Unlike in most javascript contexts, the special keyword `this` doesn't point to an object but instead returns the string `"this"`.
+
----
#### `get(id)`
- `id`: widget `id` as a string.
-Returns the value of the first matching widget.
+Returns the value of the first matching widget. If the returned value is an object, a copy is returned to allow safe mutation.
----
@@ -73,25 +160,54 @@ Returns the value of the first matching widget.
- `id`: widget `id` as a string. Can be `"this"` to target the host widget, or `"parent"` to target the parent widget. `id` may contains wildcards ('\*').
- `value`: new value for the widget.
- `options` (optional): `object`, accepts the following items:
- - `sync: false` (prevents widgets from triggering synchronization and scripts)
- - `send: false` (prevents widgets from sending osc messages)
+ - `sync: false`: prevents widgets from triggering synchronization and scripts
+ - `script: false`: prevents scripts but not synchronization
+ - `send: false`: prevents widgets from sending osc messages
+ - `external: true`: simulates a value coming from an osc/midi message (implies `send: false` automatically)
Sets the value of the first matching widget. If `ìd` contains wildcards, affects all matching widgets **except** the emitting widget.
If the event that triggered the script's execution was initiated by a user interaction, this will make the widget send its value as well (unless `options` is set to `{send: false}`).
+----
+
+#### `getVar(id, name)`
+- `id`: widget `id` as a string.
+- `name`: variable name as a string.
+
+Returns the value of a widget's custom variable. If the returned value is an object, a copy is returned to allow safe mutation.
+
+----
+
+#### `setVar(id, name, value)`
+- `id`: widget `id` as a string. Can be `"this"` to target the host widget, or `"parent"` to target the parent widget. `id` may contains wildcards ('\*').
+- `name`: variable name as a string.
+- `value`: new value for the variable.
+
+Sets the value of a widget's custom variable (see [advanced syntaxes](./advanced-syntaxes.md##ustom-variables-varvariablename-default)). If `ìd` contains wildcards, affects all matching widgets.
+
+
----
#### `send(target, address, ...args)`
-- `target` (optional): `"ip:port"` or `"midi:device_name"` string. If omitted, the widget's target will be used.
+- `target` (optional): `"ip:port"` or `"midi:device_name"` string. If omitted, the widget's target (or the server's defaults) will be used.
- `address`: osc address, must start with a `/`
-- `args`: value or `{type: "OSC_TYPE_LETTER", value: VALUE}` `object`
+- `args`: values or `{type: "OSC_TYPE_LETTER", value: VALUE}` objects
Sends an osc message.
If the event that triggered the script's execution was not initiated by a user interaction, this function will have no effect.
-This function ignores the widget's `bypass` property.
+This function ignores the widget's `bypass` and `ignoreDefaults` properties.
+
+??? infos "Examples"
+ ```javascript
+ send('127.0.0.1:4444', '/address', 1)
+ send('127.0.0.1:4444', '/address', 1, 2)
+ send('/address', 1) // uses the widget's target
+ send('/address', {type: 'i', value: 1}) // sends 1 as an integer
+ ```
+
----
@@ -99,7 +215,7 @@ This function ignores the widget's `bypass` property.
- `id`: widget `id` as a string. Can be `"this"` to target the host widget, or `"parent"` to target the parent widget.
- `name`: property name.
-Returns the property called `"name"` of the first matching widget.
+Returns the property called `"name"` of the first matching widget. If the returned value is an object, a copy is returned to allow safe mutation.
----
@@ -118,6 +234,13 @@ Forces a widget to check if one of its properties has changed and update itself
----
+#### `updateCanvas(id)`
+- `id`: widget `id` as a string. Can be `"this"` to target the host widget.
+
+Forces a canvas widget redraw.
+
+----
+
#### `httpGet(url, callback)`
- `url`: url of the resource to fetch (local url only)
@@ -132,10 +255,13 @@ Returns a state object (`id:value`) for matching widget and all their children.
----
-#### `stateSet(state)`
+#### `stateSet(state, options)`
Loads a state object. If the event that triggered the script's execution was initiated by a user interaction, this will make the updated widgets send their value as well.
+- `options` (optional): `object`, accepts the following items:
+ - `send: false`: prevents widgets from sending osc messages
+
----
#### `storage`
@@ -146,9 +272,9 @@ Global [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/lo
#### `setTimeout(id, callback, delay)` / `setInterval(id, callback, delay)`
-These work like their native equivalent, with an extra (optional) `id` argument.
+These work like almost their native equivalent, with an extra (optional) `id` argument.
-- `id` (optional): unique identifier. If a timeout with the same id is already running, it is cleared before the new one is created. If omitted, defaults to `undefined`. One can use `Math.random()` or `Date.now()` to force new id at each execution, though this might cause performance issues. `id`s are scoped to the widget's context: two timeouts with the same `id` in two different widgets can run concurrently
+- `id` (optional): unique identifier, if omitted, defaults to `undefined`. If a timeout with the same id is already running, it is cleared before the new one is created (even if `undefined`). `id`s are scoped to the widget's context: two timeouts with the same `id` in two different widgets can run concurrently
- `callback`: function to be executed
- `delay`: delay before execution is ms
@@ -157,11 +283,16 @@ Reference:
- https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
- https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
+
+Usage note:
+
+If no concurrent timeout / interval is needed, calling `setTimeout`, `setInterval`, `clearTimeout` and `clearInterval` with no `ìd` argument will do.
+
-----
#### `clearTimeout(id)` / `clearInterval(id)`
-Clear timeout with matching `id`.
+Clears timeout with matching `id`.
Reference:
@@ -170,16 +301,34 @@ Reference:
----
+#### `setFocus(id)`
+
+- `id` (optional): widget `id` as a string
+
+Gives focus to a widget (ie input widget). If `id` is omitted or falsy, currently focused element will be unfocused.
+
+*Built-in client only*: tells the operating system to give the focus to the client window
+
+----
+
#### `unfocus()`
*Built-in client only*: tells the operating system to give the focus to the window that was focused before.
----
+#### `setFocusable(focusable)`
+
+- `focusable`: `0` or `1`
+
+*Built-in client only*: define whether the client window can be focused or not. Text inputs cannot be interacted with when the window is not focusable.
+
+----
+
#### `getScroll(id)`
- `id`: widget `id` as a string.
-Returns the scroll state of a container as a `[x, y]` array.
+Returns the scroll position of a container as a `[x, y]` array.
----
@@ -192,14 +341,97 @@ Sets the scroll state of a container.
----
-#### `toolbar(i1, i2, ...)`
-- `iX`: menu entry index
+#### `scrollIntoView(id, option)`
+- `id`: widget `id` as a string. Can be `"this"` to target the host widget, or `"parent"` to target the parent widget.
+- `option`: `alignToTop` or `options` argument as defined in https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
-Trigger toolbar action at specified index.
+Scroll containers to make widget(s) visible.
-!!! example "Examples"
+
+----
+
+#### `toolbar(id)`
+- `id` menu entry id (string)
+
+Triggers toobar action if currently available (ie accessible from the menu). `id` can be one of the following:
+
+- `session-new`,`session-open`, `session-save`, `session-save-as`, `session-fragment`, `session-backup`, `session-import`, `session-export`
+- `state-store`, `state-recall`, `state-send`, `state-open`, `state-save`, `state-save-as`, `state-import`, `state-export`
+- `editor-enabled`, `editor-grid`, `editor-tree`, `editor-inspector`, `editor-percents`
+- `console-enabled`, `console-clear`
+- `fullscreen`, `notifictions`, `prevent-sleep`, `virtual-keyboard`
+
+Some actions will only be triggered if initiated with a physical user interaction, check the console for errors if it doesn't work as expected.
+
+
+=== "Legacy syntax: `toolbar(i1, i2, ...)`"
+
+ - `iX`: menu entry index
+
+ Triggers toolbar action at specified index.
+
+ !!! example "Examples"
- `toolbar(0, 0)` -> Open a new session
- - `toolbar(3)` -> Toggle full screen
+ - `toolbar(4)` -> Toggle full screen
- Actions will only be triggered if initiated with a user interaction. Fullscreen cannot be toggled with a simulated interaction (i.e. using `/SET`)
+
+----
+
+#### `getToolbar(id)`
+- `id` menu entry id (string)
+
+Returns `true` if the toolbar entry exists and is currently activated.
+
+#### `openUrl(url)`
+- `url`: http(s) url
+
+*Built-in client only*: opens url with the system's default browser
+*External client only*: opens url in a new tab
+
+If the event that triggered the script's execution was not initiated by a user interaction, this function will have no effect.
+
+----
+
+#### `runAs(id, callback)`
+- `id`: widget `id` as a string.
+- `callback`: function to be executed
+
+Run `callback` function as if executed by another that widget matches specified id. This will not change the value of any local variable but `"this"` and `"parent"` arguments (accepted by functions such as `set()`) will be interpreted differently. Timeouts and intervals will be created and cleared in the target widget's scope.
+
+----
+
+#### `reload(keepState)`
+- `keepState` (optional): `true` by default, set to false to discard the client's state.
+
+Reload the client application. Cannot be called from the `onCreate` property.
+
+If the event that triggered the script's execution was not initiated by a user interaction, this function will have no effect.
+
+
+----
+
+#### `getNavigator()`
+
+Returns the instance of [Navigator](https://developer.mozilla.org/en-US/docs/Web/API/Navigator).
+
+----
+
+#### `browseFile(options, callback)`
+
+Opens the server file browser and pass selected file to a callback function (does not create nor read files by itself).
+
+- `options`: object with the following keys:
+ - `extension`: allowed extension (default: "*")
+ - `directory`: starting directory for browser (default: user's home)
+ - `allowDir`: allow choosing a directory instead of a file (default: false)
+ - `mode`: "save" or "open"
+- `callback`: function called with 1 argument (file path)
+
+#### `uploadFile(options, callback)`
+
+Opens the client file upload prompt and pass the raw content of selected file to a callback function.
+
+- `options`: object with the following keys:
+ - `types`: equivalent of HTML attribute [`accept`](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/accept)
+- `callback`: function called with 1 argument (file content)
diff --git a/resources/docs/download.md b/resources/docs/download.md
index ff9ebb29..d5089028 100644
--- a/resources/docs/download.md
+++ b/resources/docs/download.md
@@ -3,56 +3,20 @@
!!! tip ""
[*Click here*](/docs/getting-started/introduction/#installation) to read the installation guide.
- Open Stage Control
+
+ Open Stage Control v{{config.latest_release}}
+
-Loading assets...
+
+ - GNU/Linux RPM (64-bit)
+ - GNU/Linux Debian (64-bit)
+ - GNU/Linux (64-bit)
+ - Node.js
+ - MacOS x64
+ - MacOS arm64
+ - Windows (64-bit)
-??? abstract "Changelog"
- Loading changelog...
-
-
-
+
+
+
diff --git a/resources/docs/extra/scripts.js b/resources/docs/extra/scripts.js
index c31449b7..f75c16a1 100644
--- a/resources/docs/extra/scripts.js
+++ b/resources/docs/extra/scripts.js
@@ -3,9 +3,19 @@ document.addEventListener('DOMContentLoaded', ()=>{
if (window.location.hash && window.location.href.includes('properties-reference')) {
// show target in tabs/details
document.querySelectorAll('[id='+window.location.hash.split("#")[1]+']').forEach(function(item){
- var tab = item.closest('.tabbed-content'),
- details = item.closest('details')
- if (tab) tab.previousSibling.click()
+ var tab = item.closest('.tabbed-block'),
+ container= item.closest('.tabbed-set'),
+ details = item.closest('details'),
+ index = 0
+ while (tab.previousElementSibling) {
+ index++
+ tab = tab.previousElementSibling
+ }
+ console.log(index)
+ container.querySelectorAll('.tabbed-labels label:nth-child('+(index+1)+')').forEach(function(item,i){
+ item.click()
+ })
+
if (item) {
item.scrollIntoView()
document.documentElement.scrollTop -= 70
diff --git a/resources/docs/extra/styles.css b/resources/docs/extra/styles.css
index 905bc870..83093318 100644
--- a/resources/docs/extra/styles.css
+++ b/resources/docs/extra/styles.css
@@ -102,6 +102,10 @@ details.api summary:before {
display: none!important;
}
+details summary div {
+ display: inline-block;
+}
+
i[title="dynamic"] {
color: var(--osc-accent-color);
}
diff --git a/resources/fonts/fa-solid-900.woff2 b/resources/fonts/fa-solid-900.woff2
index 978a681a..c7bd59c2 100644
Binary files a/resources/fonts/fa-solid-900.woff2 and b/resources/fonts/fa-solid-900.woff2 differ
diff --git a/resources/fonts/fa-solid.css b/resources/fonts/fa-solid.css
index fdd5fe71..ff9ec65e 100644
--- a/resources/fonts/fa-solid.css
+++ b/resources/fonts/fa-solid.css
@@ -1,14 +1,20 @@
/*!
- * Font Awesome Free 5.0.8 by @fontawesome - https://fontawesome.com
- * License - https://fontawesome.com/license (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
+ * Font Awesome Free 6.0.0 by @fontawesome - https://fontawesome.com
+ * License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
+ * Copyright 2022 Fonticons, Inc.
*/
+:root, :host {
+ --fa-font-solid: normal 900 1em/1 "FontAwesome"; }
+
@font-face {
- font-family: FontAwesome;
+ font-family: 'FontAwesome';
font-style: normal;
font-weight: 900;
- src: url("./fa-solid-900.woff2") format("woff2")}
+ font-display: block;
+ src: url("./fa-solid-900.woff2") format("woff2"); }
.fa,
-.fas {
- font-family: FontAwesome;
+.fas,
+.fa-solid {
+ font-family: 'FontAwesome';
font-weight: 900; }
diff --git a/resources/fonts/fontawesome.min.css b/resources/fonts/fontawesome.min.css
index 06a13c55..8b21c3d2 100644
--- a/resources/fonts/fontawesome.min.css
+++ b/resources/fonts/fontawesome.min.css
@@ -1,5 +1,6 @@
/*!
- * Font Awesome Free 5.13.0 by @fontawesome - https://fontawesome.com
+ * Font Awesome Free 6.0.0 by @fontawesome - https://fontawesome.com
* License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
+ * Copyright 2022 Fonticons, Inc.
*/
-.fa,.fab,.fad,.fal,.far,.fas{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:inline-block;font-style:normal;font-variant:normal;text-rendering:auto;line-height:1}.fa-lg{font-size:1.33333em;line-height:.75em;vertical-align:-.0667em}.fa-xs{font-size:.75em}.fa-sm{font-size:.875em}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:2.5em;padding-left:0}.fa-ul>li{position:relative}.fa-li{left:-2em;position:absolute;text-align:center;width:2em;line-height:inherit}.fa-border{border:.08em solid #eee;border-radius:.1em;padding:.2em .25em .15em}.fa-pull-left{float:left}.fa-pull-right{float:right}.fa.fa-pull-left,.fab.fa-pull-left,.fal.fa-pull-left,.far.fa-pull-left,.fas.fa-pull-left{margin-right:.3em}.fa.fa-pull-right,.fab.fa-pull-right,.fal.fa-pull-right,.far.fa-pull-right,.fas.fa-pull-right{margin-left:.3em}.fa-spin{-webkit-animation:fa-spin 2s linear infinite;animation:fa-spin 2s linear infinite}.fa-pulse{-webkit-animation:fa-spin 1s steps(8) infinite;animation:fa-spin 1s steps(8) infinite}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.fa-rotate-90{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";-webkit-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-webkit-transform:scaleY(-1);transform:scaleY(-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical,.fa-flip-vertical{-ms-filter:"progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)"}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1);transform:scale(-1)}:root .fa-flip-both,:root .fa-flip-horizontal,:root .fa-flip-vertical,:root .fa-rotate-90,:root .fa-rotate-180,:root .fa-rotate-270{-webkit-filter:none;filter:none}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:#fff}.fa-500px:before{content:"\f26e"}.fa-accessible-icon:before{content:"\f368"}.fa-accusoft:before{content:"\f369"}.fa-acquisitions-incorporated:before{content:"\f6af"}.fa-ad:before{content:"\f641"}.fa-address-book:before{content:"\f2b9"}.fa-address-card:before{content:"\f2bb"}.fa-adjust:before{content:"\f042"}.fa-adn:before{content:"\f170"}.fa-adobe:before{content:"\f778"}.fa-adversal:before{content:"\f36a"}.fa-affiliatetheme:before{content:"\f36b"}.fa-air-freshener:before{content:"\f5d0"}.fa-airbnb:before{content:"\f834"}.fa-algolia:before{content:"\f36c"}.fa-align-center:before{content:"\f037"}.fa-align-justify:before{content:"\f039"}.fa-align-left:before{content:"\f036"}.fa-align-right:before{content:"\f038"}.fa-alipay:before{content:"\f642"}.fa-allergies:before{content:"\f461"}.fa-amazon:before{content:"\f270"}.fa-amazon-pay:before{content:"\f42c"}.fa-ambulance:before{content:"\f0f9"}.fa-american-sign-language-interpreting:before{content:"\f2a3"}.fa-amilia:before{content:"\f36d"}.fa-anchor:before{content:"\f13d"}.fa-android:before{content:"\f17b"}.fa-angellist:before{content:"\f209"}.fa-angle-double-down:before{content:"\f103"}.fa-angle-double-left:before{content:"\f100"}.fa-angle-double-right:before{content:"\f101"}.fa-angle-double-up:before{content:"\f102"}.fa-angle-down:before{content:"\f107"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angry:before{content:"\f556"}.fa-angrycreative:before{content:"\f36e"}.fa-angular:before{content:"\f420"}.fa-ankh:before{content:"\f644"}.fa-app-store:before{content:"\f36f"}.fa-app-store-ios:before{content:"\f370"}.fa-apper:before{content:"\f371"}.fa-apple:before{content:"\f179"}.fa-apple-alt:before{content:"\f5d1"}.fa-apple-pay:before{content:"\f415"}.fa-archive:before{content:"\f187"}.fa-archway:before{content:"\f557"}.fa-arrow-alt-circle-down:before{content:"\f358"}.fa-arrow-alt-circle-left:before{content:"\f359"}.fa-arrow-alt-circle-right:before{content:"\f35a"}.fa-arrow-alt-circle-up:before{content:"\f35b"}.fa-arrow-circle-down:before{content:"\f0ab"}.fa-arrow-circle-left:before{content:"\f0a8"}.fa-arrow-circle-right:before{content:"\f0a9"}.fa-arrow-circle-up:before{content:"\f0aa"}.fa-arrow-down:before{content:"\f063"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-up:before{content:"\f062"}.fa-arrows-alt:before{content:"\f0b2"}.fa-arrows-alt-h:before{content:"\f337"}.fa-arrows-alt-v:before{content:"\f338"}.fa-artstation:before{content:"\f77a"}.fa-assistive-listening-systems:before{content:"\f2a2"}.fa-asterisk:before{content:"\f069"}.fa-asymmetrik:before{content:"\f372"}.fa-at:before{content:"\f1fa"}.fa-atlas:before{content:"\f558"}.fa-atlassian:before{content:"\f77b"}.fa-atom:before{content:"\f5d2"}.fa-audible:before{content:"\f373"}.fa-audio-description:before{content:"\f29e"}.fa-autoprefixer:before{content:"\f41c"}.fa-avianex:before{content:"\f374"}.fa-aviato:before{content:"\f421"}.fa-award:before{content:"\f559"}.fa-aws:before{content:"\f375"}.fa-baby:before{content:"\f77c"}.fa-baby-carriage:before{content:"\f77d"}.fa-backspace:before{content:"\f55a"}.fa-backward:before{content:"\f04a"}.fa-bacon:before{content:"\f7e5"}.fa-bahai:before{content:"\f666"}.fa-balance-scale:before{content:"\f24e"}.fa-balance-scale-left:before{content:"\f515"}.fa-balance-scale-right:before{content:"\f516"}.fa-ban:before{content:"\f05e"}.fa-band-aid:before{content:"\f462"}.fa-bandcamp:before{content:"\f2d5"}.fa-barcode:before{content:"\f02a"}.fa-bars:before{content:"\f0c9"}.fa-baseball-ball:before{content:"\f433"}.fa-basketball-ball:before{content:"\f434"}.fa-bath:before{content:"\f2cd"}.fa-battery-empty:before{content:"\f244"}.fa-battery-full:before{content:"\f240"}.fa-battery-half:before{content:"\f242"}.fa-battery-quarter:before{content:"\f243"}.fa-battery-three-quarters:before{content:"\f241"}.fa-battle-net:before{content:"\f835"}.fa-bed:before{content:"\f236"}.fa-beer:before{content:"\f0fc"}.fa-behance:before{content:"\f1b4"}.fa-behance-square:before{content:"\f1b5"}.fa-bell:before{content:"\f0f3"}.fa-bell-slash:before{content:"\f1f6"}.fa-bezier-curve:before{content:"\f55b"}.fa-bible:before{content:"\f647"}.fa-bicycle:before{content:"\f206"}.fa-biking:before{content:"\f84a"}.fa-bimobject:before{content:"\f378"}.fa-binoculars:before{content:"\f1e5"}.fa-biohazard:before{content:"\f780"}.fa-birthday-cake:before{content:"\f1fd"}.fa-bitbucket:before{content:"\f171"}.fa-bitcoin:before{content:"\f379"}.fa-bity:before{content:"\f37a"}.fa-black-tie:before{content:"\f27e"}.fa-blackberry:before{content:"\f37b"}.fa-blender:before{content:"\f517"}.fa-blender-phone:before{content:"\f6b6"}.fa-blind:before{content:"\f29d"}.fa-blog:before{content:"\f781"}.fa-blogger:before{content:"\f37c"}.fa-blogger-b:before{content:"\f37d"}.fa-bluetooth:before{content:"\f293"}.fa-bluetooth-b:before{content:"\f294"}.fa-bold:before{content:"\f032"}.fa-bolt:before{content:"\f0e7"}.fa-bomb:before{content:"\f1e2"}.fa-bone:before{content:"\f5d7"}.fa-bong:before{content:"\f55c"}.fa-book:before{content:"\f02d"}.fa-book-dead:before{content:"\f6b7"}.fa-book-medical:before{content:"\f7e6"}.fa-book-open:before{content:"\f518"}.fa-book-reader:before{content:"\f5da"}.fa-bookmark:before{content:"\f02e"}.fa-bootstrap:before{content:"\f836"}.fa-border-all:before{content:"\f84c"}.fa-border-none:before{content:"\f850"}.fa-border-style:before{content:"\f853"}.fa-bowling-ball:before{content:"\f436"}.fa-box:before{content:"\f466"}.fa-box-open:before{content:"\f49e"}.fa-box-tissue:before{content:"\f95b"}.fa-boxes:before{content:"\f468"}.fa-braille:before{content:"\f2a1"}.fa-brain:before{content:"\f5dc"}.fa-bread-slice:before{content:"\f7ec"}.fa-briefcase:before{content:"\f0b1"}.fa-briefcase-medical:before{content:"\f469"}.fa-broadcast-tower:before{content:"\f519"}.fa-broom:before{content:"\f51a"}.fa-brush:before{content:"\f55d"}.fa-btc:before{content:"\f15a"}.fa-buffer:before{content:"\f837"}.fa-bug:before{content:"\f188"}.fa-building:before{content:"\f1ad"}.fa-bullhorn:before{content:"\f0a1"}.fa-bullseye:before{content:"\f140"}.fa-burn:before{content:"\f46a"}.fa-buromobelexperte:before{content:"\f37f"}.fa-bus:before{content:"\f207"}.fa-bus-alt:before{content:"\f55e"}.fa-business-time:before{content:"\f64a"}.fa-buy-n-large:before{content:"\f8a6"}.fa-buysellads:before{content:"\f20d"}.fa-calculator:before{content:"\f1ec"}.fa-calendar:before{content:"\f133"}.fa-calendar-alt:before{content:"\f073"}.fa-calendar-check:before{content:"\f274"}.fa-calendar-day:before{content:"\f783"}.fa-calendar-minus:before{content:"\f272"}.fa-calendar-plus:before{content:"\f271"}.fa-calendar-times:before{content:"\f273"}.fa-calendar-week:before{content:"\f784"}.fa-camera:before{content:"\f030"}.fa-camera-retro:before{content:"\f083"}.fa-campground:before{content:"\f6bb"}.fa-canadian-maple-leaf:before{content:"\f785"}.fa-candy-cane:before{content:"\f786"}.fa-cannabis:before{content:"\f55f"}.fa-capsules:before{content:"\f46b"}.fa-car:before{content:"\f1b9"}.fa-car-alt:before{content:"\f5de"}.fa-car-battery:before{content:"\f5df"}.fa-car-crash:before{content:"\f5e1"}.fa-car-side:before{content:"\f5e4"}.fa-caravan:before{content:"\f8ff"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-caret-square-down:before{content:"\f150"}.fa-caret-square-left:before{content:"\f191"}.fa-caret-square-right:before{content:"\f152"}.fa-caret-square-up:before{content:"\f151"}.fa-caret-up:before{content:"\f0d8"}.fa-carrot:before{content:"\f787"}.fa-cart-arrow-down:before{content:"\f218"}.fa-cart-plus:before{content:"\f217"}.fa-cash-register:before{content:"\f788"}.fa-cat:before{content:"\f6be"}.fa-cc-amazon-pay:before{content:"\f42d"}.fa-cc-amex:before{content:"\f1f3"}.fa-cc-apple-pay:before{content:"\f416"}.fa-cc-diners-club:before{content:"\f24c"}.fa-cc-discover:before{content:"\f1f2"}.fa-cc-jcb:before{content:"\f24b"}.fa-cc-mastercard:before{content:"\f1f1"}.fa-cc-paypal:before{content:"\f1f4"}.fa-cc-stripe:before{content:"\f1f5"}.fa-cc-visa:before{content:"\f1f0"}.fa-centercode:before{content:"\f380"}.fa-centos:before{content:"\f789"}.fa-certificate:before{content:"\f0a3"}.fa-chair:before{content:"\f6c0"}.fa-chalkboard:before{content:"\f51b"}.fa-chalkboard-teacher:before{content:"\f51c"}.fa-charging-station:before{content:"\f5e7"}.fa-chart-area:before{content:"\f1fe"}.fa-chart-bar:before{content:"\f080"}.fa-chart-line:before{content:"\f201"}.fa-chart-pie:before{content:"\f200"}.fa-check:before{content:"\f00c"}.fa-check-circle:before{content:"\f058"}.fa-check-double:before{content:"\f560"}.fa-check-square:before{content:"\f14a"}.fa-cheese:before{content:"\f7ef"}.fa-chess:before{content:"\f439"}.fa-chess-bishop:before{content:"\f43a"}.fa-chess-board:before{content:"\f43c"}.fa-chess-king:before{content:"\f43f"}.fa-chess-knight:before{content:"\f441"}.fa-chess-pawn:before{content:"\f443"}.fa-chess-queen:before{content:"\f445"}.fa-chess-rook:before{content:"\f447"}.fa-chevron-circle-down:before{content:"\f13a"}.fa-chevron-circle-left:before{content:"\f137"}.fa-chevron-circle-right:before{content:"\f138"}.fa-chevron-circle-up:before{content:"\f139"}.fa-chevron-down:before{content:"\f078"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-chevron-up:before{content:"\f077"}.fa-child:before{content:"\f1ae"}.fa-chrome:before{content:"\f268"}.fa-chromecast:before{content:"\f838"}.fa-church:before{content:"\f51d"}.fa-circle:before{content:"\f111"}.fa-circle-notch:before{content:"\f1ce"}.fa-city:before{content:"\f64f"}.fa-clinic-medical:before{content:"\f7f2"}.fa-clipboard:before{content:"\f328"}.fa-clipboard-check:before{content:"\f46c"}.fa-clipboard-list:before{content:"\f46d"}.fa-clock:before{content:"\f017"}.fa-clone:before{content:"\f24d"}.fa-closed-captioning:before{content:"\f20a"}.fa-cloud:before{content:"\f0c2"}.fa-cloud-download-alt:before{content:"\f381"}.fa-cloud-meatball:before{content:"\f73b"}.fa-cloud-moon:before{content:"\f6c3"}.fa-cloud-moon-rain:before{content:"\f73c"}.fa-cloud-rain:before{content:"\f73d"}.fa-cloud-showers-heavy:before{content:"\f740"}.fa-cloud-sun:before{content:"\f6c4"}.fa-cloud-sun-rain:before{content:"\f743"}.fa-cloud-upload-alt:before{content:"\f382"}.fa-cloudscale:before{content:"\f383"}.fa-cloudsmith:before{content:"\f384"}.fa-cloudversify:before{content:"\f385"}.fa-cocktail:before{content:"\f561"}.fa-code:before{content:"\f121"}.fa-code-branch:before{content:"\f126"}.fa-codepen:before{content:"\f1cb"}.fa-codiepie:before{content:"\f284"}.fa-coffee:before{content:"\f0f4"}.fa-cog:before{content:"\f013"}.fa-cogs:before{content:"\f085"}.fa-coins:before{content:"\f51e"}.fa-columns:before{content:"\f0db"}.fa-comment:before{content:"\f075"}.fa-comment-alt:before{content:"\f27a"}.fa-comment-dollar:before{content:"\f651"}.fa-comment-dots:before{content:"\f4ad"}.fa-comment-medical:before{content:"\f7f5"}.fa-comment-slash:before{content:"\f4b3"}.fa-comments:before{content:"\f086"}.fa-comments-dollar:before{content:"\f653"}.fa-compact-disc:before{content:"\f51f"}.fa-compass:before{content:"\f14e"}.fa-compress:before{content:"\f066"}.fa-compress-alt:before{content:"\f422"}.fa-compress-arrows-alt:before{content:"\f78c"}.fa-concierge-bell:before{content:"\f562"}.fa-confluence:before{content:"\f78d"}.fa-connectdevelop:before{content:"\f20e"}.fa-contao:before{content:"\f26d"}.fa-cookie:before{content:"\f563"}.fa-cookie-bite:before{content:"\f564"}.fa-copy:before{content:"\f0c5"}.fa-copyright:before{content:"\f1f9"}.fa-cotton-bureau:before{content:"\f89e"}.fa-couch:before{content:"\f4b8"}.fa-cpanel:before{content:"\f388"}.fa-creative-commons:before{content:"\f25e"}.fa-creative-commons-by:before{content:"\f4e7"}.fa-creative-commons-nc:before{content:"\f4e8"}.fa-creative-commons-nc-eu:before{content:"\f4e9"}.fa-creative-commons-nc-jp:before{content:"\f4ea"}.fa-creative-commons-nd:before{content:"\f4eb"}.fa-creative-commons-pd:before{content:"\f4ec"}.fa-creative-commons-pd-alt:before{content:"\f4ed"}.fa-creative-commons-remix:before{content:"\f4ee"}.fa-creative-commons-sa:before{content:"\f4ef"}.fa-creative-commons-sampling:before{content:"\f4f0"}.fa-creative-commons-sampling-plus:before{content:"\f4f1"}.fa-creative-commons-share:before{content:"\f4f2"}.fa-creative-commons-zero:before{content:"\f4f3"}.fa-credit-card:before{content:"\f09d"}.fa-critical-role:before{content:"\f6c9"}.fa-crop:before{content:"\f125"}.fa-crop-alt:before{content:"\f565"}.fa-cross:before{content:"\f654"}.fa-crosshairs:before{content:"\f05b"}.fa-crow:before{content:"\f520"}.fa-crown:before{content:"\f521"}.fa-crutch:before{content:"\f7f7"}.fa-css3:before{content:"\f13c"}.fa-css3-alt:before{content:"\f38b"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-cut:before{content:"\f0c4"}.fa-cuttlefish:before{content:"\f38c"}.fa-d-and-d:before{content:"\f38d"}.fa-d-and-d-beyond:before{content:"\f6ca"}.fa-dailymotion:before{content:"\f952"}.fa-dashcube:before{content:"\f210"}.fa-database:before{content:"\f1c0"}.fa-deaf:before{content:"\f2a4"}.fa-delicious:before{content:"\f1a5"}.fa-democrat:before{content:"\f747"}.fa-deploydog:before{content:"\f38e"}.fa-deskpro:before{content:"\f38f"}.fa-desktop:before{content:"\f108"}.fa-dev:before{content:"\f6cc"}.fa-deviantart:before{content:"\f1bd"}.fa-dharmachakra:before{content:"\f655"}.fa-dhl:before{content:"\f790"}.fa-diagnoses:before{content:"\f470"}.fa-diaspora:before{content:"\f791"}.fa-dice:before{content:"\f522"}.fa-dice-d20:before{content:"\f6cf"}.fa-dice-d6:before{content:"\f6d1"}.fa-dice-five:before{content:"\f523"}.fa-dice-four:before{content:"\f524"}.fa-dice-one:before{content:"\f525"}.fa-dice-six:before{content:"\f526"}.fa-dice-three:before{content:"\f527"}.fa-dice-two:before{content:"\f528"}.fa-digg:before{content:"\f1a6"}.fa-digital-ocean:before{content:"\f391"}.fa-digital-tachograph:before{content:"\f566"}.fa-directions:before{content:"\f5eb"}.fa-discord:before{content:"\f392"}.fa-discourse:before{content:"\f393"}.fa-disease:before{content:"\f7fa"}.fa-divide:before{content:"\f529"}.fa-dizzy:before{content:"\f567"}.fa-dna:before{content:"\f471"}.fa-dochub:before{content:"\f394"}.fa-docker:before{content:"\f395"}.fa-dog:before{content:"\f6d3"}.fa-dollar-sign:before{content:"\f155"}.fa-dolly:before{content:"\f472"}.fa-dolly-flatbed:before{content:"\f474"}.fa-donate:before{content:"\f4b9"}.fa-door-closed:before{content:"\f52a"}.fa-door-open:before{content:"\f52b"}.fa-dot-circle:before{content:"\f192"}.fa-dove:before{content:"\f4ba"}.fa-download:before{content:"\f019"}.fa-draft2digital:before{content:"\f396"}.fa-drafting-compass:before{content:"\f568"}.fa-dragon:before{content:"\f6d5"}.fa-draw-polygon:before{content:"\f5ee"}.fa-dribbble:before{content:"\f17d"}.fa-dribbble-square:before{content:"\f397"}.fa-dropbox:before{content:"\f16b"}.fa-drum:before{content:"\f569"}.fa-drum-steelpan:before{content:"\f56a"}.fa-drumstick-bite:before{content:"\f6d7"}.fa-drupal:before{content:"\f1a9"}.fa-dumbbell:before{content:"\f44b"}.fa-dumpster:before{content:"\f793"}.fa-dumpster-fire:before{content:"\f794"}.fa-dungeon:before{content:"\f6d9"}.fa-dyalog:before{content:"\f399"}.fa-earlybirds:before{content:"\f39a"}.fa-ebay:before{content:"\f4f4"}.fa-edge:before{content:"\f282"}.fa-edit:before{content:"\f044"}.fa-egg:before{content:"\f7fb"}.fa-eject:before{content:"\f052"}.fa-elementor:before{content:"\f430"}.fa-ellipsis-h:before{content:"\f141"}.fa-ellipsis-v:before{content:"\f142"}.fa-ello:before{content:"\f5f1"}.fa-ember:before{content:"\f423"}.fa-empire:before{content:"\f1d1"}.fa-envelope:before{content:"\f0e0"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-text:before{content:"\f658"}.fa-envelope-square:before{content:"\f199"}.fa-envira:before{content:"\f299"}.fa-equals:before{content:"\f52c"}.fa-eraser:before{content:"\f12d"}.fa-erlang:before{content:"\f39d"}.fa-ethereum:before{content:"\f42e"}.fa-ethernet:before{content:"\f796"}.fa-etsy:before{content:"\f2d7"}.fa-euro-sign:before{content:"\f153"}.fa-evernote:before{content:"\f839"}.fa-exchange-alt:before{content:"\f362"}.fa-exclamation:before{content:"\f12a"}.fa-exclamation-circle:before{content:"\f06a"}.fa-exclamation-triangle:before{content:"\f071"}.fa-expand:before{content:"\f065"}.fa-expand-alt:before{content:"\f424"}.fa-expand-arrows-alt:before{content:"\f31e"}.fa-expeditedssl:before{content:"\f23e"}.fa-external-link-alt:before{content:"\f35d"}.fa-external-link-square-alt:before{content:"\f360"}.fa-eye:before{content:"\f06e"}.fa-eye-dropper:before{content:"\f1fb"}.fa-eye-slash:before{content:"\f070"}.fa-facebook:before{content:"\f09a"}.fa-facebook-f:before{content:"\f39e"}.fa-facebook-messenger:before{content:"\f39f"}.fa-facebook-square:before{content:"\f082"}.fa-fan:before{content:"\f863"}.fa-fantasy-flight-games:before{content:"\f6dc"}.fa-fast-backward:before{content:"\f049"}.fa-fast-forward:before{content:"\f050"}.fa-faucet:before{content:"\f905"}.fa-fax:before{content:"\f1ac"}.fa-feather:before{content:"\f52d"}.fa-feather-alt:before{content:"\f56b"}.fa-fedex:before{content:"\f797"}.fa-fedora:before{content:"\f798"}.fa-female:before{content:"\f182"}.fa-fighter-jet:before{content:"\f0fb"}.fa-figma:before{content:"\f799"}.fa-file:before{content:"\f15b"}.fa-file-alt:before{content:"\f15c"}.fa-file-archive:before{content:"\f1c6"}.fa-file-audio:before{content:"\f1c7"}.fa-file-code:before{content:"\f1c9"}.fa-file-contract:before{content:"\f56c"}.fa-file-csv:before{content:"\f6dd"}.fa-file-download:before{content:"\f56d"}.fa-file-excel:before{content:"\f1c3"}.fa-file-export:before{content:"\f56e"}.fa-file-image:before{content:"\f1c5"}.fa-file-import:before{content:"\f56f"}.fa-file-invoice:before{content:"\f570"}.fa-file-invoice-dollar:before{content:"\f571"}.fa-file-medical:before{content:"\f477"}.fa-file-medical-alt:before{content:"\f478"}.fa-file-pdf:before{content:"\f1c1"}.fa-file-powerpoint:before{content:"\f1c4"}.fa-file-prescription:before{content:"\f572"}.fa-file-signature:before{content:"\f573"}.fa-file-upload:before{content:"\f574"}.fa-file-video:before{content:"\f1c8"}.fa-file-word:before{content:"\f1c2"}.fa-fill:before{content:"\f575"}.fa-fill-drip:before{content:"\f576"}.fa-film:before{content:"\f008"}.fa-filter:before{content:"\f0b0"}.fa-fingerprint:before{content:"\f577"}.fa-fire:before{content:"\f06d"}.fa-fire-alt:before{content:"\f7e4"}.fa-fire-extinguisher:before{content:"\f134"}.fa-firefox:before{content:"\f269"}.fa-firefox-browser:before{content:"\f907"}.fa-first-aid:before{content:"\f479"}.fa-first-order:before{content:"\f2b0"}.fa-first-order-alt:before{content:"\f50a"}.fa-firstdraft:before{content:"\f3a1"}.fa-fish:before{content:"\f578"}.fa-fist-raised:before{content:"\f6de"}.fa-flag:before{content:"\f024"}.fa-flag-checkered:before{content:"\f11e"}.fa-flag-usa:before{content:"\f74d"}.fa-flask:before{content:"\f0c3"}.fa-flickr:before{content:"\f16e"}.fa-flipboard:before{content:"\f44d"}.fa-flushed:before{content:"\f579"}.fa-fly:before{content:"\f417"}.fa-folder:before{content:"\f07b"}.fa-folder-minus:before{content:"\f65d"}.fa-folder-open:before{content:"\f07c"}.fa-folder-plus:before{content:"\f65e"}.fa-font:before{content:"\f031"}.fa-font-awesome:before{content:"\f2b4"}.fa-font-awesome-alt:before{content:"\f35c"}.fa-font-awesome-flag:before{content:"\f425"}.fa-font-awesome-logo-full:before{content:"\f4e6"}.fa-fonticons:before{content:"\f280"}.fa-fonticons-fi:before{content:"\f3a2"}.fa-football-ball:before{content:"\f44e"}.fa-fort-awesome:before{content:"\f286"}.fa-fort-awesome-alt:before{content:"\f3a3"}.fa-forumbee:before{content:"\f211"}.fa-forward:before{content:"\f04e"}.fa-foursquare:before{content:"\f180"}.fa-free-code-camp:before{content:"\f2c5"}.fa-freebsd:before{content:"\f3a4"}.fa-frog:before{content:"\f52e"}.fa-frown:before{content:"\f119"}.fa-frown-open:before{content:"\f57a"}.fa-fulcrum:before{content:"\f50b"}.fa-funnel-dollar:before{content:"\f662"}.fa-futbol:before{content:"\f1e3"}.fa-galactic-republic:before{content:"\f50c"}.fa-galactic-senate:before{content:"\f50d"}.fa-gamepad:before{content:"\f11b"}.fa-gas-pump:before{content:"\f52f"}.fa-gavel:before{content:"\f0e3"}.fa-gem:before{content:"\f3a5"}.fa-genderless:before{content:"\f22d"}.fa-get-pocket:before{content:"\f265"}.fa-gg:before{content:"\f260"}.fa-gg-circle:before{content:"\f261"}.fa-ghost:before{content:"\f6e2"}.fa-gift:before{content:"\f06b"}.fa-gifts:before{content:"\f79c"}.fa-git:before{content:"\f1d3"}.fa-git-alt:before{content:"\f841"}.fa-git-square:before{content:"\f1d2"}.fa-github:before{content:"\f09b"}.fa-github-alt:before{content:"\f113"}.fa-github-square:before{content:"\f092"}.fa-gitkraken:before{content:"\f3a6"}.fa-gitlab:before{content:"\f296"}.fa-gitter:before{content:"\f426"}.fa-glass-cheers:before{content:"\f79f"}.fa-glass-martini:before{content:"\f000"}.fa-glass-martini-alt:before{content:"\f57b"}.fa-glass-whiskey:before{content:"\f7a0"}.fa-glasses:before{content:"\f530"}.fa-glide:before{content:"\f2a5"}.fa-glide-g:before{content:"\f2a6"}.fa-globe:before{content:"\f0ac"}.fa-globe-africa:before{content:"\f57c"}.fa-globe-americas:before{content:"\f57d"}.fa-globe-asia:before{content:"\f57e"}.fa-globe-europe:before{content:"\f7a2"}.fa-gofore:before{content:"\f3a7"}.fa-golf-ball:before{content:"\f450"}.fa-goodreads:before{content:"\f3a8"}.fa-goodreads-g:before{content:"\f3a9"}.fa-google:before{content:"\f1a0"}.fa-google-drive:before{content:"\f3aa"}.fa-google-play:before{content:"\f3ab"}.fa-google-plus:before{content:"\f2b3"}.fa-google-plus-g:before{content:"\f0d5"}.fa-google-plus-square:before{content:"\f0d4"}.fa-google-wallet:before{content:"\f1ee"}.fa-gopuram:before{content:"\f664"}.fa-graduation-cap:before{content:"\f19d"}.fa-gratipay:before{content:"\f184"}.fa-grav:before{content:"\f2d6"}.fa-greater-than:before{content:"\f531"}.fa-greater-than-equal:before{content:"\f532"}.fa-grimace:before{content:"\f57f"}.fa-grin:before{content:"\f580"}.fa-grin-alt:before{content:"\f581"}.fa-grin-beam:before{content:"\f582"}.fa-grin-beam-sweat:before{content:"\f583"}.fa-grin-hearts:before{content:"\f584"}.fa-grin-squint:before{content:"\f585"}.fa-grin-squint-tears:before{content:"\f586"}.fa-grin-stars:before{content:"\f587"}.fa-grin-tears:before{content:"\f588"}.fa-grin-tongue:before{content:"\f589"}.fa-grin-tongue-squint:before{content:"\f58a"}.fa-grin-tongue-wink:before{content:"\f58b"}.fa-grin-wink:before{content:"\f58c"}.fa-grip-horizontal:before{content:"\f58d"}.fa-grip-lines:before{content:"\f7a4"}.fa-grip-lines-vertical:before{content:"\f7a5"}.fa-grip-vertical:before{content:"\f58e"}.fa-gripfire:before{content:"\f3ac"}.fa-grunt:before{content:"\f3ad"}.fa-guitar:before{content:"\f7a6"}.fa-gulp:before{content:"\f3ae"}.fa-h-square:before{content:"\f0fd"}.fa-hacker-news:before{content:"\f1d4"}.fa-hacker-news-square:before{content:"\f3af"}.fa-hackerrank:before{content:"\f5f7"}.fa-hamburger:before{content:"\f805"}.fa-hammer:before{content:"\f6e3"}.fa-hamsa:before{content:"\f665"}.fa-hand-holding:before{content:"\f4bd"}.fa-hand-holding-heart:before{content:"\f4be"}.fa-hand-holding-medical:before{content:"\f95c"}.fa-hand-holding-usd:before{content:"\f4c0"}.fa-hand-holding-water:before{content:"\f4c1"}.fa-hand-lizard:before{content:"\f258"}.fa-hand-middle-finger:before{content:"\f806"}.fa-hand-paper:before{content:"\f256"}.fa-hand-peace:before{content:"\f25b"}.fa-hand-point-down:before{content:"\f0a7"}.fa-hand-point-left:before{content:"\f0a5"}.fa-hand-point-right:before{content:"\f0a4"}.fa-hand-point-up:before{content:"\f0a6"}.fa-hand-pointer:before{content:"\f25a"}.fa-hand-rock:before{content:"\f255"}.fa-hand-scissors:before{content:"\f257"}.fa-hand-sparkles:before{content:"\f95d"}.fa-hand-spock:before{content:"\f259"}.fa-hands:before{content:"\f4c2"}.fa-hands-helping:before{content:"\f4c4"}.fa-hands-wash:before{content:"\f95e"}.fa-handshake:before{content:"\f2b5"}.fa-handshake-alt-slash:before{content:"\f95f"}.fa-handshake-slash:before{content:"\f960"}.fa-hanukiah:before{content:"\f6e6"}.fa-hard-hat:before{content:"\f807"}.fa-hashtag:before{content:"\f292"}.fa-hat-cowboy:before{content:"\f8c0"}.fa-hat-cowboy-side:before{content:"\f8c1"}.fa-hat-wizard:before{content:"\f6e8"}.fa-hdd:before{content:"\f0a0"}.fa-head-side-cough:before{content:"\f961"}.fa-head-side-cough-slash:before{content:"\f962"}.fa-head-side-mask:before{content:"\f963"}.fa-head-side-virus:before{content:"\f964"}.fa-heading:before{content:"\f1dc"}.fa-headphones:before{content:"\f025"}.fa-headphones-alt:before{content:"\f58f"}.fa-headset:before{content:"\f590"}.fa-heart:before{content:"\f004"}.fa-heart-broken:before{content:"\f7a9"}.fa-heartbeat:before{content:"\f21e"}.fa-helicopter:before{content:"\f533"}.fa-highlighter:before{content:"\f591"}.fa-hiking:before{content:"\f6ec"}.fa-hippo:before{content:"\f6ed"}.fa-hips:before{content:"\f452"}.fa-hire-a-helper:before{content:"\f3b0"}.fa-history:before{content:"\f1da"}.fa-hockey-puck:before{content:"\f453"}.fa-holly-berry:before{content:"\f7aa"}.fa-home:before{content:"\f015"}.fa-hooli:before{content:"\f427"}.fa-hornbill:before{content:"\f592"}.fa-horse:before{content:"\f6f0"}.fa-horse-head:before{content:"\f7ab"}.fa-hospital:before{content:"\f0f8"}.fa-hospital-alt:before{content:"\f47d"}.fa-hospital-symbol:before{content:"\f47e"}.fa-hospital-user:before{content:"\f80d"}.fa-hot-tub:before{content:"\f593"}.fa-hotdog:before{content:"\f80f"}.fa-hotel:before{content:"\f594"}.fa-hotjar:before{content:"\f3b1"}.fa-hourglass:before{content:"\f254"}.fa-hourglass-end:before{content:"\f253"}.fa-hourglass-half:before{content:"\f252"}.fa-hourglass-start:before{content:"\f251"}.fa-house-damage:before{content:"\f6f1"}.fa-house-user:before{content:"\f965"}.fa-houzz:before{content:"\f27c"}.fa-hryvnia:before{content:"\f6f2"}.fa-html5:before{content:"\f13b"}.fa-hubspot:before{content:"\f3b2"}.fa-i-cursor:before{content:"\f246"}.fa-ice-cream:before{content:"\f810"}.fa-icicles:before{content:"\f7ad"}.fa-icons:before{content:"\f86d"}.fa-id-badge:before{content:"\f2c1"}.fa-id-card:before{content:"\f2c2"}.fa-id-card-alt:before{content:"\f47f"}.fa-ideal:before{content:"\f913"}.fa-igloo:before{content:"\f7ae"}.fa-image:before{content:"\f03e"}.fa-images:before{content:"\f302"}.fa-imdb:before{content:"\f2d8"}.fa-inbox:before{content:"\f01c"}.fa-indent:before{content:"\f03c"}.fa-industry:before{content:"\f275"}.fa-infinity:before{content:"\f534"}.fa-info:before{content:"\f129"}.fa-info-circle:before{content:"\f05a"}.fa-instagram:before{content:"\f16d"}.fa-instagram-square:before{content:"\f955"}.fa-intercom:before{content:"\f7af"}.fa-internet-explorer:before{content:"\f26b"}.fa-invision:before{content:"\f7b0"}.fa-ioxhost:before{content:"\f208"}.fa-italic:before{content:"\f033"}.fa-itch-io:before{content:"\f83a"}.fa-itunes:before{content:"\f3b4"}.fa-itunes-note:before{content:"\f3b5"}.fa-java:before{content:"\f4e4"}.fa-jedi:before{content:"\f669"}.fa-jedi-order:before{content:"\f50e"}.fa-jenkins:before{content:"\f3b6"}.fa-jira:before{content:"\f7b1"}.fa-joget:before{content:"\f3b7"}.fa-joint:before{content:"\f595"}.fa-joomla:before{content:"\f1aa"}.fa-journal-whills:before{content:"\f66a"}.fa-js:before{content:"\f3b8"}.fa-js-square:before{content:"\f3b9"}.fa-jsfiddle:before{content:"\f1cc"}.fa-kaaba:before{content:"\f66b"}.fa-kaggle:before{content:"\f5fa"}.fa-key:before{content:"\f084"}.fa-keybase:before{content:"\f4f5"}.fa-keyboard:before{content:"\f11c"}.fa-keycdn:before{content:"\f3ba"}.fa-khanda:before{content:"\f66d"}.fa-kickstarter:before{content:"\f3bb"}.fa-kickstarter-k:before{content:"\f3bc"}.fa-kiss:before{content:"\f596"}.fa-kiss-beam:before{content:"\f597"}.fa-kiss-wink-heart:before{content:"\f598"}.fa-kiwi-bird:before{content:"\f535"}.fa-korvue:before{content:"\f42f"}.fa-landmark:before{content:"\f66f"}.fa-language:before{content:"\f1ab"}.fa-laptop:before{content:"\f109"}.fa-laptop-code:before{content:"\f5fc"}.fa-laptop-house:before{content:"\f966"}.fa-laptop-medical:before{content:"\f812"}.fa-laravel:before{content:"\f3bd"}.fa-lastfm:before{content:"\f202"}.fa-lastfm-square:before{content:"\f203"}.fa-laugh:before{content:"\f599"}.fa-laugh-beam:before{content:"\f59a"}.fa-laugh-squint:before{content:"\f59b"}.fa-laugh-wink:before{content:"\f59c"}.fa-layer-group:before{content:"\f5fd"}.fa-leaf:before{content:"\f06c"}.fa-leanpub:before{content:"\f212"}.fa-lemon:before{content:"\f094"}.fa-less:before{content:"\f41d"}.fa-less-than:before{content:"\f536"}.fa-less-than-equal:before{content:"\f537"}.fa-level-down-alt:before{content:"\f3be"}.fa-level-up-alt:before{content:"\f3bf"}.fa-life-ring:before{content:"\f1cd"}.fa-lightbulb:before{content:"\f0eb"}.fa-line:before{content:"\f3c0"}.fa-link:before{content:"\f0c1"}.fa-linkedin:before{content:"\f08c"}.fa-linkedin-in:before{content:"\f0e1"}.fa-linode:before{content:"\f2b8"}.fa-linux:before{content:"\f17c"}.fa-lira-sign:before{content:"\f195"}.fa-list:before{content:"\f03a"}.fa-list-alt:before{content:"\f022"}.fa-list-ol:before{content:"\f0cb"}.fa-list-ul:before{content:"\f0ca"}.fa-location-arrow:before{content:"\f124"}.fa-lock:before{content:"\f023"}.fa-lock-open:before{content:"\f3c1"}.fa-long-arrow-alt-down:before{content:"\f309"}.fa-long-arrow-alt-left:before{content:"\f30a"}.fa-long-arrow-alt-right:before{content:"\f30b"}.fa-long-arrow-alt-up:before{content:"\f30c"}.fa-low-vision:before{content:"\f2a8"}.fa-luggage-cart:before{content:"\f59d"}.fa-lungs:before{content:"\f604"}.fa-lungs-virus:before{content:"\f967"}.fa-lyft:before{content:"\f3c3"}.fa-magento:before{content:"\f3c4"}.fa-magic:before{content:"\f0d0"}.fa-magnet:before{content:"\f076"}.fa-mail-bulk:before{content:"\f674"}.fa-mailchimp:before{content:"\f59e"}.fa-male:before{content:"\f183"}.fa-mandalorian:before{content:"\f50f"}.fa-map:before{content:"\f279"}.fa-map-marked:before{content:"\f59f"}.fa-map-marked-alt:before{content:"\f5a0"}.fa-map-marker:before{content:"\f041"}.fa-map-marker-alt:before{content:"\f3c5"}.fa-map-pin:before{content:"\f276"}.fa-map-signs:before{content:"\f277"}.fa-markdown:before{content:"\f60f"}.fa-marker:before{content:"\f5a1"}.fa-mars:before{content:"\f222"}.fa-mars-double:before{content:"\f227"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-h:before{content:"\f22b"}.fa-mars-stroke-v:before{content:"\f22a"}.fa-mask:before{content:"\f6fa"}.fa-mastodon:before{content:"\f4f6"}.fa-maxcdn:before{content:"\f136"}.fa-mdb:before{content:"\f8ca"}.fa-medal:before{content:"\f5a2"}.fa-medapps:before{content:"\f3c6"}.fa-medium:before{content:"\f23a"}.fa-medium-m:before{content:"\f3c7"}.fa-medkit:before{content:"\f0fa"}.fa-medrt:before{content:"\f3c8"}.fa-meetup:before{content:"\f2e0"}.fa-megaport:before{content:"\f5a3"}.fa-meh:before{content:"\f11a"}.fa-meh-blank:before{content:"\f5a4"}.fa-meh-rolling-eyes:before{content:"\f5a5"}.fa-memory:before{content:"\f538"}.fa-mendeley:before{content:"\f7b3"}.fa-menorah:before{content:"\f676"}.fa-mercury:before{content:"\f223"}.fa-meteor:before{content:"\f753"}.fa-microblog:before{content:"\f91a"}.fa-microchip:before{content:"\f2db"}.fa-microphone:before{content:"\f130"}.fa-microphone-alt:before{content:"\f3c9"}.fa-microphone-alt-slash:before{content:"\f539"}.fa-microphone-slash:before{content:"\f131"}.fa-microscope:before{content:"\f610"}.fa-microsoft:before{content:"\f3ca"}.fa-minus:before{content:"\f068"}.fa-minus-circle:before{content:"\f056"}.fa-minus-square:before{content:"\f146"}.fa-mitten:before{content:"\f7b5"}.fa-mix:before{content:"\f3cb"}.fa-mixcloud:before{content:"\f289"}.fa-mixer:before{content:"\f956"}.fa-mizuni:before{content:"\f3cc"}.fa-mobile:before{content:"\f10b"}.fa-mobile-alt:before{content:"\f3cd"}.fa-modx:before{content:"\f285"}.fa-monero:before{content:"\f3d0"}.fa-money-bill:before{content:"\f0d6"}.fa-money-bill-alt:before{content:"\f3d1"}.fa-money-bill-wave:before{content:"\f53a"}.fa-money-bill-wave-alt:before{content:"\f53b"}.fa-money-check:before{content:"\f53c"}.fa-money-check-alt:before{content:"\f53d"}.fa-monument:before{content:"\f5a6"}.fa-moon:before{content:"\f186"}.fa-mortar-pestle:before{content:"\f5a7"}.fa-mosque:before{content:"\f678"}.fa-motorcycle:before{content:"\f21c"}.fa-mountain:before{content:"\f6fc"}.fa-mouse:before{content:"\f8cc"}.fa-mouse-pointer:before{content:"\f245"}.fa-mug-hot:before{content:"\f7b6"}.fa-music:before{content:"\f001"}.fa-napster:before{content:"\f3d2"}.fa-neos:before{content:"\f612"}.fa-network-wired:before{content:"\f6ff"}.fa-neuter:before{content:"\f22c"}.fa-newspaper:before{content:"\f1ea"}.fa-nimblr:before{content:"\f5a8"}.fa-node:before{content:"\f419"}.fa-node-js:before{content:"\f3d3"}.fa-not-equal:before{content:"\f53e"}.fa-notes-medical:before{content:"\f481"}.fa-npm:before{content:"\f3d4"}.fa-ns8:before{content:"\f3d5"}.fa-nutritionix:before{content:"\f3d6"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-odnoklassniki:before{content:"\f263"}.fa-odnoklassniki-square:before{content:"\f264"}.fa-oil-can:before{content:"\f613"}.fa-old-republic:before{content:"\f510"}.fa-om:before{content:"\f679"}.fa-opencart:before{content:"\f23d"}.fa-openid:before{content:"\f19b"}.fa-opera:before{content:"\f26a"}.fa-optin-monster:before{content:"\f23c"}.fa-orcid:before{content:"\f8d2"}.fa-osi:before{content:"\f41a"}.fa-otter:before{content:"\f700"}.fa-outdent:before{content:"\f03b"}.fa-page4:before{content:"\f3d7"}.fa-pagelines:before{content:"\f18c"}.fa-pager:before{content:"\f815"}.fa-paint-brush:before{content:"\f1fc"}.fa-paint-roller:before{content:"\f5aa"}.fa-palette:before{content:"\f53f"}.fa-palfed:before{content:"\f3d8"}.fa-pallet:before{content:"\f482"}.fa-paper-plane:before{content:"\f1d8"}.fa-paperclip:before{content:"\f0c6"}.fa-parachute-box:before{content:"\f4cd"}.fa-paragraph:before{content:"\f1dd"}.fa-parking:before{content:"\f540"}.fa-passport:before{content:"\f5ab"}.fa-pastafarianism:before{content:"\f67b"}.fa-paste:before{content:"\f0ea"}.fa-patreon:before{content:"\f3d9"}.fa-pause:before{content:"\f04c"}.fa-pause-circle:before{content:"\f28b"}.fa-paw:before{content:"\f1b0"}.fa-paypal:before{content:"\f1ed"}.fa-peace:before{content:"\f67c"}.fa-pen:before{content:"\f304"}.fa-pen-alt:before{content:"\f305"}.fa-pen-fancy:before{content:"\f5ac"}.fa-pen-nib:before{content:"\f5ad"}.fa-pen-square:before{content:"\f14b"}.fa-pencil-alt:before{content:"\f303"}.fa-pencil-ruler:before{content:"\f5ae"}.fa-penny-arcade:before{content:"\f704"}.fa-people-arrows:before{content:"\f968"}.fa-people-carry:before{content:"\f4ce"}.fa-pepper-hot:before{content:"\f816"}.fa-percent:before{content:"\f295"}.fa-percentage:before{content:"\f541"}.fa-periscope:before{content:"\f3da"}.fa-person-booth:before{content:"\f756"}.fa-phabricator:before{content:"\f3db"}.fa-phoenix-framework:before{content:"\f3dc"}.fa-phoenix-squadron:before{content:"\f511"}.fa-phone:before{content:"\f095"}.fa-phone-alt:before{content:"\f879"}.fa-phone-slash:before{content:"\f3dd"}.fa-phone-square:before{content:"\f098"}.fa-phone-square-alt:before{content:"\f87b"}.fa-phone-volume:before{content:"\f2a0"}.fa-photo-video:before{content:"\f87c"}.fa-php:before{content:"\f457"}.fa-pied-piper:before{content:"\f2ae"}.fa-pied-piper-alt:before{content:"\f1a8"}.fa-pied-piper-hat:before{content:"\f4e5"}.fa-pied-piper-pp:before{content:"\f1a7"}.fa-pied-piper-square:before{content:"\f91e"}.fa-piggy-bank:before{content:"\f4d3"}.fa-pills:before{content:"\f484"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-p:before{content:"\f231"}.fa-pinterest-square:before{content:"\f0d3"}.fa-pizza-slice:before{content:"\f818"}.fa-place-of-worship:before{content:"\f67f"}.fa-plane:before{content:"\f072"}.fa-plane-arrival:before{content:"\f5af"}.fa-plane-departure:before{content:"\f5b0"}.fa-plane-slash:before{content:"\f969"}.fa-play:before{content:"\f04b"}.fa-play-circle:before{content:"\f144"}.fa-playstation:before{content:"\f3df"}.fa-plug:before{content:"\f1e6"}.fa-plus:before{content:"\f067"}.fa-plus-circle:before{content:"\f055"}.fa-plus-square:before{content:"\f0fe"}.fa-podcast:before{content:"\f2ce"}.fa-poll:before{content:"\f681"}.fa-poll-h:before{content:"\f682"}.fa-poo:before{content:"\f2fe"}.fa-poo-storm:before{content:"\f75a"}.fa-poop:before{content:"\f619"}.fa-portrait:before{content:"\f3e0"}.fa-pound-sign:before{content:"\f154"}.fa-power-off:before{content:"\f011"}.fa-pray:before{content:"\f683"}.fa-praying-hands:before{content:"\f684"}.fa-prescription:before{content:"\f5b1"}.fa-prescription-bottle:before{content:"\f485"}.fa-prescription-bottle-alt:before{content:"\f486"}.fa-print:before{content:"\f02f"}.fa-procedures:before{content:"\f487"}.fa-product-hunt:before{content:"\f288"}.fa-project-diagram:before{content:"\f542"}.fa-pump-medical:before{content:"\f96a"}.fa-pump-soap:before{content:"\f96b"}.fa-pushed:before{content:"\f3e1"}.fa-puzzle-piece:before{content:"\f12e"}.fa-python:before{content:"\f3e2"}.fa-qq:before{content:"\f1d6"}.fa-qrcode:before{content:"\f029"}.fa-question:before{content:"\f128"}.fa-question-circle:before{content:"\f059"}.fa-quidditch:before{content:"\f458"}.fa-quinscape:before{content:"\f459"}.fa-quora:before{content:"\f2c4"}.fa-quote-left:before{content:"\f10d"}.fa-quote-right:before{content:"\f10e"}.fa-quran:before{content:"\f687"}.fa-r-project:before{content:"\f4f7"}.fa-radiation:before{content:"\f7b9"}.fa-radiation-alt:before{content:"\f7ba"}.fa-rainbow:before{content:"\f75b"}.fa-random:before{content:"\f074"}.fa-raspberry-pi:before{content:"\f7bb"}.fa-ravelry:before{content:"\f2d9"}.fa-react:before{content:"\f41b"}.fa-reacteurope:before{content:"\f75d"}.fa-readme:before{content:"\f4d5"}.fa-rebel:before{content:"\f1d0"}.fa-receipt:before{content:"\f543"}.fa-record-vinyl:before{content:"\f8d9"}.fa-recycle:before{content:"\f1b8"}.fa-red-river:before{content:"\f3e3"}.fa-reddit:before{content:"\f1a1"}.fa-reddit-alien:before{content:"\f281"}.fa-reddit-square:before{content:"\f1a2"}.fa-redhat:before{content:"\f7bc"}.fa-redo:before{content:"\f01e"}.fa-redo-alt:before{content:"\f2f9"}.fa-registered:before{content:"\f25d"}.fa-remove-format:before{content:"\f87d"}.fa-renren:before{content:"\f18b"}.fa-reply:before{content:"\f3e5"}.fa-reply-all:before{content:"\f122"}.fa-replyd:before{content:"\f3e6"}.fa-republican:before{content:"\f75e"}.fa-researchgate:before{content:"\f4f8"}.fa-resolving:before{content:"\f3e7"}.fa-restroom:before{content:"\f7bd"}.fa-retweet:before{content:"\f079"}.fa-rev:before{content:"\f5b2"}.fa-ribbon:before{content:"\f4d6"}.fa-ring:before{content:"\f70b"}.fa-road:before{content:"\f018"}.fa-robot:before{content:"\f544"}.fa-rocket:before{content:"\f135"}.fa-rocketchat:before{content:"\f3e8"}.fa-rockrms:before{content:"\f3e9"}.fa-route:before{content:"\f4d7"}.fa-rss:before{content:"\f09e"}.fa-rss-square:before{content:"\f143"}.fa-ruble-sign:before{content:"\f158"}.fa-ruler:before{content:"\f545"}.fa-ruler-combined:before{content:"\f546"}.fa-ruler-horizontal:before{content:"\f547"}.fa-ruler-vertical:before{content:"\f548"}.fa-running:before{content:"\f70c"}.fa-rupee-sign:before{content:"\f156"}.fa-sad-cry:before{content:"\f5b3"}.fa-sad-tear:before{content:"\f5b4"}.fa-safari:before{content:"\f267"}.fa-salesforce:before{content:"\f83b"}.fa-sass:before{content:"\f41e"}.fa-satellite:before{content:"\f7bf"}.fa-satellite-dish:before{content:"\f7c0"}.fa-save:before{content:"\f0c7"}.fa-schlix:before{content:"\f3ea"}.fa-school:before{content:"\f549"}.fa-screwdriver:before{content:"\f54a"}.fa-scribd:before{content:"\f28a"}.fa-scroll:before{content:"\f70e"}.fa-sd-card:before{content:"\f7c2"}.fa-search:before{content:"\f002"}.fa-search-dollar:before{content:"\f688"}.fa-search-location:before{content:"\f689"}.fa-search-minus:before{content:"\f010"}.fa-search-plus:before{content:"\f00e"}.fa-searchengin:before{content:"\f3eb"}.fa-seedling:before{content:"\f4d8"}.fa-sellcast:before{content:"\f2da"}.fa-sellsy:before{content:"\f213"}.fa-server:before{content:"\f233"}.fa-servicestack:before{content:"\f3ec"}.fa-shapes:before{content:"\f61f"}.fa-share:before{content:"\f064"}.fa-share-alt:before{content:"\f1e0"}.fa-share-alt-square:before{content:"\f1e1"}.fa-share-square:before{content:"\f14d"}.fa-shekel-sign:before{content:"\f20b"}.fa-shield-alt:before{content:"\f3ed"}.fa-shield-virus:before{content:"\f96c"}.fa-ship:before{content:"\f21a"}.fa-shipping-fast:before{content:"\f48b"}.fa-shirtsinbulk:before{content:"\f214"}.fa-shoe-prints:before{content:"\f54b"}.fa-shopify:before{content:"\f957"}.fa-shopping-bag:before{content:"\f290"}.fa-shopping-basket:before{content:"\f291"}.fa-shopping-cart:before{content:"\f07a"}.fa-shopware:before{content:"\f5b5"}.fa-shower:before{content:"\f2cc"}.fa-shuttle-van:before{content:"\f5b6"}.fa-sign:before{content:"\f4d9"}.fa-sign-in-alt:before{content:"\f2f6"}.fa-sign-language:before{content:"\f2a7"}.fa-sign-out-alt:before{content:"\f2f5"}.fa-signal:before{content:"\f012"}.fa-signature:before{content:"\f5b7"}.fa-sim-card:before{content:"\f7c4"}.fa-simplybuilt:before{content:"\f215"}.fa-sistrix:before{content:"\f3ee"}.fa-sitemap:before{content:"\f0e8"}.fa-sith:before{content:"\f512"}.fa-skating:before{content:"\f7c5"}.fa-sketch:before{content:"\f7c6"}.fa-skiing:before{content:"\f7c9"}.fa-skiing-nordic:before{content:"\f7ca"}.fa-skull:before{content:"\f54c"}.fa-skull-crossbones:before{content:"\f714"}.fa-skyatlas:before{content:"\f216"}.fa-skype:before{content:"\f17e"}.fa-slack:before{content:"\f198"}.fa-slack-hash:before{content:"\f3ef"}.fa-slash:before{content:"\f715"}.fa-sleigh:before{content:"\f7cc"}.fa-sliders-h:before{content:"\f1de"}.fa-slideshare:before{content:"\f1e7"}.fa-smile:before{content:"\f118"}.fa-smile-beam:before{content:"\f5b8"}.fa-smile-wink:before{content:"\f4da"}.fa-smog:before{content:"\f75f"}.fa-smoking:before{content:"\f48d"}.fa-smoking-ban:before{content:"\f54d"}.fa-sms:before{content:"\f7cd"}.fa-snapchat:before{content:"\f2ab"}.fa-snapchat-ghost:before{content:"\f2ac"}.fa-snapchat-square:before{content:"\f2ad"}.fa-snowboarding:before{content:"\f7ce"}.fa-snowflake:before{content:"\f2dc"}.fa-snowman:before{content:"\f7d0"}.fa-snowplow:before{content:"\f7d2"}.fa-soap:before{content:"\f96e"}.fa-socks:before{content:"\f696"}.fa-solar-panel:before{content:"\f5ba"}.fa-sort:before{content:"\f0dc"}.fa-sort-alpha-down:before{content:"\f15d"}.fa-sort-alpha-down-alt:before{content:"\f881"}.fa-sort-alpha-up:before{content:"\f15e"}.fa-sort-alpha-up-alt:before{content:"\f882"}.fa-sort-amount-down:before{content:"\f160"}.fa-sort-amount-down-alt:before{content:"\f884"}.fa-sort-amount-up:before{content:"\f161"}.fa-sort-amount-up-alt:before{content:"\f885"}.fa-sort-down:before{content:"\f0dd"}.fa-sort-numeric-down:before{content:"\f162"}.fa-sort-numeric-down-alt:before{content:"\f886"}.fa-sort-numeric-up:before{content:"\f163"}.fa-sort-numeric-up-alt:before{content:"\f887"}.fa-sort-up:before{content:"\f0de"}.fa-soundcloud:before{content:"\f1be"}.fa-sourcetree:before{content:"\f7d3"}.fa-spa:before{content:"\f5bb"}.fa-space-shuttle:before{content:"\f197"}.fa-speakap:before{content:"\f3f3"}.fa-speaker-deck:before{content:"\f83c"}.fa-spell-check:before{content:"\f891"}.fa-spider:before{content:"\f717"}.fa-spinner:before{content:"\f110"}.fa-splotch:before{content:"\f5bc"}.fa-spotify:before{content:"\f1bc"}.fa-spray-can:before{content:"\f5bd"}.fa-square:before{content:"\f0c8"}.fa-square-full:before{content:"\f45c"}.fa-square-root-alt:before{content:"\f698"}.fa-squarespace:before{content:"\f5be"}.fa-stack-exchange:before{content:"\f18d"}.fa-stack-overflow:before{content:"\f16c"}.fa-stackpath:before{content:"\f842"}.fa-stamp:before{content:"\f5bf"}.fa-star:before{content:"\f005"}.fa-star-and-crescent:before{content:"\f699"}.fa-star-half:before{content:"\f089"}.fa-star-half-alt:before{content:"\f5c0"}.fa-star-of-david:before{content:"\f69a"}.fa-star-of-life:before{content:"\f621"}.fa-staylinked:before{content:"\f3f5"}.fa-steam:before{content:"\f1b6"}.fa-steam-square:before{content:"\f1b7"}.fa-steam-symbol:before{content:"\f3f6"}.fa-step-backward:before{content:"\f048"}.fa-step-forward:before{content:"\f051"}.fa-stethoscope:before{content:"\f0f1"}.fa-sticker-mule:before{content:"\f3f7"}.fa-sticky-note:before{content:"\f249"}.fa-stop:before{content:"\f04d"}.fa-stop-circle:before{content:"\f28d"}.fa-stopwatch:before{content:"\f2f2"}.fa-stopwatch-20:before{content:"\f96f"}.fa-store:before{content:"\f54e"}.fa-store-alt:before{content:"\f54f"}.fa-store-alt-slash:before{content:"\f970"}.fa-store-slash:before{content:"\f971"}.fa-strava:before{content:"\f428"}.fa-stream:before{content:"\f550"}.fa-street-view:before{content:"\f21d"}.fa-strikethrough:before{content:"\f0cc"}.fa-stripe:before{content:"\f429"}.fa-stripe-s:before{content:"\f42a"}.fa-stroopwafel:before{content:"\f551"}.fa-studiovinari:before{content:"\f3f8"}.fa-stumbleupon:before{content:"\f1a4"}.fa-stumbleupon-circle:before{content:"\f1a3"}.fa-subscript:before{content:"\f12c"}.fa-subway:before{content:"\f239"}.fa-suitcase:before{content:"\f0f2"}.fa-suitcase-rolling:before{content:"\f5c1"}.fa-sun:before{content:"\f185"}.fa-superpowers:before{content:"\f2dd"}.fa-superscript:before{content:"\f12b"}.fa-supple:before{content:"\f3f9"}.fa-surprise:before{content:"\f5c2"}.fa-suse:before{content:"\f7d6"}.fa-swatchbook:before{content:"\f5c3"}.fa-swift:before{content:"\f8e1"}.fa-swimmer:before{content:"\f5c4"}.fa-swimming-pool:before{content:"\f5c5"}.fa-symfony:before{content:"\f83d"}.fa-synagogue:before{content:"\f69b"}.fa-sync:before{content:"\f021"}.fa-sync-alt:before{content:"\f2f1"}.fa-syringe:before{content:"\f48e"}.fa-table:before{content:"\f0ce"}.fa-table-tennis:before{content:"\f45d"}.fa-tablet:before{content:"\f10a"}.fa-tablet-alt:before{content:"\f3fa"}.fa-tablets:before{content:"\f490"}.fa-tachometer-alt:before{content:"\f3fd"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-tape:before{content:"\f4db"}.fa-tasks:before{content:"\f0ae"}.fa-taxi:before{content:"\f1ba"}.fa-teamspeak:before{content:"\f4f9"}.fa-teeth:before{content:"\f62e"}.fa-teeth-open:before{content:"\f62f"}.fa-telegram:before{content:"\f2c6"}.fa-telegram-plane:before{content:"\f3fe"}.fa-temperature-high:before{content:"\f769"}.fa-temperature-low:before{content:"\f76b"}.fa-tencent-weibo:before{content:"\f1d5"}.fa-tenge:before{content:"\f7d7"}.fa-terminal:before{content:"\f120"}.fa-text-height:before{content:"\f034"}.fa-text-width:before{content:"\f035"}.fa-th:before{content:"\f00a"}.fa-th-large:before{content:"\f009"}.fa-th-list:before{content:"\f00b"}.fa-the-red-yeti:before{content:"\f69d"}.fa-theater-masks:before{content:"\f630"}.fa-themeco:before{content:"\f5c6"}.fa-themeisle:before{content:"\f2b2"}.fa-thermometer:before{content:"\f491"}.fa-thermometer-empty:before{content:"\f2cb"}.fa-thermometer-full:before{content:"\f2c7"}.fa-thermometer-half:before{content:"\f2c9"}.fa-thermometer-quarter:before{content:"\f2ca"}.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-think-peaks:before{content:"\f731"}.fa-thumbs-down:before{content:"\f165"}.fa-thumbs-up:before{content:"\f164"}.fa-thumbtack:before{content:"\f08d"}.fa-ticket-alt:before{content:"\f3ff"}.fa-times:before{content:"\f00d"}.fa-times-circle:before{content:"\f057"}.fa-tint:before{content:"\f043"}.fa-tint-slash:before{content:"\f5c7"}.fa-tired:before{content:"\f5c8"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-toilet:before{content:"\f7d8"}.fa-toilet-paper:before{content:"\f71e"}.fa-toilet-paper-slash:before{content:"\f972"}.fa-toolbox:before{content:"\f552"}.fa-tools:before{content:"\f7d9"}.fa-tooth:before{content:"\f5c9"}.fa-torah:before{content:"\f6a0"}.fa-torii-gate:before{content:"\f6a1"}.fa-tractor:before{content:"\f722"}.fa-trade-federation:before{content:"\f513"}.fa-trademark:before{content:"\f25c"}.fa-traffic-light:before{content:"\f637"}.fa-trailer:before{content:"\f941"}.fa-train:before{content:"\f238"}.fa-tram:before{content:"\f7da"}.fa-transgender:before{content:"\f224"}.fa-transgender-alt:before{content:"\f225"}.fa-trash:before{content:"\f1f8"}.fa-trash-alt:before{content:"\f2ed"}.fa-trash-restore:before{content:"\f829"}.fa-trash-restore-alt:before{content:"\f82a"}.fa-tree:before{content:"\f1bb"}.fa-trello:before{content:"\f181"}.fa-tripadvisor:before{content:"\f262"}.fa-trophy:before{content:"\f091"}.fa-truck:before{content:"\f0d1"}.fa-truck-loading:before{content:"\f4de"}.fa-truck-monster:before{content:"\f63b"}.fa-truck-moving:before{content:"\f4df"}.fa-truck-pickup:before{content:"\f63c"}.fa-tshirt:before{content:"\f553"}.fa-tty:before{content:"\f1e4"}.fa-tumblr:before{content:"\f173"}.fa-tumblr-square:before{content:"\f174"}.fa-tv:before{content:"\f26c"}.fa-twitch:before{content:"\f1e8"}.fa-twitter:before{content:"\f099"}.fa-twitter-square:before{content:"\f081"}.fa-typo3:before{content:"\f42b"}.fa-uber:before{content:"\f402"}.fa-ubuntu:before{content:"\f7df"}.fa-uikit:before{content:"\f403"}.fa-umbraco:before{content:"\f8e8"}.fa-umbrella:before{content:"\f0e9"}.fa-umbrella-beach:before{content:"\f5ca"}.fa-underline:before{content:"\f0cd"}.fa-undo:before{content:"\f0e2"}.fa-undo-alt:before{content:"\f2ea"}.fa-uniregistry:before{content:"\f404"}.fa-unity:before{content:"\f949"}.fa-universal-access:before{content:"\f29a"}.fa-university:before{content:"\f19c"}.fa-unlink:before{content:"\f127"}.fa-unlock:before{content:"\f09c"}.fa-unlock-alt:before{content:"\f13e"}.fa-untappd:before{content:"\f405"}.fa-upload:before{content:"\f093"}.fa-ups:before{content:"\f7e0"}.fa-usb:before{content:"\f287"}.fa-user:before{content:"\f007"}.fa-user-alt:before{content:"\f406"}.fa-user-alt-slash:before{content:"\f4fa"}.fa-user-astronaut:before{content:"\f4fb"}.fa-user-check:before{content:"\f4fc"}.fa-user-circle:before{content:"\f2bd"}.fa-user-clock:before{content:"\f4fd"}.fa-user-cog:before{content:"\f4fe"}.fa-user-edit:before{content:"\f4ff"}.fa-user-friends:before{content:"\f500"}.fa-user-graduate:before{content:"\f501"}.fa-user-injured:before{content:"\f728"}.fa-user-lock:before{content:"\f502"}.fa-user-md:before{content:"\f0f0"}.fa-user-minus:before{content:"\f503"}.fa-user-ninja:before{content:"\f504"}.fa-user-nurse:before{content:"\f82f"}.fa-user-plus:before{content:"\f234"}.fa-user-secret:before{content:"\f21b"}.fa-user-shield:before{content:"\f505"}.fa-user-slash:before{content:"\f506"}.fa-user-tag:before{content:"\f507"}.fa-user-tie:before{content:"\f508"}.fa-user-times:before{content:"\f235"}.fa-users:before{content:"\f0c0"}.fa-users-cog:before{content:"\f509"}.fa-usps:before{content:"\f7e1"}.fa-ussunnah:before{content:"\f407"}.fa-utensil-spoon:before{content:"\f2e5"}.fa-utensils:before{content:"\f2e7"}.fa-vaadin:before{content:"\f408"}.fa-vector-square:before{content:"\f5cb"}.fa-venus:before{content:"\f221"}.fa-venus-double:before{content:"\f226"}.fa-venus-mars:before{content:"\f228"}.fa-viacoin:before{content:"\f237"}.fa-viadeo:before{content:"\f2a9"}.fa-viadeo-square:before{content:"\f2aa"}.fa-vial:before{content:"\f492"}.fa-vials:before{content:"\f493"}.fa-viber:before{content:"\f409"}.fa-video:before{content:"\f03d"}.fa-video-slash:before{content:"\f4e2"}.fa-vihara:before{content:"\f6a7"}.fa-vimeo:before{content:"\f40a"}.fa-vimeo-square:before{content:"\f194"}.fa-vimeo-v:before{content:"\f27d"}.fa-vine:before{content:"\f1ca"}.fa-virus:before{content:"\f974"}.fa-virus-slash:before{content:"\f975"}.fa-viruses:before{content:"\f976"}.fa-vk:before{content:"\f189"}.fa-vnv:before{content:"\f40b"}.fa-voicemail:before{content:"\f897"}.fa-volleyball-ball:before{content:"\f45f"}.fa-volume-down:before{content:"\f027"}.fa-volume-mute:before{content:"\f6a9"}.fa-volume-off:before{content:"\f026"}.fa-volume-up:before{content:"\f028"}.fa-vote-yea:before{content:"\f772"}.fa-vr-cardboard:before{content:"\f729"}.fa-vuejs:before{content:"\f41f"}.fa-walking:before{content:"\f554"}.fa-wallet:before{content:"\f555"}.fa-warehouse:before{content:"\f494"}.fa-water:before{content:"\f773"}.fa-wave-square:before{content:"\f83e"}.fa-waze:before{content:"\f83f"}.fa-weebly:before{content:"\f5cc"}.fa-weibo:before{content:"\f18a"}.fa-weight:before{content:"\f496"}.fa-weight-hanging:before{content:"\f5cd"}.fa-weixin:before{content:"\f1d7"}.fa-whatsapp:before{content:"\f232"}.fa-whatsapp-square:before{content:"\f40c"}.fa-wheelchair:before{content:"\f193"}.fa-whmcs:before{content:"\f40d"}.fa-wifi:before{content:"\f1eb"}.fa-wikipedia-w:before{content:"\f266"}.fa-wind:before{content:"\f72e"}.fa-window-close:before{content:"\f410"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-windows:before{content:"\f17a"}.fa-wine-bottle:before{content:"\f72f"}.fa-wine-glass:before{content:"\f4e3"}.fa-wine-glass-alt:before{content:"\f5ce"}.fa-wix:before{content:"\f5cf"}.fa-wizards-of-the-coast:before{content:"\f730"}.fa-wolf-pack-battalion:before{content:"\f514"}.fa-won-sign:before{content:"\f159"}.fa-wordpress:before{content:"\f19a"}.fa-wordpress-simple:before{content:"\f411"}.fa-wpbeginner:before{content:"\f297"}.fa-wpexplorer:before{content:"\f2de"}.fa-wpforms:before{content:"\f298"}.fa-wpressr:before{content:"\f3e4"}.fa-wrench:before{content:"\f0ad"}.fa-x-ray:before{content:"\f497"}.fa-xbox:before{content:"\f412"}.fa-xing:before{content:"\f168"}.fa-xing-square:before{content:"\f169"}.fa-y-combinator:before{content:"\f23b"}.fa-yahoo:before{content:"\f19e"}.fa-yammer:before{content:"\f840"}.fa-yandex:before{content:"\f413"}.fa-yandex-international:before{content:"\f414"}.fa-yarn:before{content:"\f7e3"}.fa-yelp:before{content:"\f1e9"}.fa-yen-sign:before{content:"\f157"}.fa-yin-yang:before{content:"\f6ad"}.fa-yoast:before{content:"\f2b1"}.fa-youtube:before{content:"\f167"}.fa-youtube-square:before{content:"\f431"}.fa-zhihu:before{content:"\f63f"}.sr-only{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.sr-only-focusable:active,.sr-only-focusable:focus{clip:auto;height:auto;margin:0;overflow:visible;position:static;width:auto}
\ No newline at end of file
+.fa{font-family:var(--fa-style-family,"Font Awesome 6 Free");font-weight:var(--fa-style,900)}.fa,.fa-brands,.fa-duotone,.fa-light,.fa-regular,.fa-solid,.fa-thin,.fab,.fad,.fal,.far,.fas,.fat{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;display:var(--fa-display,inline-block);font-style:normal;font-variant:normal;line-height:1;text-rendering:auto}.fa-1x{font-size:1em}.fa-2x{font-size:2em}.fa-3x{font-size:3em}.fa-4x{font-size:4em}.fa-5x{font-size:5em}.fa-6x{font-size:6em}.fa-7x{font-size:7em}.fa-8x{font-size:8em}.fa-9x{font-size:9em}.fa-10x{font-size:10em}.fa-2xs{font-size:.625em;line-height:.1em;vertical-align:.225em}.fa-xs{font-size:.75em;line-height:.08333em;vertical-align:.125em}.fa-sm{font-size:.875em;line-height:.07143em;vertical-align:.05357em}.fa-lg{font-size:1.25em;line-height:.05em;vertical-align:-.075em}.fa-xl{font-size:1.5em;line-height:.04167em;vertical-align:-.125em}.fa-2xl{font-size:2em;line-height:.03125em;vertical-align:-.1875em}.fa-fw{text-align:center;width:1.25em}.fa-ul{list-style-type:none;margin-left:var(--fa-li-margin,2.5em);padding-left:0}.fa-ul>li{position:relative}.fa-li{left:calc(var(--fa-li-width, 2em)*-1);position:absolute;text-align:center;width:var(--fa-li-width,2em);line-height:inherit}.fa-border{border-radius:var(--fa-border-radius,.1em);border:var(--fa-border-width,.08em) var(--fa-border-style,solid) var(--fa-border-color,#eee);padding:var(--fa-border-padding,.2em .25em .15em)}.fa-pull-left{float:left;margin-right:var(--fa-pull-margin,.3em)}.fa-pull-right{float:right;margin-left:var(--fa-pull-margin,.3em)}.fa-beat{-webkit-animation-name:fa-beat;animation-name:fa-beat;-webkit-animation-delay:var(--fa-animation-delay,0);animation-delay:var(--fa-animation-delay,0);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-bounce{-webkit-animation-name:fa-bounce;animation-name:fa-bounce;-webkit-animation-delay:var(--fa-animation-delay,0);animation-delay:var(--fa-animation-delay,0);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.28,.84,.42,1))}.fa-fade{-webkit-animation-name:fa-fade;animation-name:fa-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-beat-fade,.fa-fade{-webkit-animation-delay:var(--fa-animation-delay,0);animation-delay:var(--fa-animation-delay,0);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s)}.fa-beat-fade{-webkit-animation-name:fa-beat-fade;animation-name:fa-beat-fade;-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1));animation-timing-function:var(--fa-animation-timing,cubic-bezier(.4,0,.6,1))}.fa-flip{-webkit-animation-name:fa-flip;animation-name:fa-flip;-webkit-animation-delay:var(--fa-animation-delay,0);animation-delay:var(--fa-animation-delay,0);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,ease-in-out);animation-timing-function:var(--fa-animation-timing,ease-in-out)}.fa-shake{-webkit-animation-name:fa-shake;animation-name:fa-shake;-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,linear);animation-timing-function:var(--fa-animation-timing,linear)}.fa-shake,.fa-spin{-webkit-animation-delay:var(--fa-animation-delay,0);animation-delay:var(--fa-animation-delay,0);-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal)}.fa-spin{-webkit-animation-name:fa-spin;animation-name:fa-spin;-webkit-animation-duration:var(--fa-animation-duration,2s);animation-duration:var(--fa-animation-duration,2s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,linear);animation-timing-function:var(--fa-animation-timing,linear)}.fa-spin-reverse{--fa-animation-direction:reverse}.fa-pulse,.fa-spin-pulse{-webkit-animation-name:fa-spin;animation-name:fa-spin;-webkit-animation-direction:var(--fa-animation-direction,normal);animation-direction:var(--fa-animation-direction,normal);-webkit-animation-duration:var(--fa-animation-duration,1s);animation-duration:var(--fa-animation-duration,1s);-webkit-animation-iteration-count:var(--fa-animation-iteration-count,infinite);animation-iteration-count:var(--fa-animation-iteration-count,infinite);-webkit-animation-timing-function:var(--fa-animation-timing,steps(8));animation-timing-function:var(--fa-animation-timing,steps(8))}@media (prefers-reduced-motion:reduce){.fa-beat,.fa-beat-fade,.fa-bounce,.fa-fade,.fa-flip,.fa-pulse,.fa-shake,.fa-spin,.fa-spin-pulse{-webkit-animation-delay:-1ms;animation-delay:-1ms;-webkit-animation-duration:1ms;animation-duration:1ms;-webkit-animation-iteration-count:1;animation-iteration-count:1;transition-delay:0s;transition-duration:0s}}@-webkit-keyframes fa-beat{0%,90%{-webkit-transform:scale(1);transform:scale(1)}45%{-webkit-transform:scale(var(--fa-beat-scale,1.25));transform:scale(var(--fa-beat-scale,1.25))}}@keyframes fa-beat{0%,90%{-webkit-transform:scale(1);transform:scale(1)}45%{-webkit-transform:scale(var(--fa-beat-scale,1.25));transform:scale(var(--fa-beat-scale,1.25))}}@-webkit-keyframes fa-bounce{0%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}10%{-webkit-transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0);transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0)}30%{-webkit-transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em));transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em))}50%{-webkit-transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0);transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0)}57%{-webkit-transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em));transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em))}64%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}to{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}}@keyframes fa-bounce{0%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}10%{-webkit-transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0);transform:scale(var(--fa-bounce-start-scale-x,1.1),var(--fa-bounce-start-scale-y,.9)) translateY(0)}30%{-webkit-transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em));transform:scale(var(--fa-bounce-jump-scale-x,.9),var(--fa-bounce-jump-scale-y,1.1)) translateY(var(--fa-bounce-height,-.5em))}50%{-webkit-transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0);transform:scale(var(--fa-bounce-land-scale-x,1.05),var(--fa-bounce-land-scale-y,.95)) translateY(0)}57%{-webkit-transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em));transform:scale(1) translateY(var(--fa-bounce-rebound,-.125em))}64%{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}to{-webkit-transform:scale(1) translateY(0);transform:scale(1) translateY(0)}}@-webkit-keyframes fa-fade{50%{opacity:var(--fa-fade-opacity,.4)}}@keyframes fa-fade{50%{opacity:var(--fa-fade-opacity,.4)}}@-webkit-keyframes fa-beat-fade{0%,to{opacity:var(--fa-beat-fade-opacity,.4);-webkit-transform:scale(1);transform:scale(1)}50%{opacity:1;-webkit-transform:scale(var(--fa-beat-fade-scale,1.125));transform:scale(var(--fa-beat-fade-scale,1.125))}}@keyframes fa-beat-fade{0%,to{opacity:var(--fa-beat-fade-opacity,.4);-webkit-transform:scale(1);transform:scale(1)}50%{opacity:1;-webkit-transform:scale(var(--fa-beat-fade-scale,1.125));transform:scale(var(--fa-beat-fade-scale,1.125))}}@-webkit-keyframes fa-flip{50%{-webkit-transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg));transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg))}}@keyframes fa-flip{50%{-webkit-transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg));transform:rotate3d(var(--fa-flip-x,0),var(--fa-flip-y,1),var(--fa-flip-z,0),var(--fa-flip-angle,-180deg))}}@-webkit-keyframes fa-shake{0%{-webkit-transform:rotate(-15deg);transform:rotate(-15deg)}4%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}8%,24%{-webkit-transform:rotate(-18deg);transform:rotate(-18deg)}12%,28%{-webkit-transform:rotate(18deg);transform:rotate(18deg)}16%{-webkit-transform:rotate(-22deg);transform:rotate(-22deg)}20%{-webkit-transform:rotate(22deg);transform:rotate(22deg)}32%{-webkit-transform:rotate(-12deg);transform:rotate(-12deg)}36%{-webkit-transform:rotate(12deg);transform:rotate(12deg)}40%,to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}@keyframes fa-shake{0%{-webkit-transform:rotate(-15deg);transform:rotate(-15deg)}4%{-webkit-transform:rotate(15deg);transform:rotate(15deg)}8%,24%{-webkit-transform:rotate(-18deg);transform:rotate(-18deg)}12%,28%{-webkit-transform:rotate(18deg);transform:rotate(18deg)}16%{-webkit-transform:rotate(-22deg);transform:rotate(-22deg)}20%{-webkit-transform:rotate(22deg);transform:rotate(22deg)}32%{-webkit-transform:rotate(-12deg);transform:rotate(-12deg)}36%{-webkit-transform:rotate(12deg);transform:rotate(12deg)}40%,to{-webkit-transform:rotate(0deg);transform:rotate(0deg)}}@-webkit-keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}@keyframes fa-spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(1turn);transform:rotate(1turn)}}.fa-rotate-90{-webkit-transform:rotate(90deg);transform:rotate(90deg)}.fa-rotate-180{-webkit-transform:rotate(180deg);transform:rotate(180deg)}.fa-rotate-270{-webkit-transform:rotate(270deg);transform:rotate(270deg)}.fa-flip-horizontal{-webkit-transform:scaleX(-1);transform:scaleX(-1)}.fa-flip-vertical{-webkit-transform:scaleY(-1);transform:scaleY(-1)}.fa-flip-both,.fa-flip-horizontal.fa-flip-vertical{-webkit-transform:scale(-1);transform:scale(-1)}.fa-rotate-by{-webkit-transform:rotate(var(--fa-rotate-angle,none));transform:rotate(var(--fa-rotate-angle,none))}.fa-stack{display:inline-block;height:2em;line-height:2em;position:relative;vertical-align:middle;width:2.5em}.fa-stack-1x,.fa-stack-2x{left:0;position:absolute;text-align:center;width:100%;z-index:var(--fa-stack-z-index,auto)}.fa-stack-1x{line-height:inherit}.fa-stack-2x{font-size:2em}.fa-inverse{color:var(--fa-inverse,#fff)}.fa-0:before{content:"\30"}.fa-1:before{content:"\31"}.fa-2:before{content:"\32"}.fa-3:before{content:"\33"}.fa-4:before{content:"\34"}.fa-5:before{content:"\35"}.fa-6:before{content:"\36"}.fa-7:before{content:"\37"}.fa-8:before{content:"\38"}.fa-9:before{content:"\39"}.fa-a:before{content:"\41"}.fa-address-book:before,.fa-contact-book:before{content:"\f2b9"}.fa-address-card:before,.fa-contact-card:before,.fa-vcard:before{content:"\f2bb"}.fa-align-center:before{content:"\f037"}.fa-align-justify:before{content:"\f039"}.fa-align-left:before{content:"\f036"}.fa-align-right:before{content:"\f038"}.fa-anchor:before{content:"\f13d"}.fa-angle-down:before{content:"\f107"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"}.fa-angle-up:before{content:"\f106"}.fa-angle-double-down:before,.fa-angles-down:before{content:"\f103"}.fa-angle-double-left:before,.fa-angles-left:before{content:"\f100"}.fa-angle-double-right:before,.fa-angles-right:before{content:"\f101"}.fa-angle-double-up:before,.fa-angles-up:before{content:"\f102"}.fa-ankh:before{content:"\f644"}.fa-apple-alt:before,.fa-apple-whole:before{content:"\f5d1"}.fa-archway:before{content:"\f557"}.fa-arrow-down:before{content:"\f063"}.fa-arrow-down-1-9:before,.fa-sort-numeric-asc:before,.fa-sort-numeric-down:before{content:"\f162"}.fa-arrow-down-9-1:before,.fa-sort-numeric-desc:before,.fa-sort-numeric-down-alt:before{content:"\f886"}.fa-arrow-down-a-z:before,.fa-sort-alpha-asc:before,.fa-sort-alpha-down:before{content:"\f15d"}.fa-arrow-down-long:before,.fa-long-arrow-down:before{content:"\f175"}.fa-arrow-down-short-wide:before,.fa-sort-amount-desc:before,.fa-sort-amount-down-alt:before{content:"\f884"}.fa-arrow-down-wide-short:before,.fa-sort-amount-asc:before,.fa-sort-amount-down:before{content:"\f160"}.fa-arrow-down-z-a:before,.fa-sort-alpha-desc:before,.fa-sort-alpha-down-alt:before{content:"\f881"}.fa-arrow-left:before{content:"\f060"}.fa-arrow-left-long:before,.fa-long-arrow-left:before{content:"\f177"}.fa-arrow-pointer:before,.fa-mouse-pointer:before{content:"\f245"}.fa-arrow-right:before{content:"\f061"}.fa-arrow-right-arrow-left:before,.fa-exchange:before{content:"\f0ec"}.fa-arrow-right-from-bracket:before,.fa-sign-out:before{content:"\f08b"}.fa-arrow-right-long:before,.fa-long-arrow-right:before{content:"\f178"}.fa-arrow-right-to-bracket:before,.fa-sign-in:before{content:"\f090"}.fa-arrow-left-rotate:before,.fa-arrow-rotate-back:before,.fa-arrow-rotate-backward:before,.fa-arrow-rotate-left:before,.fa-undo:before{content:"\f0e2"}.fa-arrow-right-rotate:before,.fa-arrow-rotate-forward:before,.fa-arrow-rotate-right:before,.fa-redo:before{content:"\f01e"}.fa-arrow-trend-down:before{content:"\e097"}.fa-arrow-trend-up:before{content:"\e098"}.fa-arrow-turn-down:before,.fa-level-down:before{content:"\f149"}.fa-arrow-turn-up:before,.fa-level-up:before{content:"\f148"}.fa-arrow-up:before{content:"\f062"}.fa-arrow-up-1-9:before,.fa-sort-numeric-up:before{content:"\f163"}.fa-arrow-up-9-1:before,.fa-sort-numeric-up-alt:before{content:"\f887"}.fa-arrow-up-a-z:before,.fa-sort-alpha-up:before{content:"\f15e"}.fa-arrow-up-from-bracket:before{content:"\e09a"}.fa-arrow-up-long:before,.fa-long-arrow-up:before{content:"\f176"}.fa-arrow-up-right-from-square:before,.fa-external-link:before{content:"\f08e"}.fa-arrow-up-short-wide:before,.fa-sort-amount-up-alt:before{content:"\f885"}.fa-arrow-up-wide-short:before,.fa-sort-amount-up:before{content:"\f161"}.fa-arrow-up-z-a:before,.fa-sort-alpha-up-alt:before{content:"\f882"}.fa-arrows-h:before,.fa-arrows-left-right:before{content:"\f07e"}.fa-arrows-rotate:before,.fa-refresh:before,.fa-sync:before{content:"\f021"}.fa-arrows-up-down:before,.fa-arrows-v:before{content:"\f07d"}.fa-arrows-up-down-left-right:before,.fa-arrows:before{content:"\f047"}.fa-asterisk:before{content:"\2a"}.fa-at:before{content:"\40"}.fa-atom:before{content:"\f5d2"}.fa-audio-description:before{content:"\f29e"}.fa-austral-sign:before{content:"\e0a9"}.fa-award:before{content:"\f559"}.fa-b:before{content:"\42"}.fa-baby:before{content:"\f77c"}.fa-baby-carriage:before,.fa-carriage-baby:before{content:"\f77d"}.fa-backward:before{content:"\f04a"}.fa-backward-fast:before,.fa-fast-backward:before{content:"\f049"}.fa-backward-step:before,.fa-step-backward:before{content:"\f048"}.fa-bacon:before{content:"\f7e5"}.fa-bacteria:before{content:"\e059"}.fa-bacterium:before{content:"\e05a"}.fa-bag-shopping:before,.fa-shopping-bag:before{content:"\f290"}.fa-bahai:before{content:"\f666"}.fa-baht-sign:before{content:"\e0ac"}.fa-ban:before,.fa-cancel:before{content:"\f05e"}.fa-ban-smoking:before,.fa-smoking-ban:before{content:"\f54d"}.fa-band-aid:before,.fa-bandage:before{content:"\f462"}.fa-barcode:before{content:"\f02a"}.fa-bars:before,.fa-navicon:before{content:"\f0c9"}.fa-bars-progress:before,.fa-tasks-alt:before{content:"\f828"}.fa-bars-staggered:before,.fa-reorder:before,.fa-stream:before{content:"\f550"}.fa-baseball-ball:before,.fa-baseball:before{content:"\f433"}.fa-baseball-bat-ball:before{content:"\f432"}.fa-basket-shopping:before,.fa-shopping-basket:before{content:"\f291"}.fa-basketball-ball:before,.fa-basketball:before{content:"\f434"}.fa-bath:before,.fa-bathtub:before{content:"\f2cd"}.fa-battery-0:before,.fa-battery-empty:before{content:"\f244"}.fa-battery-5:before,.fa-battery-full:before,.fa-battery:before{content:"\f240"}.fa-battery-3:before,.fa-battery-half:before{content:"\f242"}.fa-battery-2:before,.fa-battery-quarter:before{content:"\f243"}.fa-battery-4:before,.fa-battery-three-quarters:before{content:"\f241"}.fa-bed:before{content:"\f236"}.fa-bed-pulse:before,.fa-procedures:before{content:"\f487"}.fa-beer-mug-empty:before,.fa-beer:before{content:"\f0fc"}.fa-bell:before{content:"\f0f3"}.fa-bell-concierge:before,.fa-concierge-bell:before{content:"\f562"}.fa-bell-slash:before{content:"\f1f6"}.fa-bezier-curve:before{content:"\f55b"}.fa-bicycle:before{content:"\f206"}.fa-binoculars:before{content:"\f1e5"}.fa-biohazard:before{content:"\f780"}.fa-bitcoin-sign:before{content:"\e0b4"}.fa-blender:before{content:"\f517"}.fa-blender-phone:before{content:"\f6b6"}.fa-blog:before{content:"\f781"}.fa-bold:before{content:"\f032"}.fa-bolt:before,.fa-zap:before{content:"\f0e7"}.fa-bolt-lightning:before{content:"\e0b7"}.fa-bomb:before{content:"\f1e2"}.fa-bone:before{content:"\f5d7"}.fa-bong:before{content:"\f55c"}.fa-book:before{content:"\f02d"}.fa-atlas:before,.fa-book-atlas:before{content:"\f558"}.fa-bible:before,.fa-book-bible:before{content:"\f647"}.fa-book-journal-whills:before,.fa-journal-whills:before{content:"\f66a"}.fa-book-medical:before{content:"\f7e6"}.fa-book-open:before{content:"\f518"}.fa-book-open-reader:before,.fa-book-reader:before{content:"\f5da"}.fa-book-quran:before,.fa-quran:before{content:"\f687"}.fa-book-dead:before,.fa-book-skull:before{content:"\f6b7"}.fa-bookmark:before{content:"\f02e"}.fa-border-all:before{content:"\f84c"}.fa-border-none:before{content:"\f850"}.fa-border-style:before,.fa-border-top-left:before{content:"\f853"}.fa-bowling-ball:before{content:"\f436"}.fa-box:before{content:"\f466"}.fa-archive:before,.fa-box-archive:before{content:"\f187"}.fa-box-open:before{content:"\f49e"}.fa-box-tissue:before{content:"\e05b"}.fa-boxes-alt:before,.fa-boxes-stacked:before,.fa-boxes:before{content:"\f468"}.fa-braille:before{content:"\f2a1"}.fa-brain:before{content:"\f5dc"}.fa-brazilian-real-sign:before{content:"\e46c"}.fa-bread-slice:before{content:"\f7ec"}.fa-briefcase:before{content:"\f0b1"}.fa-briefcase-medical:before{content:"\f469"}.fa-broom:before{content:"\f51a"}.fa-broom-ball:before,.fa-quidditch-broom-ball:before,.fa-quidditch:before{content:"\f458"}.fa-brush:before{content:"\f55d"}.fa-bug:before{content:"\f188"}.fa-bug-slash:before{content:"\e490"}.fa-building:before{content:"\f1ad"}.fa-bank:before,.fa-building-columns:before,.fa-institution:before,.fa-museum:before,.fa-university:before{content:"\f19c"}.fa-bullhorn:before{content:"\f0a1"}.fa-bullseye:before{content:"\f140"}.fa-burger:before,.fa-hamburger:before{content:"\f805"}.fa-bus:before{content:"\f207"}.fa-bus-alt:before,.fa-bus-simple:before{content:"\f55e"}.fa-briefcase-clock:before,.fa-business-time:before{content:"\f64a"}.fa-c:before{content:"\43"}.fa-birthday-cake:before,.fa-cake-candles:before,.fa-cake:before{content:"\f1fd"}.fa-calculator:before{content:"\f1ec"}.fa-calendar:before{content:"\f133"}.fa-calendar-check:before{content:"\f274"}.fa-calendar-day:before{content:"\f783"}.fa-calendar-alt:before,.fa-calendar-days:before{content:"\f073"}.fa-calendar-minus:before{content:"\f272"}.fa-calendar-plus:before{content:"\f271"}.fa-calendar-week:before{content:"\f784"}.fa-calendar-times:before,.fa-calendar-xmark:before{content:"\f273"}.fa-camera-alt:before,.fa-camera:before{content:"\f030"}.fa-camera-retro:before{content:"\f083"}.fa-camera-rotate:before{content:"\e0d8"}.fa-campground:before{content:"\f6bb"}.fa-candy-cane:before{content:"\f786"}.fa-cannabis:before{content:"\f55f"}.fa-capsules:before{content:"\f46b"}.fa-automobile:before,.fa-car:before{content:"\f1b9"}.fa-battery-car:before,.fa-car-battery:before{content:"\f5df"}.fa-car-crash:before{content:"\f5e1"}.fa-car-alt:before,.fa-car-rear:before{content:"\f5de"}.fa-car-side:before{content:"\f5e4"}.fa-caravan:before{content:"\f8ff"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-caret-up:before{content:"\f0d8"}.fa-carrot:before{content:"\f787"}.fa-cart-arrow-down:before{content:"\f218"}.fa-cart-flatbed:before,.fa-dolly-flatbed:before{content:"\f474"}.fa-cart-flatbed-suitcase:before,.fa-luggage-cart:before{content:"\f59d"}.fa-cart-plus:before{content:"\f217"}.fa-cart-shopping:before,.fa-shopping-cart:before{content:"\f07a"}.fa-cash-register:before{content:"\f788"}.fa-cat:before{content:"\f6be"}.fa-cedi-sign:before{content:"\e0df"}.fa-cent-sign:before{content:"\e3f5"}.fa-certificate:before{content:"\f0a3"}.fa-chair:before{content:"\f6c0"}.fa-blackboard:before,.fa-chalkboard:before{content:"\f51b"}.fa-chalkboard-teacher:before,.fa-chalkboard-user:before{content:"\f51c"}.fa-champagne-glasses:before,.fa-glass-cheers:before{content:"\f79f"}.fa-charging-station:before{content:"\f5e7"}.fa-area-chart:before,.fa-chart-area:before{content:"\f1fe"}.fa-bar-chart:before,.fa-chart-bar:before{content:"\f080"}.fa-chart-column:before{content:"\e0e3"}.fa-chart-gantt:before{content:"\e0e4"}.fa-chart-line:before,.fa-line-chart:before{content:"\f201"}.fa-chart-pie:before,.fa-pie-chart:before{content:"\f200"}.fa-check:before{content:"\f00c"}.fa-check-double:before{content:"\f560"}.fa-check-to-slot:before,.fa-vote-yea:before{content:"\f772"}.fa-cheese:before{content:"\f7ef"}.fa-chess:before{content:"\f439"}.fa-chess-bishop:before{content:"\f43a"}.fa-chess-board:before{content:"\f43c"}.fa-chess-king:before{content:"\f43f"}.fa-chess-knight:before{content:"\f441"}.fa-chess-pawn:before{content:"\f443"}.fa-chess-queen:before{content:"\f445"}.fa-chess-rook:before{content:"\f447"}.fa-chevron-down:before{content:"\f078"}.fa-chevron-left:before{content:"\f053"}.fa-chevron-right:before{content:"\f054"}.fa-chevron-up:before{content:"\f077"}.fa-child:before{content:"\f1ae"}.fa-church:before{content:"\f51d"}.fa-circle:before{content:"\f111"}.fa-arrow-circle-down:before,.fa-circle-arrow-down:before{content:"\f0ab"}.fa-arrow-circle-left:before,.fa-circle-arrow-left:before{content:"\f0a8"}.fa-arrow-circle-right:before,.fa-circle-arrow-right:before{content:"\f0a9"}.fa-arrow-circle-up:before,.fa-circle-arrow-up:before{content:"\f0aa"}.fa-check-circle:before,.fa-circle-check:before{content:"\f058"}.fa-chevron-circle-down:before,.fa-circle-chevron-down:before{content:"\f13a"}.fa-chevron-circle-left:before,.fa-circle-chevron-left:before{content:"\f137"}.fa-chevron-circle-right:before,.fa-circle-chevron-right:before{content:"\f138"}.fa-chevron-circle-up:before,.fa-circle-chevron-up:before{content:"\f139"}.fa-circle-dollar-to-slot:before,.fa-donate:before{content:"\f4b9"}.fa-circle-dot:before,.fa-dot-circle:before{content:"\f192"}.fa-arrow-alt-circle-down:before,.fa-circle-down:before{content:"\f358"}.fa-circle-exclamation:before,.fa-exclamation-circle:before{content:"\f06a"}.fa-circle-h:before,.fa-hospital-symbol:before{content:"\f47e"}.fa-adjust:before,.fa-circle-half-stroke:before{content:"\f042"}.fa-circle-info:before,.fa-info-circle:before{content:"\f05a"}.fa-arrow-alt-circle-left:before,.fa-circle-left:before{content:"\f359"}.fa-circle-minus:before,.fa-minus-circle:before{content:"\f056"}.fa-circle-notch:before{content:"\f1ce"}.fa-circle-pause:before,.fa-pause-circle:before{content:"\f28b"}.fa-circle-play:before,.fa-play-circle:before{content:"\f144"}.fa-circle-plus:before,.fa-plus-circle:before{content:"\f055"}.fa-circle-question:before,.fa-question-circle:before{content:"\f059"}.fa-circle-radiation:before,.fa-radiation-alt:before{content:"\f7ba"}.fa-arrow-alt-circle-right:before,.fa-circle-right:before{content:"\f35a"}.fa-circle-stop:before,.fa-stop-circle:before{content:"\f28d"}.fa-arrow-alt-circle-up:before,.fa-circle-up:before{content:"\f35b"}.fa-circle-user:before,.fa-user-circle:before{content:"\f2bd"}.fa-circle-xmark:before,.fa-times-circle:before,.fa-xmark-circle:before{content:"\f057"}.fa-city:before{content:"\f64f"}.fa-clapperboard:before{content:"\e131"}.fa-clipboard:before{content:"\f328"}.fa-clipboard-check:before{content:"\f46c"}.fa-clipboard-list:before{content:"\f46d"}.fa-clock-four:before,.fa-clock:before{content:"\f017"}.fa-clock-rotate-left:before,.fa-history:before{content:"\f1da"}.fa-clone:before{content:"\f24d"}.fa-closed-captioning:before{content:"\f20a"}.fa-cloud:before{content:"\f0c2"}.fa-cloud-arrow-down:before,.fa-cloud-download-alt:before,.fa-cloud-download:before{content:"\f0ed"}.fa-cloud-arrow-up:before,.fa-cloud-upload-alt:before,.fa-cloud-upload:before{content:"\f0ee"}.fa-cloud-meatball:before{content:"\f73b"}.fa-cloud-moon:before{content:"\f6c3"}.fa-cloud-moon-rain:before{content:"\f73c"}.fa-cloud-rain:before{content:"\f73d"}.fa-cloud-showers-heavy:before{content:"\f740"}.fa-cloud-sun:before{content:"\f6c4"}.fa-cloud-sun-rain:before{content:"\f743"}.fa-clover:before{content:"\e139"}.fa-code:before{content:"\f121"}.fa-code-branch:before{content:"\f126"}.fa-code-commit:before{content:"\f386"}.fa-code-compare:before{content:"\e13a"}.fa-code-fork:before{content:"\e13b"}.fa-code-merge:before{content:"\f387"}.fa-code-pull-request:before{content:"\e13c"}.fa-coins:before{content:"\f51e"}.fa-colon-sign:before{content:"\e140"}.fa-comment:before{content:"\f075"}.fa-comment-dollar:before{content:"\f651"}.fa-comment-dots:before,.fa-commenting:before{content:"\f4ad"}.fa-comment-medical:before{content:"\f7f5"}.fa-comment-slash:before{content:"\f4b3"}.fa-comment-sms:before,.fa-sms:before{content:"\f7cd"}.fa-comments:before{content:"\f086"}.fa-comments-dollar:before{content:"\f653"}.fa-compact-disc:before{content:"\f51f"}.fa-compass:before{content:"\f14e"}.fa-compass-drafting:before,.fa-drafting-compass:before{content:"\f568"}.fa-compress:before{content:"\f066"}.fa-computer-mouse:before,.fa-mouse:before{content:"\f8cc"}.fa-cookie:before{content:"\f563"}.fa-cookie-bite:before{content:"\f564"}.fa-copy:before{content:"\f0c5"}.fa-copyright:before{content:"\f1f9"}.fa-couch:before{content:"\f4b8"}.fa-credit-card-alt:before,.fa-credit-card:before{content:"\f09d"}.fa-crop:before{content:"\f125"}.fa-crop-alt:before,.fa-crop-simple:before{content:"\f565"}.fa-cross:before{content:"\f654"}.fa-crosshairs:before{content:"\f05b"}.fa-crow:before{content:"\f520"}.fa-crown:before{content:"\f521"}.fa-crutch:before{content:"\f7f7"}.fa-cruzeiro-sign:before{content:"\e152"}.fa-cube:before{content:"\f1b2"}.fa-cubes:before{content:"\f1b3"}.fa-d:before{content:"\44"}.fa-database:before{content:"\f1c0"}.fa-backspace:before,.fa-delete-left:before{content:"\f55a"}.fa-democrat:before{content:"\f747"}.fa-desktop-alt:before,.fa-desktop:before{content:"\f390"}.fa-dharmachakra:before{content:"\f655"}.fa-diagram-next:before{content:"\e476"}.fa-diagram-predecessor:before{content:"\e477"}.fa-diagram-project:before,.fa-project-diagram:before{content:"\f542"}.fa-diagram-successor:before{content:"\e47a"}.fa-diamond:before{content:"\f219"}.fa-diamond-turn-right:before,.fa-directions:before{content:"\f5eb"}.fa-dice:before{content:"\f522"}.fa-dice-d20:before{content:"\f6cf"}.fa-dice-d6:before{content:"\f6d1"}.fa-dice-five:before{content:"\f523"}.fa-dice-four:before{content:"\f524"}.fa-dice-one:before{content:"\f525"}.fa-dice-six:before{content:"\f526"}.fa-dice-three:before{content:"\f527"}.fa-dice-two:before{content:"\f528"}.fa-disease:before{content:"\f7fa"}.fa-divide:before{content:"\f529"}.fa-dna:before{content:"\f471"}.fa-dog:before{content:"\f6d3"}.fa-dollar-sign:before,.fa-dollar:before,.fa-usd:before{content:"\24"}.fa-dolly-box:before,.fa-dolly:before{content:"\f472"}.fa-dong-sign:before{content:"\e169"}.fa-door-closed:before{content:"\f52a"}.fa-door-open:before{content:"\f52b"}.fa-dove:before{content:"\f4ba"}.fa-compress-alt:before,.fa-down-left-and-up-right-to-center:before{content:"\f422"}.fa-down-long:before,.fa-long-arrow-alt-down:before{content:"\f309"}.fa-download:before{content:"\f019"}.fa-dragon:before{content:"\f6d5"}.fa-draw-polygon:before{content:"\f5ee"}.fa-droplet:before,.fa-tint:before{content:"\f043"}.fa-droplet-slash:before,.fa-tint-slash:before{content:"\f5c7"}.fa-drum:before{content:"\f569"}.fa-drum-steelpan:before{content:"\f56a"}.fa-drumstick-bite:before{content:"\f6d7"}.fa-dumbbell:before{content:"\f44b"}.fa-dumpster:before{content:"\f793"}.fa-dumpster-fire:before{content:"\f794"}.fa-dungeon:before{content:"\f6d9"}.fa-e:before{content:"\45"}.fa-deaf:before,.fa-deafness:before,.fa-ear-deaf:before,.fa-hard-of-hearing:before{content:"\f2a4"}.fa-assistive-listening-systems:before,.fa-ear-listen:before{content:"\f2a2"}.fa-earth-africa:before,.fa-globe-africa:before{content:"\f57c"}.fa-earth-america:before,.fa-earth-americas:before,.fa-earth:before,.fa-globe-americas:before{content:"\f57d"}.fa-earth-asia:before,.fa-globe-asia:before{content:"\f57e"}.fa-earth-europe:before,.fa-globe-europe:before{content:"\f7a2"}.fa-earth-oceania:before,.fa-globe-oceania:before{content:"\e47b"}.fa-egg:before{content:"\f7fb"}.fa-eject:before{content:"\f052"}.fa-elevator:before{content:"\e16d"}.fa-ellipsis-h:before,.fa-ellipsis:before{content:"\f141"}.fa-ellipsis-v:before,.fa-ellipsis-vertical:before{content:"\f142"}.fa-envelope:before{content:"\f0e0"}.fa-envelope-open:before{content:"\f2b6"}.fa-envelope-open-text:before{content:"\f658"}.fa-envelopes-bulk:before,.fa-mail-bulk:before{content:"\f674"}.fa-equals:before{content:"\3d"}.fa-eraser:before{content:"\f12d"}.fa-ethernet:before{content:"\f796"}.fa-eur:before,.fa-euro-sign:before,.fa-euro:before{content:"\f153"}.fa-exclamation:before{content:"\21"}.fa-expand:before{content:"\f065"}.fa-eye:before{content:"\f06e"}.fa-eye-dropper-empty:before,.fa-eye-dropper:before,.fa-eyedropper:before{content:"\f1fb"}.fa-eye-low-vision:before,.fa-low-vision:before{content:"\f2a8"}.fa-eye-slash:before{content:"\f070"}.fa-f:before{content:"\46"}.fa-angry:before,.fa-face-angry:before{content:"\f556"}.fa-dizzy:before,.fa-face-dizzy:before{content:"\f567"}.fa-face-flushed:before,.fa-flushed:before{content:"\f579"}.fa-face-frown:before,.fa-frown:before{content:"\f119"}.fa-face-frown-open:before,.fa-frown-open:before{content:"\f57a"}.fa-face-grimace:before,.fa-grimace:before{content:"\f57f"}.fa-face-grin:before,.fa-grin:before{content:"\f580"}.fa-face-grin-beam:before,.fa-grin-beam:before{content:"\f582"}.fa-face-grin-beam-sweat:before,.fa-grin-beam-sweat:before{content:"\f583"}.fa-face-grin-hearts:before,.fa-grin-hearts:before{content:"\f584"}.fa-face-grin-squint:before,.fa-grin-squint:before{content:"\f585"}.fa-face-grin-squint-tears:before,.fa-grin-squint-tears:before{content:"\f586"}.fa-face-grin-stars:before,.fa-grin-stars:before{content:"\f587"}.fa-face-grin-tears:before,.fa-grin-tears:before{content:"\f588"}.fa-face-grin-tongue:before,.fa-grin-tongue:before{content:"\f589"}.fa-face-grin-tongue-squint:before,.fa-grin-tongue-squint:before{content:"\f58a"}.fa-face-grin-tongue-wink:before,.fa-grin-tongue-wink:before{content:"\f58b"}.fa-face-grin-wide:before,.fa-grin-alt:before{content:"\f581"}.fa-face-grin-wink:before,.fa-grin-wink:before{content:"\f58c"}.fa-face-kiss:before,.fa-kiss:before{content:"\f596"}.fa-face-kiss-beam:before,.fa-kiss-beam:before{content:"\f597"}.fa-face-kiss-wink-heart:before,.fa-kiss-wink-heart:before{content:"\f598"}.fa-face-laugh:before,.fa-laugh:before{content:"\f599"}.fa-face-laugh-beam:before,.fa-laugh-beam:before{content:"\f59a"}.fa-face-laugh-squint:before,.fa-laugh-squint:before{content:"\f59b"}.fa-face-laugh-wink:before,.fa-laugh-wink:before{content:"\f59c"}.fa-face-meh:before,.fa-meh:before{content:"\f11a"}.fa-face-meh-blank:before,.fa-meh-blank:before{content:"\f5a4"}.fa-face-rolling-eyes:before,.fa-meh-rolling-eyes:before{content:"\f5a5"}.fa-face-sad-cry:before,.fa-sad-cry:before{content:"\f5b3"}.fa-face-sad-tear:before,.fa-sad-tear:before{content:"\f5b4"}.fa-face-smile:before,.fa-smile:before{content:"\f118"}.fa-face-smile-beam:before,.fa-smile-beam:before{content:"\f5b8"}.fa-face-smile-wink:before,.fa-smile-wink:before{content:"\f4da"}.fa-face-surprise:before,.fa-surprise:before{content:"\f5c2"}.fa-face-tired:before,.fa-tired:before{content:"\f5c8"}.fa-fan:before{content:"\f863"}.fa-faucet:before{content:"\e005"}.fa-fax:before{content:"\f1ac"}.fa-feather:before{content:"\f52d"}.fa-feather-alt:before,.fa-feather-pointed:before{content:"\f56b"}.fa-file:before{content:"\f15b"}.fa-file-arrow-down:before,.fa-file-download:before{content:"\f56d"}.fa-file-arrow-up:before,.fa-file-upload:before{content:"\f574"}.fa-file-audio:before{content:"\f1c7"}.fa-file-code:before{content:"\f1c9"}.fa-file-contract:before{content:"\f56c"}.fa-file-csv:before{content:"\f6dd"}.fa-file-excel:before{content:"\f1c3"}.fa-arrow-right-from-file:before,.fa-file-export:before{content:"\f56e"}.fa-file-image:before{content:"\f1c5"}.fa-arrow-right-to-file:before,.fa-file-import:before{content:"\f56f"}.fa-file-invoice:before{content:"\f570"}.fa-file-invoice-dollar:before{content:"\f571"}.fa-file-alt:before,.fa-file-lines:before,.fa-file-text:before{content:"\f15c"}.fa-file-medical:before{content:"\f477"}.fa-file-pdf:before{content:"\f1c1"}.fa-file-powerpoint:before{content:"\f1c4"}.fa-file-prescription:before{content:"\f572"}.fa-file-signature:before{content:"\f573"}.fa-file-video:before{content:"\f1c8"}.fa-file-medical-alt:before,.fa-file-waveform:before{content:"\f478"}.fa-file-word:before{content:"\f1c2"}.fa-file-archive:before,.fa-file-zipper:before{content:"\f1c6"}.fa-fill:before{content:"\f575"}.fa-fill-drip:before{content:"\f576"}.fa-film:before{content:"\f008"}.fa-filter:before{content:"\f0b0"}.fa-filter-circle-dollar:before,.fa-funnel-dollar:before{content:"\f662"}.fa-filter-circle-xmark:before{content:"\e17b"}.fa-fingerprint:before{content:"\f577"}.fa-fire:before{content:"\f06d"}.fa-fire-extinguisher:before{content:"\f134"}.fa-fire-alt:before,.fa-fire-flame-curved:before{content:"\f7e4"}.fa-burn:before,.fa-fire-flame-simple:before{content:"\f46a"}.fa-fish:before{content:"\f578"}.fa-flag:before{content:"\f024"}.fa-flag-checkered:before{content:"\f11e"}.fa-flag-usa:before{content:"\f74d"}.fa-flask:before{content:"\f0c3"}.fa-floppy-disk:before,.fa-save:before{content:"\f0c7"}.fa-florin-sign:before{content:"\e184"}.fa-folder:before{content:"\f07b"}.fa-folder-minus:before{content:"\f65d"}.fa-folder-open:before{content:"\f07c"}.fa-folder-plus:before{content:"\f65e"}.fa-folder-tree:before{content:"\f802"}.fa-font:before{content:"\f031"}.fa-football-ball:before,.fa-football:before{content:"\f44e"}.fa-forward:before{content:"\f04e"}.fa-fast-forward:before,.fa-forward-fast:before{content:"\f050"}.fa-forward-step:before,.fa-step-forward:before{content:"\f051"}.fa-franc-sign:before{content:"\e18f"}.fa-frog:before{content:"\f52e"}.fa-futbol-ball:before,.fa-futbol:before,.fa-soccer-ball:before{content:"\f1e3"}.fa-g:before{content:"\47"}.fa-gamepad:before{content:"\f11b"}.fa-gas-pump:before{content:"\f52f"}.fa-dashboard:before,.fa-gauge-med:before,.fa-gauge:before,.fa-tachometer-alt-average:before{content:"\f624"}.fa-gauge-high:before,.fa-tachometer-alt-fast:before,.fa-tachometer-alt:before{content:"\f625"}.fa-gauge-simple-med:before,.fa-gauge-simple:before,.fa-tachometer-average:before{content:"\f629"}.fa-gauge-simple-high:before,.fa-tachometer-fast:before,.fa-tachometer:before{content:"\f62a"}.fa-gavel:before,.fa-legal:before{content:"\f0e3"}.fa-cog:before,.fa-gear:before{content:"\f013"}.fa-cogs:before,.fa-gears:before{content:"\f085"}.fa-gem:before{content:"\f3a5"}.fa-genderless:before{content:"\f22d"}.fa-ghost:before{content:"\f6e2"}.fa-gift:before{content:"\f06b"}.fa-gifts:before{content:"\f79c"}.fa-glasses:before{content:"\f530"}.fa-globe:before{content:"\f0ac"}.fa-golf-ball-tee:before,.fa-golf-ball:before{content:"\f450"}.fa-gopuram:before{content:"\f664"}.fa-graduation-cap:before,.fa-mortar-board:before{content:"\f19d"}.fa-greater-than:before{content:"\3e"}.fa-greater-than-equal:before{content:"\f532"}.fa-grip-horizontal:before,.fa-grip:before{content:"\f58d"}.fa-grip-lines:before{content:"\f7a4"}.fa-grip-lines-vertical:before{content:"\f7a5"}.fa-grip-vertical:before{content:"\f58e"}.fa-guarani-sign:before{content:"\e19a"}.fa-guitar:before{content:"\f7a6"}.fa-gun:before{content:"\e19b"}.fa-h:before{content:"\48"}.fa-hammer:before{content:"\f6e3"}.fa-hamsa:before{content:"\f665"}.fa-hand-paper:before,.fa-hand:before{content:"\f256"}.fa-hand-back-fist:before,.fa-hand-rock:before{content:"\f255"}.fa-allergies:before,.fa-hand-dots:before{content:"\f461"}.fa-fist-raised:before,.fa-hand-fist:before{content:"\f6de"}.fa-hand-holding:before{content:"\f4bd"}.fa-hand-holding-dollar:before,.fa-hand-holding-usd:before{content:"\f4c0"}.fa-hand-holding-droplet:before,.fa-hand-holding-water:before{content:"\f4c1"}.fa-hand-holding-heart:before{content:"\f4be"}.fa-hand-holding-medical:before{content:"\e05c"}.fa-hand-lizard:before{content:"\f258"}.fa-hand-middle-finger:before{content:"\f806"}.fa-hand-peace:before{content:"\f25b"}.fa-hand-point-down:before{content:"\f0a7"}.fa-hand-point-left:before{content:"\f0a5"}.fa-hand-point-right:before{content:"\f0a4"}.fa-hand-point-up:before{content:"\f0a6"}.fa-hand-pointer:before{content:"\f25a"}.fa-hand-scissors:before{content:"\f257"}.fa-hand-sparkles:before{content:"\e05d"}.fa-hand-spock:before{content:"\f259"}.fa-hands:before,.fa-sign-language:before,.fa-signing:before{content:"\f2a7"}.fa-american-sign-language-interpreting:before,.fa-asl-interpreting:before,.fa-hands-american-sign-language-interpreting:before,.fa-hands-asl-interpreting:before{content:"\f2a3"}.fa-hands-bubbles:before,.fa-hands-wash:before{content:"\e05e"}.fa-hands-clapping:before{content:"\e1a8"}.fa-hands-holding:before{content:"\f4c2"}.fa-hands-praying:before,.fa-praying-hands:before{content:"\f684"}.fa-handshake:before{content:"\f2b5"}.fa-hands-helping:before,.fa-handshake-angle:before{content:"\f4c4"}.fa-handshake-alt-slash:before,.fa-handshake-simple-slash:before{content:"\e05f"}.fa-handshake-slash:before{content:"\e060"}.fa-hanukiah:before{content:"\f6e6"}.fa-hard-drive:before,.fa-hdd:before{content:"\f0a0"}.fa-hashtag:before{content:"\23"}.fa-hat-cowboy:before{content:"\f8c0"}.fa-hat-cowboy-side:before{content:"\f8c1"}.fa-hat-wizard:before{content:"\f6e8"}.fa-head-side-cough:before{content:"\e061"}.fa-head-side-cough-slash:before{content:"\e062"}.fa-head-side-mask:before{content:"\e063"}.fa-head-side-virus:before{content:"\e064"}.fa-header:before,.fa-heading:before{content:"\f1dc"}.fa-headphones:before{content:"\f025"}.fa-headphones-alt:before,.fa-headphones-simple:before{content:"\f58f"}.fa-headset:before{content:"\f590"}.fa-heart:before{content:"\f004"}.fa-heart-broken:before,.fa-heart-crack:before{content:"\f7a9"}.fa-heart-pulse:before,.fa-heartbeat:before{content:"\f21e"}.fa-helicopter:before{content:"\f533"}.fa-hard-hat:before,.fa-hat-hard:before,.fa-helmet-safety:before{content:"\f807"}.fa-highlighter:before{content:"\f591"}.fa-hippo:before{content:"\f6ed"}.fa-hockey-puck:before{content:"\f453"}.fa-holly-berry:before{content:"\f7aa"}.fa-horse:before{content:"\f6f0"}.fa-horse-head:before{content:"\f7ab"}.fa-hospital-alt:before,.fa-hospital-wide:before,.fa-hospital:before{content:"\f0f8"}.fa-hospital-user:before{content:"\f80d"}.fa-hot-tub-person:before,.fa-hot-tub:before{content:"\f593"}.fa-hotdog:before{content:"\f80f"}.fa-hotel:before{content:"\f594"}.fa-hourglass-2:before,.fa-hourglass-half:before,.fa-hourglass:before{content:"\f254"}.fa-hourglass-empty:before{content:"\f252"}.fa-hourglass-3:before,.fa-hourglass-end:before{content:"\f253"}.fa-hourglass-1:before,.fa-hourglass-start:before{content:"\f251"}.fa-home-alt:before,.fa-home-lg-alt:before,.fa-home:before,.fa-house:before{content:"\f015"}.fa-home-lg:before,.fa-house-chimney:before{content:"\e3af"}.fa-house-chimney-crack:before,.fa-house-damage:before{content:"\f6f1"}.fa-clinic-medical:before,.fa-house-chimney-medical:before{content:"\f7f2"}.fa-house-chimney-user:before{content:"\e065"}.fa-house-chimney-window:before{content:"\e00d"}.fa-house-crack:before{content:"\e3b1"}.fa-house-laptop:before,.fa-laptop-house:before{content:"\e066"}.fa-house-medical:before{content:"\e3b2"}.fa-home-user:before,.fa-house-user:before{content:"\e1b0"}.fa-hryvnia-sign:before,.fa-hryvnia:before{content:"\f6f2"}.fa-i:before{content:"\49"}.fa-i-cursor:before{content:"\f246"}.fa-ice-cream:before{content:"\f810"}.fa-icicles:before{content:"\f7ad"}.fa-heart-music-camera-bolt:before,.fa-icons:before{content:"\f86d"}.fa-id-badge:before{content:"\f2c1"}.fa-drivers-license:before,.fa-id-card:before{content:"\f2c2"}.fa-id-card-alt:before,.fa-id-card-clip:before{content:"\f47f"}.fa-igloo:before{content:"\f7ae"}.fa-image:before{content:"\f03e"}.fa-image-portrait:before,.fa-portrait:before{content:"\f3e0"}.fa-images:before{content:"\f302"}.fa-inbox:before{content:"\f01c"}.fa-indent:before{content:"\f03c"}.fa-indian-rupee-sign:before,.fa-indian-rupee:before,.fa-inr:before{content:"\e1bc"}.fa-industry:before{content:"\f275"}.fa-infinity:before{content:"\f534"}.fa-info:before{content:"\f129"}.fa-italic:before{content:"\f033"}.fa-j:before{content:"\4a"}.fa-jedi:before{content:"\f669"}.fa-fighter-jet:before,.fa-jet-fighter:before{content:"\f0fb"}.fa-joint:before{content:"\f595"}.fa-k:before{content:"\4b"}.fa-kaaba:before{content:"\f66b"}.fa-key:before{content:"\f084"}.fa-keyboard:before{content:"\f11c"}.fa-khanda:before{content:"\f66d"}.fa-kip-sign:before{content:"\e1c4"}.fa-first-aid:before,.fa-kit-medical:before{content:"\f479"}.fa-kiwi-bird:before{content:"\f535"}.fa-l:before{content:"\4c"}.fa-landmark:before{content:"\f66f"}.fa-language:before{content:"\f1ab"}.fa-laptop:before{content:"\f109"}.fa-laptop-code:before{content:"\f5fc"}.fa-laptop-medical:before{content:"\f812"}.fa-lari-sign:before{content:"\e1c8"}.fa-layer-group:before{content:"\f5fd"}.fa-leaf:before{content:"\f06c"}.fa-left-long:before,.fa-long-arrow-alt-left:before{content:"\f30a"}.fa-arrows-alt-h:before,.fa-left-right:before{content:"\f337"}.fa-lemon:before{content:"\f094"}.fa-less-than:before{content:"\3c"}.fa-less-than-equal:before{content:"\f537"}.fa-life-ring:before{content:"\f1cd"}.fa-lightbulb:before{content:"\f0eb"}.fa-chain:before,.fa-link:before{content:"\f0c1"}.fa-chain-broken:before,.fa-chain-slash:before,.fa-link-slash:before,.fa-unlink:before{content:"\f127"}.fa-lira-sign:before{content:"\f195"}.fa-list-squares:before,.fa-list:before{content:"\f03a"}.fa-list-check:before,.fa-tasks:before{content:"\f0ae"}.fa-list-1-2:before,.fa-list-numeric:before,.fa-list-ol:before{content:"\f0cb"}.fa-list-dots:before,.fa-list-ul:before{content:"\f0ca"}.fa-litecoin-sign:before{content:"\e1d3"}.fa-location-arrow:before{content:"\f124"}.fa-location-crosshairs:before,.fa-location:before{content:"\f601"}.fa-location-dot:before,.fa-map-marker-alt:before{content:"\f3c5"}.fa-location-pin:before,.fa-map-marker:before{content:"\f041"}.fa-lock:before{content:"\f023"}.fa-lock-open:before{content:"\f3c1"}.fa-lungs:before{content:"\f604"}.fa-lungs-virus:before{content:"\e067"}.fa-m:before{content:"\4d"}.fa-magnet:before{content:"\f076"}.fa-magnifying-glass:before,.fa-search:before{content:"\f002"}.fa-magnifying-glass-dollar:before,.fa-search-dollar:before{content:"\f688"}.fa-magnifying-glass-location:before,.fa-search-location:before{content:"\f689"}.fa-magnifying-glass-minus:before,.fa-search-minus:before{content:"\f010"}.fa-magnifying-glass-plus:before,.fa-search-plus:before{content:"\f00e"}.fa-manat-sign:before{content:"\e1d5"}.fa-map:before{content:"\f279"}.fa-map-location:before,.fa-map-marked:before{content:"\f59f"}.fa-map-location-dot:before,.fa-map-marked-alt:before{content:"\f5a0"}.fa-map-pin:before{content:"\f276"}.fa-marker:before{content:"\f5a1"}.fa-mars:before{content:"\f222"}.fa-mars-and-venus:before{content:"\f224"}.fa-mars-double:before{content:"\f227"}.fa-mars-stroke:before{content:"\f229"}.fa-mars-stroke-h:before,.fa-mars-stroke-right:before{content:"\f22b"}.fa-mars-stroke-up:before,.fa-mars-stroke-v:before{content:"\f22a"}.fa-glass-martini-alt:before,.fa-martini-glass:before{content:"\f57b"}.fa-cocktail:before,.fa-martini-glass-citrus:before{content:"\f561"}.fa-glass-martini:before,.fa-martini-glass-empty:before{content:"\f000"}.fa-mask:before{content:"\f6fa"}.fa-mask-face:before{content:"\e1d7"}.fa-masks-theater:before,.fa-theater-masks:before{content:"\f630"}.fa-expand-arrows-alt:before,.fa-maximize:before{content:"\f31e"}.fa-medal:before{content:"\f5a2"}.fa-memory:before{content:"\f538"}.fa-menorah:before{content:"\f676"}.fa-mercury:before{content:"\f223"}.fa-comment-alt:before,.fa-message:before{content:"\f27a"}.fa-meteor:before{content:"\f753"}.fa-microchip:before{content:"\f2db"}.fa-microphone:before{content:"\f130"}.fa-microphone-alt:before,.fa-microphone-lines:before{content:"\f3c9"}.fa-microphone-alt-slash:before,.fa-microphone-lines-slash:before{content:"\f539"}.fa-microphone-slash:before{content:"\f131"}.fa-microscope:before{content:"\f610"}.fa-mill-sign:before{content:"\e1ed"}.fa-compress-arrows-alt:before,.fa-minimize:before{content:"\f78c"}.fa-minus:before,.fa-subtract:before{content:"\f068"}.fa-mitten:before{content:"\f7b5"}.fa-mobile-android:before,.fa-mobile-phone:before,.fa-mobile:before{content:"\f3ce"}.fa-mobile-button:before{content:"\f10b"}.fa-mobile-alt:before,.fa-mobile-screen-button:before{content:"\f3cd"}.fa-money-bill:before{content:"\f0d6"}.fa-money-bill-1:before,.fa-money-bill-alt:before{content:"\f3d1"}.fa-money-bill-1-wave:before,.fa-money-bill-wave-alt:before{content:"\f53b"}.fa-money-bill-wave:before{content:"\f53a"}.fa-money-check:before{content:"\f53c"}.fa-money-check-alt:before,.fa-money-check-dollar:before{content:"\f53d"}.fa-monument:before{content:"\f5a6"}.fa-moon:before{content:"\f186"}.fa-mortar-pestle:before{content:"\f5a7"}.fa-mosque:before{content:"\f678"}.fa-motorcycle:before{content:"\f21c"}.fa-mountain:before{content:"\f6fc"}.fa-mug-hot:before{content:"\f7b6"}.fa-coffee:before,.fa-mug-saucer:before{content:"\f0f4"}.fa-music:before{content:"\f001"}.fa-n:before{content:"\4e"}.fa-naira-sign:before{content:"\e1f6"}.fa-network-wired:before{content:"\f6ff"}.fa-neuter:before{content:"\f22c"}.fa-newspaper:before{content:"\f1ea"}.fa-not-equal:before{content:"\f53e"}.fa-note-sticky:before,.fa-sticky-note:before{content:"\f249"}.fa-notes-medical:before{content:"\f481"}.fa-o:before{content:"\4f"}.fa-object-group:before{content:"\f247"}.fa-object-ungroup:before{content:"\f248"}.fa-oil-can:before{content:"\f613"}.fa-om:before{content:"\f679"}.fa-otter:before{content:"\f700"}.fa-dedent:before,.fa-outdent:before{content:"\f03b"}.fa-p:before{content:"\50"}.fa-pager:before{content:"\f815"}.fa-paint-roller:before{content:"\f5aa"}.fa-paint-brush:before,.fa-paintbrush:before{content:"\f1fc"}.fa-palette:before{content:"\f53f"}.fa-pallet:before{content:"\f482"}.fa-panorama:before{content:"\e209"}.fa-paper-plane:before{content:"\f1d8"}.fa-paperclip:before{content:"\f0c6"}.fa-parachute-box:before{content:"\f4cd"}.fa-paragraph:before{content:"\f1dd"}.fa-passport:before{content:"\f5ab"}.fa-file-clipboard:before,.fa-paste:before{content:"\f0ea"}.fa-pause:before{content:"\f04c"}.fa-paw:before{content:"\f1b0"}.fa-peace:before{content:"\f67c"}.fa-pen:before{content:"\f304"}.fa-pen-alt:before,.fa-pen-clip:before{content:"\f305"}.fa-pen-fancy:before{content:"\f5ac"}.fa-pen-nib:before{content:"\f5ad"}.fa-pen-ruler:before,.fa-pencil-ruler:before{content:"\f5ae"}.fa-edit:before,.fa-pen-to-square:before{content:"\f044"}.fa-pencil-alt:before,.fa-pencil:before{content:"\f303"}.fa-people-arrows-left-right:before,.fa-people-arrows:before{content:"\e068"}.fa-people-carry-box:before,.fa-people-carry:before{content:"\f4ce"}.fa-pepper-hot:before{content:"\f816"}.fa-percent:before,.fa-percentage:before{content:"\25"}.fa-male:before,.fa-person:before{content:"\f183"}.fa-biking:before,.fa-person-biking:before{content:"\f84a"}.fa-person-booth:before{content:"\f756"}.fa-diagnoses:before,.fa-person-dots-from-line:before{content:"\f470"}.fa-female:before,.fa-person-dress:before{content:"\f182"}.fa-hiking:before,.fa-person-hiking:before{content:"\f6ec"}.fa-person-praying:before,.fa-pray:before{content:"\f683"}.fa-person-running:before,.fa-running:before{content:"\f70c"}.fa-person-skating:before,.fa-skating:before{content:"\f7c5"}.fa-person-skiing:before,.fa-skiing:before{content:"\f7c9"}.fa-person-skiing-nordic:before,.fa-skiing-nordic:before{content:"\f7ca"}.fa-person-snowboarding:before,.fa-snowboarding:before{content:"\f7ce"}.fa-person-swimming:before,.fa-swimmer:before{content:"\f5c4"}.fa-person-walking:before,.fa-walking:before{content:"\f554"}.fa-blind:before,.fa-person-walking-with-cane:before{content:"\f29d"}.fa-peseta-sign:before{content:"\e221"}.fa-peso-sign:before{content:"\e222"}.fa-phone:before{content:"\f095"}.fa-phone-alt:before,.fa-phone-flip:before{content:"\f879"}.fa-phone-slash:before{content:"\f3dd"}.fa-phone-volume:before,.fa-volume-control-phone:before{content:"\f2a0"}.fa-photo-film:before,.fa-photo-video:before{content:"\f87c"}.fa-piggy-bank:before{content:"\f4d3"}.fa-pills:before{content:"\f484"}.fa-pizza-slice:before{content:"\f818"}.fa-place-of-worship:before{content:"\f67f"}.fa-plane:before{content:"\f072"}.fa-plane-arrival:before{content:"\f5af"}.fa-plane-departure:before{content:"\f5b0"}.fa-plane-slash:before{content:"\e069"}.fa-play:before{content:"\f04b"}.fa-plug:before{content:"\f1e6"}.fa-add:before,.fa-plus:before{content:"\2b"}.fa-plus-minus:before{content:"\e43c"}.fa-podcast:before{content:"\f2ce"}.fa-poo:before{content:"\f2fe"}.fa-poo-bolt:before,.fa-poo-storm:before{content:"\f75a"}.fa-poop:before{content:"\f619"}.fa-power-off:before{content:"\f011"}.fa-prescription:before{content:"\f5b1"}.fa-prescription-bottle:before{content:"\f485"}.fa-prescription-bottle-alt:before,.fa-prescription-bottle-medical:before{content:"\f486"}.fa-print:before{content:"\f02f"}.fa-pump-medical:before{content:"\e06a"}.fa-pump-soap:before{content:"\e06b"}.fa-puzzle-piece:before{content:"\f12e"}.fa-q:before{content:"\51"}.fa-qrcode:before{content:"\f029"}.fa-question:before{content:"\3f"}.fa-quote-left-alt:before,.fa-quote-left:before{content:"\f10d"}.fa-quote-right-alt:before,.fa-quote-right:before{content:"\f10e"}.fa-r:before{content:"\52"}.fa-radiation:before{content:"\f7b9"}.fa-rainbow:before{content:"\f75b"}.fa-receipt:before{content:"\f543"}.fa-record-vinyl:before{content:"\f8d9"}.fa-ad:before,.fa-rectangle-ad:before{content:"\f641"}.fa-list-alt:before,.fa-rectangle-list:before{content:"\f022"}.fa-rectangle-times:before,.fa-rectangle-xmark:before,.fa-times-rectangle:before,.fa-window-close:before{content:"\f410"}.fa-recycle:before{content:"\f1b8"}.fa-registered:before{content:"\f25d"}.fa-repeat:before{content:"\f363"}.fa-mail-reply:before,.fa-reply:before{content:"\f3e5"}.fa-mail-reply-all:before,.fa-reply-all:before{content:"\f122"}.fa-republican:before{content:"\f75e"}.fa-restroom:before{content:"\f7bd"}.fa-retweet:before{content:"\f079"}.fa-ribbon:before{content:"\f4d6"}.fa-right-from-bracket:before,.fa-sign-out-alt:before{content:"\f2f5"}.fa-exchange-alt:before,.fa-right-left:before{content:"\f362"}.fa-long-arrow-alt-right:before,.fa-right-long:before{content:"\f30b"}.fa-right-to-bracket:before,.fa-sign-in-alt:before{content:"\f2f6"}.fa-ring:before{content:"\f70b"}.fa-road:before{content:"\f018"}.fa-robot:before{content:"\f544"}.fa-rocket:before{content:"\f135"}.fa-rotate:before,.fa-sync-alt:before{content:"\f2f1"}.fa-rotate-back:before,.fa-rotate-backward:before,.fa-rotate-left:before,.fa-undo-alt:before{content:"\f2ea"}.fa-redo-alt:before,.fa-rotate-forward:before,.fa-rotate-right:before{content:"\f2f9"}.fa-route:before{content:"\f4d7"}.fa-feed:before,.fa-rss:before{content:"\f09e"}.fa-rouble:before,.fa-rub:before,.fa-ruble-sign:before,.fa-ruble:before{content:"\f158"}.fa-ruler:before{content:"\f545"}.fa-ruler-combined:before{content:"\f546"}.fa-ruler-horizontal:before{content:"\f547"}.fa-ruler-vertical:before{content:"\f548"}.fa-rupee-sign:before,.fa-rupee:before{content:"\f156"}.fa-rupiah-sign:before{content:"\e23d"}.fa-s:before{content:"\53"}.fa-sailboat:before{content:"\e445"}.fa-satellite:before{content:"\f7bf"}.fa-satellite-dish:before{content:"\f7c0"}.fa-balance-scale:before,.fa-scale-balanced:before{content:"\f24e"}.fa-balance-scale-left:before,.fa-scale-unbalanced:before{content:"\f515"}.fa-balance-scale-right:before,.fa-scale-unbalanced-flip:before{content:"\f516"}.fa-school:before{content:"\f549"}.fa-cut:before,.fa-scissors:before{content:"\f0c4"}.fa-screwdriver:before{content:"\f54a"}.fa-screwdriver-wrench:before,.fa-tools:before{content:"\f7d9"}.fa-scroll:before{content:"\f70e"}.fa-scroll-torah:before,.fa-torah:before{content:"\f6a0"}.fa-sd-card:before{content:"\f7c2"}.fa-section:before{content:"\e447"}.fa-seedling:before,.fa-sprout:before{content:"\f4d8"}.fa-server:before{content:"\f233"}.fa-shapes:before,.fa-triangle-circle-square:before{content:"\f61f"}.fa-arrow-turn-right:before,.fa-mail-forward:before,.fa-share:before{content:"\f064"}.fa-share-from-square:before,.fa-share-square:before{content:"\f14d"}.fa-share-alt:before,.fa-share-nodes:before{content:"\f1e0"}.fa-ils:before,.fa-shekel-sign:before,.fa-shekel:before,.fa-sheqel-sign:before,.fa-sheqel:before{content:"\f20b"}.fa-shield:before{content:"\f132"}.fa-shield-alt:before,.fa-shield-blank:before{content:"\f3ed"}.fa-shield-virus:before{content:"\e06c"}.fa-ship:before{content:"\f21a"}.fa-shirt:before,.fa-t-shirt:before,.fa-tshirt:before{content:"\f553"}.fa-shoe-prints:before{content:"\f54b"}.fa-shop:before,.fa-store-alt:before{content:"\f54f"}.fa-shop-slash:before,.fa-store-alt-slash:before{content:"\e070"}.fa-shower:before{content:"\f2cc"}.fa-shrimp:before{content:"\e448"}.fa-random:before,.fa-shuffle:before{content:"\f074"}.fa-shuttle-space:before,.fa-space-shuttle:before{content:"\f197"}.fa-sign-hanging:before,.fa-sign:before{content:"\f4d9"}.fa-signal-5:before,.fa-signal-perfect:before,.fa-signal:before{content:"\f012"}.fa-signature:before{content:"\f5b7"}.fa-map-signs:before,.fa-signs-post:before{content:"\f277"}.fa-sim-card:before{content:"\f7c4"}.fa-sink:before{content:"\e06d"}.fa-sitemap:before{content:"\f0e8"}.fa-skull:before{content:"\f54c"}.fa-skull-crossbones:before{content:"\f714"}.fa-slash:before{content:"\f715"}.fa-sleigh:before{content:"\f7cc"}.fa-sliders-h:before,.fa-sliders:before{content:"\f1de"}.fa-smog:before{content:"\f75f"}.fa-smoking:before{content:"\f48d"}.fa-snowflake:before{content:"\f2dc"}.fa-snowman:before{content:"\f7d0"}.fa-snowplow:before{content:"\f7d2"}.fa-soap:before{content:"\e06e"}.fa-socks:before{content:"\f696"}.fa-solar-panel:before{content:"\f5ba"}.fa-sort:before,.fa-unsorted:before{content:"\f0dc"}.fa-sort-desc:before,.fa-sort-down:before{content:"\f0dd"}.fa-sort-asc:before,.fa-sort-up:before{content:"\f0de"}.fa-spa:before{content:"\f5bb"}.fa-pastafarianism:before,.fa-spaghetti-monster-flying:before{content:"\f67b"}.fa-spell-check:before{content:"\f891"}.fa-spider:before{content:"\f717"}.fa-spinner:before{content:"\f110"}.fa-splotch:before{content:"\f5bc"}.fa-spoon:before,.fa-utensil-spoon:before{content:"\f2e5"}.fa-spray-can:before{content:"\f5bd"}.fa-air-freshener:before,.fa-spray-can-sparkles:before{content:"\f5d0"}.fa-square:before{content:"\f0c8"}.fa-external-link-square:before,.fa-square-arrow-up-right:before{content:"\f14c"}.fa-caret-square-down:before,.fa-square-caret-down:before{content:"\f150"}.fa-caret-square-left:before,.fa-square-caret-left:before{content:"\f191"}.fa-caret-square-right:before,.fa-square-caret-right:before{content:"\f152"}.fa-caret-square-up:before,.fa-square-caret-up:before{content:"\f151"}.fa-check-square:before,.fa-square-check:before{content:"\f14a"}.fa-envelope-square:before,.fa-square-envelope:before{content:"\f199"}.fa-square-full:before{content:"\f45c"}.fa-h-square:before,.fa-square-h:before{content:"\f0fd"}.fa-minus-square:before,.fa-square-minus:before{content:"\f146"}.fa-parking:before,.fa-square-parking:before{content:"\f540"}.fa-pen-square:before,.fa-pencil-square:before,.fa-square-pen:before{content:"\f14b"}.fa-phone-square:before,.fa-square-phone:before{content:"\f098"}.fa-phone-square-alt:before,.fa-square-phone-flip:before{content:"\f87b"}.fa-plus-square:before,.fa-square-plus:before{content:"\f0fe"}.fa-poll-h:before,.fa-square-poll-horizontal:before{content:"\f682"}.fa-poll:before,.fa-square-poll-vertical:before{content:"\f681"}.fa-square-root-alt:before,.fa-square-root-variable:before{content:"\f698"}.fa-rss-square:before,.fa-square-rss:before{content:"\f143"}.fa-share-alt-square:before,.fa-square-share-nodes:before{content:"\f1e1"}.fa-external-link-square-alt:before,.fa-square-up-right:before{content:"\f360"}.fa-square-xmark:before,.fa-times-square:before,.fa-xmark-square:before{content:"\f2d3"}.fa-stairs:before{content:"\e289"}.fa-stamp:before{content:"\f5bf"}.fa-star:before{content:"\f005"}.fa-star-and-crescent:before{content:"\f699"}.fa-star-half:before{content:"\f089"}.fa-star-half-alt:before,.fa-star-half-stroke:before{content:"\f5c0"}.fa-star-of-david:before{content:"\f69a"}.fa-star-of-life:before{content:"\f621"}.fa-gbp:before,.fa-pound-sign:before,.fa-sterling-sign:before{content:"\f154"}.fa-stethoscope:before{content:"\f0f1"}.fa-stop:before{content:"\f04d"}.fa-stopwatch:before{content:"\f2f2"}.fa-stopwatch-20:before{content:"\e06f"}.fa-store:before{content:"\f54e"}.fa-store-slash:before{content:"\e071"}.fa-street-view:before{content:"\f21d"}.fa-strikethrough:before{content:"\f0cc"}.fa-stroopwafel:before{content:"\f551"}.fa-subscript:before{content:"\f12c"}.fa-suitcase:before{content:"\f0f2"}.fa-medkit:before,.fa-suitcase-medical:before{content:"\f0fa"}.fa-suitcase-rolling:before{content:"\f5c1"}.fa-sun:before{content:"\f185"}.fa-superscript:before{content:"\f12b"}.fa-swatchbook:before{content:"\f5c3"}.fa-synagogue:before{content:"\f69b"}.fa-syringe:before{content:"\f48e"}.fa-t:before{content:"\54"}.fa-table:before{content:"\f0ce"}.fa-table-cells:before,.fa-th:before{content:"\f00a"}.fa-table-cells-large:before,.fa-th-large:before{content:"\f009"}.fa-columns:before,.fa-table-columns:before{content:"\f0db"}.fa-table-list:before,.fa-th-list:before{content:"\f00b"}.fa-ping-pong-paddle-ball:before,.fa-table-tennis-paddle-ball:before,.fa-table-tennis:before{content:"\f45d"}.fa-tablet-android:before,.fa-tablet:before{content:"\f3fb"}.fa-tablet-button:before{content:"\f10a"}.fa-tablet-alt:before,.fa-tablet-screen-button:before{content:"\f3fa"}.fa-tablets:before{content:"\f490"}.fa-digital-tachograph:before,.fa-tachograph-digital:before{content:"\f566"}.fa-tag:before{content:"\f02b"}.fa-tags:before{content:"\f02c"}.fa-tape:before{content:"\f4db"}.fa-cab:before,.fa-taxi:before{content:"\f1ba"}.fa-teeth:before{content:"\f62e"}.fa-teeth-open:before{content:"\f62f"}.fa-temperature-0:before,.fa-temperature-empty:before,.fa-thermometer-0:before,.fa-thermometer-empty:before{content:"\f2cb"}.fa-temperature-4:before,.fa-temperature-full:before,.fa-thermometer-4:before,.fa-thermometer-full:before{content:"\f2c7"}.fa-temperature-2:before,.fa-temperature-half:before,.fa-thermometer-2:before,.fa-thermometer-half:before{content:"\f2c9"}.fa-temperature-high:before{content:"\f769"}.fa-temperature-low:before{content:"\f76b"}.fa-temperature-1:before,.fa-temperature-quarter:before,.fa-thermometer-1:before,.fa-thermometer-quarter:before{content:"\f2ca"}.fa-temperature-3:before,.fa-temperature-three-quarters:before,.fa-thermometer-3:before,.fa-thermometer-three-quarters:before{content:"\f2c8"}.fa-tenge-sign:before,.fa-tenge:before{content:"\f7d7"}.fa-terminal:before{content:"\f120"}.fa-text-height:before{content:"\f034"}.fa-remove-format:before,.fa-text-slash:before{content:"\f87d"}.fa-text-width:before{content:"\f035"}.fa-thermometer:before{content:"\f491"}.fa-thumbs-down:before{content:"\f165"}.fa-thumbs-up:before{content:"\f164"}.fa-thumb-tack:before,.fa-thumbtack:before{content:"\f08d"}.fa-ticket:before{content:"\f145"}.fa-ticket-alt:before,.fa-ticket-simple:before{content:"\f3ff"}.fa-timeline:before{content:"\e29c"}.fa-toggle-off:before{content:"\f204"}.fa-toggle-on:before{content:"\f205"}.fa-toilet:before{content:"\f7d8"}.fa-toilet-paper:before{content:"\f71e"}.fa-toilet-paper-slash:before{content:"\e072"}.fa-toolbox:before{content:"\f552"}.fa-tooth:before{content:"\f5c9"}.fa-torii-gate:before{content:"\f6a1"}.fa-broadcast-tower:before,.fa-tower-broadcast:before{content:"\f519"}.fa-tractor:before{content:"\f722"}.fa-trademark:before{content:"\f25c"}.fa-traffic-light:before{content:"\f637"}.fa-trailer:before{content:"\e041"}.fa-train:before{content:"\f238"}.fa-subway:before,.fa-train-subway:before{content:"\f239"}.fa-train-tram:before,.fa-tram:before{content:"\f7da"}.fa-transgender-alt:before,.fa-transgender:before{content:"\f225"}.fa-trash:before{content:"\f1f8"}.fa-trash-arrow-up:before,.fa-trash-restore:before{content:"\f829"}.fa-trash-alt:before,.fa-trash-can:before{content:"\f2ed"}.fa-trash-can-arrow-up:before,.fa-trash-restore-alt:before{content:"\f82a"}.fa-tree:before{content:"\f1bb"}.fa-exclamation-triangle:before,.fa-triangle-exclamation:before,.fa-warning:before{content:"\f071"}.fa-trophy:before{content:"\f091"}.fa-truck:before{content:"\f0d1"}.fa-shipping-fast:before,.fa-truck-fast:before{content:"\f48b"}.fa-ambulance:before,.fa-truck-medical:before{content:"\f0f9"}.fa-truck-monster:before{content:"\f63b"}.fa-truck-moving:before{content:"\f4df"}.fa-truck-pickup:before{content:"\f63c"}.fa-truck-loading:before,.fa-truck-ramp-box:before{content:"\f4de"}.fa-teletype:before,.fa-tty:before{content:"\f1e4"}.fa-try:before,.fa-turkish-lira-sign:before,.fa-turkish-lira:before{content:"\e2bb"}.fa-level-down-alt:before,.fa-turn-down:before{content:"\f3be"}.fa-level-up-alt:before,.fa-turn-up:before{content:"\f3bf"}.fa-television:before,.fa-tv-alt:before,.fa-tv:before{content:"\f26c"}.fa-u:before{content:"\55"}.fa-umbrella:before{content:"\f0e9"}.fa-umbrella-beach:before{content:"\f5ca"}.fa-underline:before{content:"\f0cd"}.fa-universal-access:before{content:"\f29a"}.fa-unlock:before{content:"\f09c"}.fa-unlock-alt:before,.fa-unlock-keyhole:before{content:"\f13e"}.fa-arrows-alt-v:before,.fa-up-down:before{content:"\f338"}.fa-arrows-alt:before,.fa-up-down-left-right:before{content:"\f0b2"}.fa-long-arrow-alt-up:before,.fa-up-long:before{content:"\f30c"}.fa-expand-alt:before,.fa-up-right-and-down-left-from-center:before{content:"\f424"}.fa-external-link-alt:before,.fa-up-right-from-square:before{content:"\f35d"}.fa-upload:before{content:"\f093"}.fa-user:before{content:"\f007"}.fa-user-astronaut:before{content:"\f4fb"}.fa-user-check:before{content:"\f4fc"}.fa-user-clock:before{content:"\f4fd"}.fa-user-doctor:before,.fa-user-md:before{content:"\f0f0"}.fa-user-cog:before,.fa-user-gear:before{content:"\f4fe"}.fa-user-graduate:before{content:"\f501"}.fa-user-friends:before,.fa-user-group:before{content:"\f500"}.fa-user-injured:before{content:"\f728"}.fa-user-alt:before,.fa-user-large:before{content:"\f406"}.fa-user-alt-slash:before,.fa-user-large-slash:before{content:"\f4fa"}.fa-user-lock:before{content:"\f502"}.fa-user-minus:before{content:"\f503"}.fa-user-ninja:before{content:"\f504"}.fa-user-nurse:before{content:"\f82f"}.fa-user-edit:before,.fa-user-pen:before{content:"\f4ff"}.fa-user-plus:before{content:"\f234"}.fa-user-secret:before{content:"\f21b"}.fa-user-shield:before{content:"\f505"}.fa-user-slash:before{content:"\f506"}.fa-user-tag:before{content:"\f507"}.fa-user-tie:before{content:"\f508"}.fa-user-times:before,.fa-user-xmark:before{content:"\f235"}.fa-users:before{content:"\f0c0"}.fa-users-cog:before,.fa-users-gear:before{content:"\f509"}.fa-users-slash:before{content:"\e073"}.fa-cutlery:before,.fa-utensils:before{content:"\f2e7"}.fa-v:before{content:"\56"}.fa-shuttle-van:before,.fa-van-shuttle:before{content:"\f5b6"}.fa-vault:before{content:"\e2c5"}.fa-vector-square:before{content:"\f5cb"}.fa-venus:before{content:"\f221"}.fa-venus-double:before{content:"\f226"}.fa-venus-mars:before{content:"\f228"}.fa-vest:before{content:"\e085"}.fa-vest-patches:before{content:"\e086"}.fa-vial:before{content:"\f492"}.fa-vials:before{content:"\f493"}.fa-video-camera:before,.fa-video:before{content:"\f03d"}.fa-video-slash:before{content:"\f4e2"}.fa-vihara:before{content:"\f6a7"}.fa-virus:before{content:"\e074"}.fa-virus-covid:before{content:"\e4a8"}.fa-virus-covid-slash:before{content:"\e4a9"}.fa-virus-slash:before{content:"\e075"}.fa-viruses:before{content:"\e076"}.fa-voicemail:before{content:"\f897"}.fa-volleyball-ball:before,.fa-volleyball:before{content:"\f45f"}.fa-volume-high:before,.fa-volume-up:before{content:"\f028"}.fa-volume-down:before,.fa-volume-low:before{content:"\f027"}.fa-volume-off:before{content:"\f026"}.fa-volume-mute:before,.fa-volume-times:before,.fa-volume-xmark:before{content:"\f6a9"}.fa-vr-cardboard:before{content:"\f729"}.fa-w:before{content:"\57"}.fa-wallet:before{content:"\f555"}.fa-magic:before,.fa-wand-magic:before{content:"\f0d0"}.fa-magic-wand-sparkles:before,.fa-wand-magic-sparkles:before{content:"\e2ca"}.fa-wand-sparkles:before{content:"\f72b"}.fa-warehouse:before{content:"\f494"}.fa-water:before{content:"\f773"}.fa-ladder-water:before,.fa-swimming-pool:before,.fa-water-ladder:before{content:"\f5c5"}.fa-wave-square:before{content:"\f83e"}.fa-weight-hanging:before{content:"\f5cd"}.fa-weight-scale:before,.fa-weight:before{content:"\f496"}.fa-wheelchair:before{content:"\f193"}.fa-glass-whiskey:before,.fa-whiskey-glass:before{content:"\f7a0"}.fa-wifi-3:before,.fa-wifi-strong:before,.fa-wifi:before{content:"\f1eb"}.fa-wind:before{content:"\f72e"}.fa-window-maximize:before{content:"\f2d0"}.fa-window-minimize:before{content:"\f2d1"}.fa-window-restore:before{content:"\f2d2"}.fa-wine-bottle:before{content:"\f72f"}.fa-wine-glass:before{content:"\f4e3"}.fa-wine-glass-alt:before,.fa-wine-glass-empty:before{content:"\f5ce"}.fa-krw:before,.fa-won-sign:before,.fa-won:before{content:"\f159"}.fa-wrench:before{content:"\f0ad"}.fa-x:before{content:"\58"}.fa-x-ray:before{content:"\f497"}.fa-close:before,.fa-multiply:before,.fa-remove:before,.fa-times:before,.fa-xmark:before{content:"\f00d"}.fa-y:before{content:"\59"}.fa-cny:before,.fa-jpy:before,.fa-rmb:before,.fa-yen-sign:before,.fa-yen:before{content:"\f157"}.fa-yin-yang:before{content:"\f6ad"}.fa-z:before{content:"\5a"}.fa-sr-only,.fa-sr-only-focusable:not(:focus),.sr-only,.sr-only-focusable:not(:focus){position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}
\ No newline at end of file
diff --git a/resources/fonts/roboto.css b/resources/fonts/roboto.css
index 956730a3..52ba4da3 100644
--- a/resources/fonts/roboto.css
+++ b/resources/fonts/roboto.css
@@ -2,14 +2,14 @@
font-family: 'Roboto';
font-style: normal;
font-weight: 700;
- src: url('Roboto-Bold.woff2') format('woff2');
+ src: url('./Roboto-Bold.woff2') format('woff2');
}
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 500;
- src: url('Roboto-Medium.woff2') format('woff2');
+ src: url('./Roboto-Medium.woff2') format('woff2');
}
@@ -17,19 +17,19 @@
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
- src: url('Roboto-Regular.woff2') format('woff2');
+ src: url('./Roboto-Regular.woff2') format('woff2');
}
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 100;
- src: url('Roboto-Light.woff2') format('woff2');
+ src: url('./Roboto-Light.woff2') format('woff2');
}
@font-face {
font-family: 'Roboto Mono';
font-style: normal;
font-weight: 500;
- src: url('roboto-mono.woff') format('woff');
+ src: url('./roboto-mono.woff') format('woff');
}
diff --git a/resources/images/logo_tray.png b/resources/images/logo_tray.png
new file mode 100644
index 00000000..d6670a2a
Binary files /dev/null and b/resources/images/logo_tray.png differ
diff --git a/resources/images/logo_tray@x2.png b/resources/images/logo_tray@x2.png
new file mode 100644
index 00000000..c3c4f0c6
Binary files /dev/null and b/resources/images/logo_tray@x2.png differ
diff --git a/resources/mkdocs.yml b/resources/mkdocs.yml
index c35b874a..e6599ab8 100644
--- a/resources/mkdocs.yml
+++ b/resources/mkdocs.yml
@@ -1,10 +1,11 @@
site_name: Open Stage Control
repo_name: open-stage-control
-repo_url: https://github.com/jean-emmanuel/open-stage-control
+repo_url: https://framagit.org/jean-emmanuel/open-stage-control
edit_uri: tree/master/resources/docs/
-copyright: "Copyleft © Jean-Emmanuel Doucet @ AMMD (GNU/GPLv3)"
+copyright: "Copyleft © Jean-Emmanuel Doucet @ AMMD (GNU/GPLv3)"
site_description: "Libre and modular OSC / MIDI controller"
site_dir: '../app/docs/'
+latest_release: 1.31.2
theme:
name: 'material'
@@ -35,6 +36,9 @@ nav:
- docs/getting-started/server-configuration.md
- docs/getting-started/running-from-sources.md
- docs/getting-started/running-with-node.md
+ - Tutorials:
+ - docs/tutorials/first-steps.md
+ - docs/tutorials/change-property-with-osc.md
- User interface:
- docs/user-interface/launcher.md
- docs/user-interface/client.md
@@ -44,6 +48,8 @@ nav:
- docs/widgets/properties-reference.md
- docs/widgets/advanced-syntaxes.md
- docs/widgets/scripting.md
+ - docs/widgets/fragments.md
+ - docs/widgets/canvas.md
- MIDI:
- MIDI configuration: docs/midi/midi-configuration.md
- MIDI messages: docs/midi/midi-messages.md
@@ -57,9 +63,7 @@ nav:
- Client options: docs/client-options.md
- Remote control: docs/remote-control.md
- Credits: docs/credits.md
-
- - Bug Tracker:
- - 'Bug Tracker': 'https://github.com/jean-emmanuel/open-stage-control/issues'
+ - Changelog: docs/changelog.md
- Community:
- 'Community forums': 'https://openstagecontrol.discourse.group'
@@ -87,5 +91,10 @@ markdown_extensions:
custom_checkbox: true
- pymdownx.tilde
- pymdownx.keys
- - pymdownx.tabbed
+ - pymdownx.tabbed:
+ alternate_style: true
- pymdownx.details
+
+
+plugins:
+ - macros
diff --git a/resources/overrides/home.html b/resources/overrides/home.html
index 5ac01543..25fbe792 100644
--- a/resources/overrides/home.html
+++ b/resources/overrides/home.html
@@ -178,13 +178,6 @@
>
Get started
-
diff --git a/scripts/build-client.js b/scripts/build-client.js
deleted file mode 100644
index ee41004a..00000000
--- a/scripts/build-client.js
+++ /dev/null
@@ -1,95 +0,0 @@
-var build = require('./build'),
- path = require('path'),
- babelify = require('babelify'),
- nanohtml = require('nanohtml'),
- watch = process.argv.includes('--watch'),
- through = require('through'),
- minimatch = require('minimatch').Minimatch
-
-
-var ignores = ['**/*.min.js', '**/jquery.ui.js', 'gyronorm.complete.min.js'],
- transformWrapper = function(transform){
- return function(file, opts){
- if (ignores.some(pattern => minimatch(pattern).match(file))) {
- return through()
- } else {
- return transform(file, opts)
- }
- }
- }
-
-var transforms = [
- [transformWrapper(nanohtml)],
- [transformWrapper(babelify)]
-]
-
-console.warn('\033[36m=> Building compressed client scripts...\033[0m')
-transforms.push([transformWrapper(require('uglifyify')), {global: true, safari10: true}])
-
-var bundle = build({
- input: '../src/client/index.js',
- output: '../app/client/open-stage-control-client.js',
- options: {
- debug: true,
- insertGlobals: false,
- noParse: ['**/*.min.js', '**/jquery.ui.js'],
- cache: {},
- packageCache: {}
- },
- plugins: watch ? [require('watchify')] : [],
- transforms: transforms
-})
-
-if (watch) {
-
- var ansiHTML = require('ansi-html'),
- WS = require('../node_modules/ws')
-
- function send(msg, data){
- var ipc = new WS('ws://127.0.0.1:8080/dev')
- ipc.on('error', ()=>{})
- ipc.on('open', ()=>{
- ipc.send(JSON.stringify([msg, data]))
- ipc.close()
- })
- }
-
- bundle.b.on('update', hotBundle)
- bundle.b.on('log', function(msg) {console.warn('\x1b[36m%s\x1b[0m', msg)})
-
- function hotBundle() {
-
- var output = bundle()
-
- output.on('end', (err)=> {
- console.log('Build successful reloading...')
- send('reload')
- })
-
- output.on('error', (err)=> {
-
- console.error(err.stack)
- send('errorPopup',
- '' +
- ansiHTML(
- err.stack
- .replace(/^ at .*/gm, '') // remove useless stack
- .replace(new RegExp(path.resolve(__dirname + '/..'), 'g'),'.') // shorten file path
- .trim()
- .replace('\n','\n\n') // add 1 new line after 1st line
- ) +
- ''
- )
-
- })
-
- }
-
-
- hotBundle()
-
-} else {
-
- bundle()
-
-}
diff --git a/scripts/build-css.js b/scripts/build-css.js
index c2fe2d57..1884a440 100644
--- a/scripts/build-css.js
+++ b/scripts/build-css.js
@@ -1,16 +1,19 @@
-var sass = require('node-sass'),
+var sass = require('sass'),
path = require('path'),
fs = require('fs')
var indir = path.resolve(__dirname + '/../src/scss/'),
outdir= path.resolve(__dirname + '/../app/assets/')
+fs.mkdirSync(outdir + '/themes/', {recursive: true})
+
fs.readdirSync(indir + '/themes/').forEach(file => {
if (file.includes('.scss') && file !== 'default.scss') {
let result = sass.renderSync({
file: indir + '/themes/' + file,
- outputStyle: 'compressed'
+ outputStyle: 'compressed',
+ silenceDeprecations: ['mixed-decls', 'slash-div', 'import', 'legacy-js-api']
})
fs.writeFileSync(outdir + '/themes/' + file.split('/').pop().replace('scss', 'css'), result.css)
@@ -22,7 +25,8 @@ var result = sass.renderSync({
file: indir + '/index.scss',
outFile: outdir + '/open-stage-control.css',
outputStyle: 'compressed',
- sourceMap: true
+ sourceMap: true,
+ silenceDeprecations: ['mixed-decls', 'slash-div', 'import', 'legacy-js-api']
})
fs.writeFileSync(outdir + '/open-stage-control.css', result.css)
@@ -33,7 +37,7 @@ if (process.argv.includes('--reload')) {
var WS = require('../node_modules/ws')
- var ipc = new WS('ws://127.0.0.1:8080/dev')
+ var ipc = new WS('ws://127.0.0.1:8080/dev/')
ipc.on('error', ()=>{})
ipc.on('open', ()=>{
diff --git a/scripts/build-launcher.js b/scripts/build-launcher.js
deleted file mode 100644
index ff41b136..00000000
--- a/scripts/build-launcher.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var build = require('./build')
-
-build({
- input: '../src/launcher/index.js',
- output: '../app/launcher/open-stage-control-launcher.js',
- options: {
- debug: true,
- ignoreMissing: false,
- detectGlobals: false,
- bare: true,
- noParse: ['**/mathjs/dist/math.min.js']
- },
- exclude: [
- 'electron',
- ]
-})()
diff --git a/scripts/build-midi-bin.sh b/scripts/build-midi-bin.sh
deleted file mode 100755
index 87561ca5..00000000
--- a/scripts/build-midi-bin.sh
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/bin/bash
-
-# buid python midi addon for linux and windows
-
-cd src/python
-
-pyinstaller midi.py --onefile
-
-docker run -v "$(pwd):/src/" cdrx/pyinstaller-linux:python3
-mv dist/linux/midi midi-linux-x64
-
-docker run -v "$(pwd):/src/" cdrx/pyinstaller-linux:python3-32bit
-mv dist/linux/midi midi-linux-ia32
-
-docker run -v "$(pwd):/src/" cdrx/pyinstaller-windows:python3
-mv dist/windows/midi.exe midi-windows-x64.exe
-
-docker run -v "$(pwd):/src/" cdrx/pyinstaller-windows:python3-32bit
-mv dist/windows/midi.exe midi-windows-ia32.exe
-
-rm -rf __pycache__ build midi.spec dist
diff --git a/scripts/build-server.js b/scripts/build-server.js
deleted file mode 100644
index 5c2352ef..00000000
--- a/scripts/build-server.js
+++ /dev/null
@@ -1,27 +0,0 @@
-var build = require('./build'),
- babelify = require('babelify')
-
-build({
- input: '../src/server/index.js',
- output: '../app/server/open-stage-control-server.js',
- options: {
- commonDir: false,
- ignoreMissing: true,
- debug: true,
- builtins: false,
- commondir: false,
- insertGlobalVars: {
- __filename: true,
- __dirname: true,
- process: true,
- electron: true,
- global: true
- },
- browserField: false,
- },
- ignore: 'serialport',
- exclude: [
- 'electron',
- './fsevents.node' // osx binary module, to be copied as is
- ]
-})()
diff --git a/scripts/build.js b/scripts/build.js
deleted file mode 100644
index 80de408b..00000000
--- a/scripts/build.js
+++ /dev/null
@@ -1,49 +0,0 @@
-var browserify = require('browserify'),
- exorcist = require('exorcist'),
- licensify = require('licensify'),
- fs = require('fs'),
- path = require('path')
-
-
-module.exports = (opt) => {
-
- var {input, output, options, ignore, exclude, transforms, plugins} = opt,
- inputPath = path.resolve(__dirname + '/' + input),
- outputPath = path.resolve(__dirname + '/' + output),
- b
-
- if (!plugins) plugins = []
- if (!plugins.includes(licensify)) plugins.push(licensify)
-
- b = browserify(inputPath, options)
-
- if (ignore) b.ignore(ignore)
- if (exclude) b.exclude(exclude)
-
- for (var plugin of plugins) {
- b.plugin(plugin)
- }
-
- if (transforms) {
- for (var transform of transforms) {
- var [t, opts] = transform
- b.transform(t, opts)
- }
- }
-
- function bundle() {
-
- var output = b.bundle()
-
- var toWrite = output.pipe(exorcist(outputPath + '.map'))
- toWrite.pipe(fs.createWriteStream(outputPath))
-
- return output
-
- }
-
- bundle.b = b
-
- return bundle
-
-}
diff --git a/scripts/client.plugin-watch.js b/scripts/client.plugin-watch.js
new file mode 100644
index 00000000..41204c80
--- /dev/null
+++ b/scripts/client.plugin-watch.js
@@ -0,0 +1,40 @@
+var ansiHTML = require('ansi-html'),
+ WS = require('../node_modules/ws'),
+ path = require('path')
+
+function send(msg, data){
+ var ipc = new WS('ws://127.0.0.1:8080/dev/')
+ ipc.on('error', ()=>{})
+ ipc.on('open', ()=>{
+ ipc.send(JSON.stringify([msg, data]))
+ ipc.close()
+ })
+}
+
+module.exports = function watchChangePlugin() {
+
+ var reloadClient = false
+
+ return {
+
+ buildEnd(error) {
+
+ if (error) {
+ var msg = `
+ ${error.message.replace(path.resolve(__dirname + '/..'),'')} at line ${error.loc.line}\n${error.frame}
+ `
+ send('errorPopup', msg.trim())
+ reloadClient = false
+ } else {
+ reloadClient = true
+ }
+
+ },
+
+ writeBundle() {
+ if (reloadClient) {
+ send('reload')
+ }
+ }
+ }
+}
diff --git a/scripts/client.rollup.config.js b/scripts/client.rollup.config.js
new file mode 100644
index 00000000..c23b26ae
--- /dev/null
+++ b/scripts/client.rollup.config.js
@@ -0,0 +1,98 @@
+var commonjs = require('@rollup/plugin-commonjs'),
+ nodeResolve = require('@rollup/plugin-node-resolve'),
+ json = require('@rollup/plugin-json'),
+ babel = require('@rollup/plugin-babel'),
+ terser = require('@rollup/plugin-terser'),
+ copy = require('rollup-plugin-copy'),
+ license = require('rollup-plugin-license'),
+ watchChange = require('./client.plugin-watch'),
+ package = require('../package.json'),
+ path = require('path'),
+ watch = process.argv.includes('--watch')
+
+module.exports = {
+ input: 'src/client/index.mjs',
+ output: [
+ {
+ dir: 'app/client/',
+ chunkFileNames: `[name].js`,
+ entryFileNames: `[name].js`,
+ format: 'es',
+ sourcemap: true,
+ sourcemapExcludeSources: true
+ },
+ ],
+ treeshake: false,
+ watch: {
+ clearScreen: false
+ },
+ plugins: [
+ json(),
+ nodeResolve({
+ browser: true
+ }),
+ commonjs(),
+ watch ? {} : babel({
+ babelHelpers: 'bundled',
+ babelrc: false,
+ exclude: [
+ /node_modules\/core-js/,
+ /node_modules\/ace-builds/
+ ],
+ presets: [[
+ '@babel/preset-env',
+ {
+ targets: {
+ ios: '11',
+ chrome: '70'
+ },
+ useBuiltIns: 'usage',
+ corejs: 3,
+ modules:false
+ }
+ ]]
+ }),
+ watch ? {} : terser({
+ sourceMap: true,
+ keep_classnames: true,
+ keep_fnames: true,
+ output: {
+ comments: false,
+ },
+ }),
+ {
+ name: 'remove-node-modules-from-source-map',
+ enforce: 'post',
+ transform(code, id) {
+ if (id.includes('node_modules')) {
+ return { code, map: { mappings: '' } }
+ }
+ }
+ },
+ watch ? {} :license({
+ thirdParty: {
+ includeSelf: true,
+ output: 'app/client/LICENSES',
+ },
+ }),
+ watch ? {} : copy({
+ targets: [
+ {src: 'resources/images/logo_nobadge.png', dest: 'app/assets/', rename: 'favicon.png'},
+ {src: 'resources/images/logo.png', dest: 'app/assets/'},
+ {src: 'resources/images/logo_tray.png', dest: 'app/assets/'},
+ {src: 'resources/images/logo_tray@x2.png', dest: 'app/assets/'},
+ {src: 'resources/images/logo_16x16.png', dest: 'app/assets/'},
+ {src: 'resources/fonts/*', dest: 'app/assets/fonts/'},
+ {src: 'node_modules/ace-builds/src-min/worker-css.js', dest: 'app/client/ace/'},
+ {src: 'node_modules/ace-builds/src-min/worker-html.js', dest: 'app/client/ace/'},
+ {src: 'node_modules/ace-builds/src-min/worker-javascript.js', dest: 'app/client/ace/'},
+ {src: 'node_modules/ace-builds/src-min/ace.js', dest: 'app/client/ace/'},
+ {src: 'src/html/client.html', dest: 'app/client/', rename: 'index.html', transform: (contents)=>{
+ return contents.toString().replace(/\$\{([^\}]+)\}/g, (m, p1)=>{return package[p1]})
+ }},
+
+ ]
+ }),
+ watchChange()
+ ]
+};
diff --git a/scripts/copy-assets.js b/scripts/copy-assets.js
deleted file mode 100644
index 1f691665..00000000
--- a/scripts/copy-assets.js
+++ /dev/null
@@ -1,56 +0,0 @@
-var cpr = require('cpr'),
- fs = require('fs'),
- path = require('path'),
- files = [
- ['../resources/images/logo_nobadge.png', '../app/assets/favicon.png'],
- ['../resources/images/logo.png', '../app/assets/logo.png'],
- ['../LICENSE', '../app/LICENSE'],
- ['../src/python/', '../app/server/python/'],
- ['../resources/fonts/', '../app/assets/fonts/'],
- ['../src/html/launcher.html', '../app/launcher/index.html'],
- ['../node_modules/fsevents/fsevents.node', '../app/server/fsevents.node'],
- ]
-
-for (var i in files) {
- cpr(...files[i].map(f => path.resolve(__dirname + '/' + f)), {
- overwrite: true
- })
-}
-
-
-var packageJson = require('../package.json'),
- appJson = {},
- copiedProps = [
- "name",
- "productName",
- "description",
- "version",
- "author",
- "repository",
- "homepage",
- "license",
- "yargs",
- "engines"
- ]
-
-for (var k of copiedProps) {
- appJson[k] = packageJson[k]
-}
-
-appJson.main = appJson.bin = "index.js"
-appJson.scripts = {
- "start": "electron index.js",
- "start-node": "node index.js"
-}
-
-appJson.optionalDependencies = {
- electron: packageJson.optionalDependencies.electron
-}
-
-fs.writeFileSync(path.resolve(__dirname + '/../app/package.json'), JSON.stringify(appJson, null, ' '))
-
-var clientHtml = fs.readFileSync(path.resolve(__dirname + '/../src/html/client.html'))
- .toString()
- .replace(/\$\{version\}/g, appJson.version)
-
-fs.writeFileSync(path.resolve(__dirname + '/../app/client/index.html'), clientHtml)
diff --git a/scripts/dist_packages.sh b/scripts/dist_packages.sh
new file mode 100755
index 00000000..8805f515
--- /dev/null
+++ b/scripts/dist_packages.sh
@@ -0,0 +1,45 @@
+#!/bin/bash
+
+# clean
+rm -rf dist app
+
+# buid
+npm run build
+npm run build-docs
+npm run package -- --all
+PLATFORM=darwin ARCH=arm64 npm run package
+npm run package-node
+
+# get current version
+VERSION=$(sed -nE 's/^\s*"version":\ "(.*?)",$/\1/p' package.json)
+
+cd dist
+
+# fetch & copy midi bins
+mkdir tmp && cd tmp
+cp ../../bin/osc-midi-* ./
+chmod +x *
+touch .expect-midi-bin
+cp {.expect-midi-bin,osc-midi-linux} ../open-stage-control-linux-x64/resources/app/server/python/
+cp {.expect-midi-bin,osc-midi-windows.exe} ../open-stage-control-win32-x64/resources/app/server/python/
+cp {.expect-midi-bin,osc-midi-osx} ../open-stage-control-darwin-x64/open-stage-control.app/Contents/Resources/app/server/python/
+cp {.expect-midi-bin,osc-midi-osx} ../open-stage-control-darwin-arm64/open-stage-control.app/Contents/Resources/app/server/python/
+cd ..
+rm -rf tmp
+
+# make packages
+mkdir packages
+npm run deb64
+npm run rpm64
+mv *.{deb,rpm} packages/
+
+mv open-stage-control-node open-stage-control_${VERSION}_node
+mv open-stage-control-win32-x64 open-stage-control_${VERSION}_win32-x64
+mv open-stage-control-linux-x64 open-stage-control_${VERSION}_linux-x64
+
+echo "Creating zip packages..."
+zip -q -r --symlinks packages/open-stage-control_${VERSION}_osx-x64.zip open-stage-control-darwin-x64/open-stage-control.app
+zip -q -r --symlinks packages/open-stage-control_${VERSION}_osx-arm64.zip open-stage-control-darwin-arm64/open-stage-control.app
+zip -q -r packages/open-stage-control_${VERSION}_node.zip open-stage-control_${VERSION}_node
+zip -q -r packages/open-stage-control_${VERSION}_win32-x64.zip open-stage-control_${VERSION}_win32-x64
+zip -q -r packages/open-stage-control_${VERSION}_linux-x64.zip open-stage-control_${VERSION}_linux-x64
diff --git a/scripts/docs.rollup.config.js b/scripts/docs.rollup.config.js
new file mode 100644
index 00000000..5b27aa0f
--- /dev/null
+++ b/scripts/docs.rollup.config.js
@@ -0,0 +1,25 @@
+var commonjs = require('@rollup/plugin-commonjs'),
+ nodeResolve = require('@rollup/plugin-node-resolve'),
+ json = require('@rollup/plugin-json')
+
+module.exports = {
+ input: 'src/docs/widgets-reference.mjs',
+ output: [
+ {
+ file: 'src/docs/widgets-reference.js',
+ inlineDynamicImports: true,
+ format: 'commonjs',
+ sourcemap: false,
+ strict: false,
+ indent: false,
+ name: '_'
+ },
+ ],
+ plugins: [
+ json(),
+ nodeResolve({
+ browser: true
+ }),
+ commonjs()
+ ]
+};
diff --git a/scripts/launcher.rollup.config.js b/scripts/launcher.rollup.config.js
new file mode 100644
index 00000000..c0b2eda1
--- /dev/null
+++ b/scripts/launcher.rollup.config.js
@@ -0,0 +1,48 @@
+var commonjs = require('@rollup/plugin-commonjs'),
+ nodeResolve = require('@rollup/plugin-node-resolve'),
+ json = require('@rollup/plugin-json'),
+ babel = require('@rollup/plugin-babel'),
+ terser = require('@rollup/plugin-terser'),
+ copy = require('rollup-plugin-copy'),
+ license = require('rollup-plugin-license'),
+ package = require('../package.json'),
+ path = require('path')
+
+module.exports = {
+ input: 'src/launcher/index.mjs',
+ output: [
+ {
+ dir: 'app/launcher/',
+ chunkFileNames: `[name].js`,
+ format: 'commonjs',
+ sourcemap: true,
+ sourcemapExcludeSources: true,
+ strict: false
+ },
+ ],
+ treeshake: false,
+ external: ['electron'],
+ watch: {
+ clearScreen: false
+ },
+ plugins: [
+ json(),
+ commonjs({
+ ignoreGlobal: true,
+ ignoreDynamicRequires: true
+ }),
+ nodeResolve(),
+ terser(),
+ license({
+ thirdParty: {
+ includeSelf: true,
+ output: 'app/launcher/LICENSES',
+ },
+ }),
+ copy({
+ targets: [
+ {src: 'src/html/launcher.html', dest: 'app/launcher/', rename: 'index.html'},
+ ]
+ })
+ ]
+};
diff --git a/scripts/package-node.js b/scripts/package-node.js
index c4934eb2..6fdae1bc 100644
--- a/scripts/package-node.js
+++ b/scripts/package-node.js
@@ -1,8 +1,4 @@
-var browserify = require('browserify'),
- exorcist = require('exorcist'),
- licensify = require('licensify'),
- fs = require('fs'),
- cpr = require('cpr'),
+var cpr = require('cpr'),
path = require('path'),
files = ['../app', '../dist/open-stage-control-node']
diff --git a/scripts/package.js b/scripts/package.js
index 40049303..de33b599 100644
--- a/scripts/package.js
+++ b/scripts/package.js
@@ -1,4 +1,4 @@
-const packager = require('electron-packager'),
+const packager = require('@electron/packager'),
path = require('path'),
appData = require('../app/package.json'),
safeFFMPEG = require('electron-packager-plugin-non-proprietary-codecs-ffmpeg').default,
@@ -12,7 +12,7 @@ packager({
name: appData.name,
platform: all ? ['linux', 'win32', 'darwin'] : process.env.PLATFORM,
arch: process.env.ARCH || 'x64',
- electronVersion: process.env.ARCH === 'armv7l' ? '1.7.11' : require('../package.json').optionalDependencies.electron,
+ electronVersion: process.env.ELECTRON_VERSION || require('../package.json').optionalDependencies.electron,
overwrite: true,
out: path.resolve(__dirname + '/../dist'),
icon: path.resolve(__dirname + '/../resources/images/logo'),
diff --git a/scripts/server.rollup.config.js b/scripts/server.rollup.config.js
new file mode 100644
index 00000000..dac5b03a
--- /dev/null
+++ b/scripts/server.rollup.config.js
@@ -0,0 +1,65 @@
+var commonjs = require('@rollup/plugin-commonjs'),
+ nodeResolve = require('@rollup/plugin-node-resolve'),
+ json = require('@rollup/plugin-json'),
+ babel = require('@rollup/plugin-babel'),
+ terser = require('@rollup/plugin-terser'),
+ copy = require('rollup-plugin-copy'),
+ license = require('rollup-plugin-license'),
+ package = require('../package.json'),
+ path = require('path')
+
+module.exports = {
+ input: {
+ 'node/index': 'src/server/node/index.mjs',
+ 'electron/index': 'src/server/electron/index.mjs'
+ },
+ output: [
+ {
+ dir: 'app/server/',
+ chunkFileNames: `[name].js`,
+ format: 'commonjs',
+ sourcemap: true,
+ sourcemapExcludeSources: true,
+ strict: false
+ },
+ ],
+ treeshake: false,
+ external: ['electron', '@serialport'],
+ watch: {
+ clearScreen: false
+ },
+ plugins: [
+ json(),
+ commonjs({
+ ignoreGlobal: true,
+ ignoreDynamicRequires: true
+ }),
+ nodeResolve({
+ preferBuiltins: true
+ }),
+ license({
+ thirdParty: {
+ includeSelf: true,
+ output: 'app/server/LICENSES',
+ },
+ }),
+ terser({
+ sourceMap: true,
+ keep_classnames: true,
+ keep_fnames: true,
+ output: {
+ comments: false,
+ },
+ }),
+ copy({
+ targets: [
+ {src: 'src/index.js', dest: 'app/'},
+ {src: 'src/server/index.js', dest: 'app/server/'},
+ {src: 'src/server/python/*.py', dest: 'app/server/python/'},
+ {src: 'node_modules/fsevents/fsevents.node', dest: 'app/server/'},
+ {src: 'LICENSE', dest: 'app/'},
+ {src: 'package.json', dest: 'app/'},
+ ]
+ })
+ ]
+};
diff --git a/src/client/backup.js b/src/client/backup.js
deleted file mode 100644
index 98a264c4..00000000
--- a/src/client/backup.js
+++ /dev/null
@@ -1,59 +0,0 @@
-var cache = require('./managers/cache'),
- localBackup = cache.get('backup', false)
-
-
-module.exports = {
-
- exists: localBackup !== null,
-
- save: ()=>{
-
- var session = require('./managers/session/'),
- state = require('./managers/state'),
- editor = require('./editor/')
-
- if (session.session) {
- cache.set('backup', {
- session: session.session.data,
- sessionPath: session.sessionPath,
- state: state.get(),
- history: editor.history,
- historyState: editor.historyState,
- editorEnabled: editor.enabled
- }, false)
- }
-
- },
-
- load: ()=>{
-
- var session = require('./managers/session/'),
- state = require('./managers/state'),
- editor = require('./editor/'),
- ipc = require('./ipc/')
-
- if (localBackup) {
-
- var data = localBackup
-
- cache.remove('backup', false)
- session.load(data.session, ()=>{
-
- state.set(data.state, false)
-
- editor.clearHistory()
- editor.history = data.history
- editor.historyState = data.historyState
-
- if (data.editorEnabled) editor.enable()
-
-
- ipc.send('sessionSetPath', {path: data.sessionPath})
- session.setSessionPath(data.sessionPath)
-
- })
-
- }
-
- }
-}
diff --git a/src/client/backup.mjs b/src/client/backup.mjs
new file mode 100644
index 00000000..8e1cef83
--- /dev/null
+++ b/src/client/backup.mjs
@@ -0,0 +1,62 @@
+import cache from './managers/cache.mjs'
+
+var session, state, editor, ipc
+;(async()=>{
+ session = (await import('./managers/session/index.mjs')).default
+ state = (await import('./managers/state.mjs')).default
+ editor = (await import('./editor/index.mjs')).default
+ ipc = (await import('./ipc/index.mjs')).default
+})()
+
+var localBackup = cache.get('backup', false)
+
+
+export const exists = localBackup !== null
+
+export function save() {
+
+ if (session.session) {
+ cache.set('backup', {
+ session: session.session.data,
+ saveMode: session.saveMode,
+ sessionPath: session.sessionPath,
+ fragments: session.fragments,
+ state: state.get(),
+ history: editor.history,
+ historyState: editor.historyState,
+ editorEnabled: editor.enabled,
+ }, false)
+ }
+
+}
+
+export function load() {
+
+ if (localBackup) {
+
+ var data = localBackup
+
+ cache.remove('backup', false)
+ for (let k in data.fragments) {
+ session.setFragment({path: k, fileContent: data.fragments[k]})
+ }
+ session.load(data.session, ()=>{
+
+ session.setSaveMode(data.saveMode)
+ state.set(data.state, false)
+
+ editor.clearHistory()
+ editor.history = data.history
+ editor.historyState = data.historyState
+
+ if (data.editorEnabled) editor.enable()
+
+
+ ipc.send('sessionSetPath', {path: data.sessionPath})
+ session.setSessionPath(data.sessionPath)
+
+ })
+
+ }
+
+}
diff --git a/src/client/dom.js b/src/client/dom.js
deleted file mode 100644
index cb455cfe..00000000
--- a/src/client/dom.js
+++ /dev/null
@@ -1,107 +0,0 @@
-var readyCallbacks = [],
- initState = false
-
-module.exports = {
-
- init: function() {
-
- for (var i in readyCallbacks) {
- readyCallbacks[i]()
- }
-
- initState = true
-
- },
-
- ready: function(callback) {
- if (initState) {
- callback()
- } else {
- readyCallbacks.push(callback)
- }
- },
-
- dispatchEvent: function(element, name, data) {
-
- var event = new CustomEvent(name, {
- detail: data,
- bubbles: true,
- cancelable: true
- })
-
- element.dispatchEvent(event)
-
- },
-
- addEventListener: function(element, events, listener, capture) {
-
- var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
-
- for (var i in eventsAsObject) {
-
- element.addEventListener(eventsAsObject[i], listener, capture)
-
- }
-
- },
-
- get: function(a, b) {
-
- var context = b ? a : document,
- selector = b || a,
- nodes
-
- if (selector.indexOf('>') === 0) selector = ':scope ' + selector
-
- if (selector.indexOf(' ') === -1 && selector.indexOf(',') === -1) {
- if (selector.indexOf('#') === 0 && context === document) {
- nodes = [document.getElementById(selector.substr(1, selector.length - 1))]
- } else if (selector.indexOf('.') === 0) {
- nodes = context.getElementsByClassName(selector.substr(1, selector.length - 1))
- }
- }
-
- if (!nodes) nodes = context.querySelectorAll(selector)
-
- return [...nodes]
-
- },
-
- 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, container) {
-
- 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) && element !== container)
- }
-
- return {
- left: offsetLeft,
- top: offsetTop
- }
- }
-
-}
diff --git a/src/client/dom.mjs b/src/client/dom.mjs
new file mode 100644
index 00000000..798802b6
--- /dev/null
+++ b/src/client/dom.mjs
@@ -0,0 +1,82 @@
+export function dispatchEvent(element, name, data) {
+
+ var event = new CustomEvent(name, {
+ detail: data,
+ bubbles: true,
+ cancelable: true
+ })
+
+ element.dispatchEvent(event)
+
+}
+
+export function addEventListener(element, events, listener, capture) {
+
+ var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
+
+ for (var i in eventsAsObject) {
+
+ element.addEventListener(eventsAsObject[i], listener, capture)
+
+ }
+
+}
+
+export function get(a, b) {
+
+ var context = b ? a : document,
+ selector = b || a,
+ nodes
+
+ if (selector.indexOf('>') === 0) selector = ':scope ' + selector
+
+ if (selector.indexOf(' ') === -1 && selector.indexOf(',') === -1 && selector.indexOf('[') === -1) {
+ if (selector.indexOf('#') === 0 && context === document) {
+ nodes = [document.getElementById(selector.substr(1, selector.length - 1))]
+ } else if (selector.lastIndexOf('.') === 0) {
+ nodes = context.getElementsByClassName(selector.substr(1, selector.length - 1))
+ }
+ }
+
+ if (!nodes) nodes = context.querySelectorAll(selector)
+
+ return [...nodes]
+
+}
+
+export function each(context, selector, callback) {
+
+ var nodes = get(context, selector)
+
+ nodes.forEach(callback)
+
+ return nodes
+
+}
+
+export function index(element) {
+ var parent = element.parentNode
+ return parent ? Array.prototype.indexOf.call(parent.children, element) : -1
+}
+
+export function offset(element, container) {
+
+ 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) && element !== container)
+ }
+
+ return {
+ left: offsetLeft,
+ top: offsetTop
+ }
+}
diff --git a/src/client/editor/context-menu.js b/src/client/editor/context-menu.mjs
similarity index 67%
rename from src/client/editor/context-menu.js
rename to src/client/editor/context-menu.mjs
index 1a71757b..a13fbf26 100644
--- a/src/client/editor/context-menu.js
+++ b/src/client/editor/context-menu.mjs
@@ -1,18 +1,29 @@
-var {updateWidget} = require('./data-workers'),
- {categories} = require('../widgets/'),
- widgetManager = require('../managers/widgets'),
- {icon} = require('../ui/utils'),
- editor = require('./'),
- locales = require('../locales'),
- ContextMenu = require('../ui/context-menu'),
- contextMenu = new ContextMenu()
+import {updateWidget} from './data-workers.mjs'
+import {categories} from '../widgets/index.mjs'
+import widgetManager from '../managers/widgets.mjs'
+import {icon} from '../ui/utils.mjs'
+import editor from './index.mjs'
+import locales from '../locales/index.mjs'
+import ContextMenu from '../ui/context-menu.mjs'
+import {GRIDWIDTH, PXSCALE} from '../globals.mjs'
+var sessionManager
+;(async()=>{
+ sessionManager = (await import('../managers/session/index.mjs')).default
+})()
+
+
+var contextMenu = new ContextMenu()
var multiSelectKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
var handleClick = function(event) {
- if (!editor.enabled) return
+ if (
+ !editor.enabled ||
+ event.detail.button === 1 ||
+ (event.detail.metaKey && event.detail.shiftKey)
+ ) return
if (!event.detail[multiSelectKey] && event.type !== 'fast-right-click' && (
event.target.classList.contains('no-widget-select') ||
@@ -24,6 +35,10 @@ var handleClick = function(event) {
if (!targetWidget) return
+ while (targetWidget.meta.not_editable && targetWidget.parent) {
+ targetWidget = targetWidget.parent
+ }
+
// if the widget is not already selected
if (!targetWidget.container.classList.contains('editing') || event.detail.ctrlKey || event.detail.shiftKey) {
// add a flag to the original event to prevent draginit
@@ -33,9 +48,34 @@ var handleClick = function(event) {
}
+ if (editor.inspector.focusedInput) {
+ editor.inspector.onChange()
+ editor.inspector.focusedInput = null
+ if (!document.body.contains(eventData.target)) return
+ }
+
if (event.type !== 'fast-right-click') {
- if (editor.inspector.focusedInput) editor.inspector.onChange()
+
+ if (targetWidget.getProp('type') === 'tab') {
+ targetWidget.parent.setValue(targetWidget.parent.children.indexOf(targetWidget), {sync: true, send: true})
+ }
+
+ if (
+ event.target.tagName === 'LI' && // Project tree
+ event.detail.shiftKey &&
+ editor.selectedWidgets.length > 0 &&
+ targetWidget.parent === editor.selectedWidgets[0].parent
+ ) {
+ var siblings = targetWidget.parent.children,
+ from = siblings.indexOf(editor.selectedWidgets[0]),
+ to = siblings.indexOf(targetWidget),
+ range = siblings.slice(Math.min(from, to), Math.max(from, to) + 1).filter(w=>!editor.selectedWidgets.includes(w))
+
+ targetWidget = editor.selectedWidgets.concat(range)
+ }
+
editor.select(targetWidget, {multi: event.detail[multiSelectKey]})
+
}
// right-click menu
@@ -58,20 +98,34 @@ var handleClick = function(event) {
if (parent !== widgetManager) {
- if (event.target.tagName !== 'LI') {
+ if (event.target.tagName !== 'LI') { // not Project tree
actions.push({
label: icon('project-diagram') + ' ' + locales('editor_show_in_tree'),
action: ()=>{
editor.widgetTree.showWidget(editor.selectedWidgets[0])
+ editor.widgetTree.blinkSelected()
},
shortcut: 't'
})
+
+ } else {
+
actions.push({
- separator: true
+ label: icon('eye') + ' ' + locales('editor_show_in_session'),
+ action: ()=>{
+ for (let w of editor.selectedWidgets) {
+ editor.widgetTree.showWidgetInSession(w)
+ }
+ },
+ shortcut: 'y'
})
}
+ actions.push({
+ separator: true
+ })
+
actions.push({
label: icon('copy') + ' ' + locales('editor_copy'),
action: editor.copyWidget.bind(editor),
@@ -137,7 +191,7 @@ var handleClick = function(event) {
}
- if (parent !== widgetManager && editor.selectedWidgets[0].parent.children.length > 1) {
+ if (parent !== widgetManager && editor.selectedWidgets.length === 1 && editor.selectedWidgets[0].parent.children.length > 1) {
actions.push({
separator: true
})
@@ -147,28 +201,28 @@ var handleClick = function(event) {
{
label: locales('editor_back'),
action: ()=>{
- editor.handleKeyboard('home')
+ editor.handleKeydown('home')
},
shortcut: 'Home'
},
{
label: locales('editor_farther'),
action: ()=>{
- editor.handleKeyboard('pageup')
+ editor.handleKeydown('pageup')
},
shortcut: 'Page Up'
},
{
label: locales('editor_closer'),
action: ()=>{
- editor.handleKeyboard('pagedown')
+ editor.handleKeydown('pagedown')
},
shortcut: 'Page Down'
},
{
label: locales('editor_front'),
action: ()=>{
- editor.handleKeyboard('end')
+ editor.handleKeydown('end')
},
shortcut: 'End'
}
@@ -212,11 +266,15 @@ var handleClick = function(event) {
data[0].widgets.push(newData)
var indexes = {addedIndexes: [data[0].widgets.length -1]}
+
updateWidget(editor.selectedWidgets[0], indexes)
-
-
editor.pushHistory(indexes)
+ var newWidget = editor.selectedWidgets[0].children[editor.selectedWidgets[0].children.length - 1]
+ editor.select([newWidget])
+ if (!editor.widgetTree.parent.minimized) editor.widgetTree.showWidget(newWidget)
+
+
}
})
@@ -229,9 +287,11 @@ var handleClick = function(event) {
}
- if (actions.length) actions.push({
- separator: true
- })
+ if (data.length == 1 && widget.childrenType !== undefined) {
+ if (actions.length) actions.push({
+ separator: true
+ })
+ }
if (data.length == 1 && widget.childrenType !== 'tab') {
actions.push({
@@ -249,9 +309,17 @@ var handleClick = function(event) {
data[0].tabs.push({})
var indexes = {addedIndexes: [data[0].tabs.length -1]}
+
updateWidget(editor.selectedWidgets[0], indexes)
editor.pushHistory(indexes)
+ var newWidget = editor.selectedWidgets[0].children[editor.selectedWidgets[0].children.length - 1]
+
+ editor.select([newWidget])
+ if (!editor.widgetTree.parent.minimized) editor.widgetTree.showWidget(newWidget)
+ newWidget.parent.setValue(newWidget.parent.children.indexOf(newWidget))
+
+
}
})
@@ -260,6 +328,20 @@ var handleClick = function(event) {
}
+ if (parent !== widgetManager && data.length === 1) {
+
+ actions.push({
+ separator: true
+ })
+
+ actions.push({
+ label: icon('file-download') + ' ' + locales('editor_fragment_export'),
+ action: ()=>{
+ sessionManager.saveFragment(editor.selectedWidgets[0].props)
+ }
+ })
+ }
+
if (parent !== widgetManager) {
actions.push({
diff --git a/src/client/editor/data-workers.js b/src/client/editor/data-workers.mjs
similarity index 80%
rename from src/client/editor/data-workers.js
rename to src/client/editor/data-workers.mjs
index 124ca0d3..3a1b1f8e 100644
--- a/src/client/editor/data-workers.js
+++ b/src/client/editor/data-workers.mjs
@@ -1,29 +1,28 @@
-var widgetManager = require('../managers/widgets'),
- resize = require('../events/resize'),
- stateManager = require('../managers/state'),
- parser = require('../parser'),
- Panel, Matrix,
- editor,
- scrollState = {}
+import widgetManager from '../managers/widgets.mjs'
+import stateManager from '../managers/state.mjs'
+import parser from '../parser.mjs'
+import * as resize from '../events/resize.mjs'
-setTimeout(()=>{
- editor = require('./')
- Panel = require('../widgets/containers/panel')
- Matrix = require('../widgets/containers/matrix')
-})
+var Panel, Matrix, editor
+;(async()=>{
+ Panel = (await import('../widgets/containers/panel.mjs')).default
+ Matrix = (await import('../widgets/containers/matrix.mjs')).default
+ editor = (await import('./index.mjs')).default
+})()
+
+var scrollState = {}
function updateWidget(widget, options={}) {
- if (options.changedProps) {
+ if (options.editedProps) {
// alternate routine for small edits
- var propNames = options.changedProps
+ var propNames = options.editedProps
if (
// if non dynamic props have changed, skip this and use rebuild routine
!propNames.some(n => !widget.isDynamicProp(n))
) {
-
- var edited = widget.updateProps(options.changedProps, null, {fromEditor: true}) || widget
+ var edited = widget.updateProps(options.editedProps, null, {fromEditor: true}) || widget
editor.widgetTree.updateTree(editor.selectedWidgets)
@@ -77,7 +76,7 @@ function updateWidget(widget, options={}) {
// save state
if (stateManager.queueCounter === 0) {
- scrollState = {}
+ scrollState = {} // scrollable modals don't store their scroll state in their value
}
stateManager.incrementQueue()
for (let w of removedWidgets) {
@@ -89,8 +88,8 @@ function updateWidget(widget, options={}) {
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 (w.getProp('scroll') && w.getProp('type') === 'modal') {
+ var s = w.getScroll()
if (s[0] !== 0 || s[1] !== 0) {
scrollState[w.getProp('id')] = s
}
@@ -107,12 +106,13 @@ function updateWidget(widget, options={}) {
parentNode: widget.parentNode,
reCreateOptions: options.reCreateOptions,
locals: widget.parsersLocalScope,
+ variables: widget.variables,
hash: widget.hash,
children: children,
- index: index
+ index: index,
+ meta: widget.meta
})
-
newWidget.container.parentNode.replaceChild(newWidget.container, widget.container)
if (newWidget.getProp('type') === 'tab') newWidget.parent.trigger('tab-created', {widget: widget})
@@ -141,7 +141,7 @@ function updateWidget(widget, options={}) {
if (stateManager.queueCounter === 0) {
for (let id in scrollState) {
for (let w of widgetManager.getWidgetById(id)) {
- if (w.scroll) w.scroll(scrollState[id])
+ if (w.getProp('scroll')) w.setScroll(scrollState[id][0], scrollState[id][1])
}
}
}
@@ -177,17 +177,19 @@ var incrementWidget = function(data, root){
return data
}
- var id = data.id,
- address = data.address
+ var id = String(data.id),
+ address = String(data.address)
if (id && address == '/' + id) {
data.address = 'auto'
- } else if (!address.match(/^auto|\/control|\/note|\/program|\/sysex|\/key_pressure|\/channel_pressure|\/pitch/) !== 'auto') {
+ } else if (!address.match(/^(auto|\/control|\/note|\/program|\/sysex|\/mtc|\/key_pressure|\/channel_pressure|\/pitch)$/)) {
+
+ var addressref = widgetManager.createAddressRef(null, data.preArgs,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
@@ -233,7 +235,7 @@ var incrementWidget = function(data, root){
}
-module.exports = {
- updateWidget:updateWidget,
- incrementWidget:incrementWidget
+export {
+ updateWidget,
+ incrementWidget
}
diff --git a/src/client/editor/diff.js b/src/client/editor/diff.js
deleted file mode 100644
index 8f2902a9..00000000
--- a/src/client/editor/diff.js
+++ /dev/null
@@ -1,32 +0,0 @@
-module.exports = {
-
- diff: require('jsondiffpatch'),
-
- diffToWidget: function(widget, diff) {
-
- // traverse a diff patch and the associated widget
- // to return the first node (widget and sub-patch) with actual changes
-
- var children = diff.tabs || diff.widgets
-
- if (children) {
- var childrenKeys = Object.keys(children),
- deletedChildren = childrenKeys.filter(x => typeof x === 'string' && x.match(/_[0-9]+/)),
- changedChildren = childrenKeys.filter(x => !isNaN(x))
- }
-
- if (
- !children ||
- Array.isArray(children) || // 'tabs' or 'widgets' property created
- deletedChildren.length || // 'tabs' or 'widgets' property created
- changedChildren.length !== 1 || // children reordered (or same property edited in multiple widgets, but case ignored)
- Array.isArray(children[changedChildren[0]]) // child item created
- ) {
- return [widget, diff]
- }
-
- return module.exports.diffToWidget(widget.children[changedChildren[0]], children[changedChildren[0]])
-
- }
-
-}
diff --git a/src/client/editor/diff.mjs b/src/client/editor/diff.mjs
new file mode 100644
index 00000000..1d3bd083
--- /dev/null
+++ b/src/client/editor/diff.mjs
@@ -0,0 +1,29 @@
+import diff from 'jsondiffpatch'
+
+export {diff}
+export function diffToWidget(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 diffToWidget(widget.children[changedChildren[0]], children[changedChildren[0]])
+
+}
diff --git a/src/client/editor/index.js b/src/client/editor/index.mjs
similarity index 57%
rename from src/client/editor/index.js
rename to src/client/editor/index.mjs
index 2fc74755..d7e262f2 100644
--- a/src/client/editor/index.js
+++ b/src/client/editor/index.mjs
@@ -1,38 +1,48 @@
-var {updateWidget, incrementWidget} = require('./data-workers'),
- keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
- {diff, diffToWidget} = require('./diff'),
- widgetManager = require('../managers/widgets'),
- {deepCopy} = require('../utils'),
- {defaults} = require('../widgets/'),
- macOs = (navigator.platform || '').match('Mac'),
- UiSelectArea = require('../ui/ui-selectarea'),
- UiInspector = require('../ui/ui-inspector'),
- UiTree = require('../ui/ui-tree'),
- UiDragResize = require('../ui/ui-dragresize'),
- uiConsole = require('../ui/ui-console'),
- notifications = require('../ui/notifications'),
- locales = require('../locales'),
- {leftUiSidePanel, rightUiSidePanel} = require('../ui/'),
- ipc = require('../ipc'),
- sessionManager
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import {updateWidget, incrementWidget} from './data-workers.mjs'
+import {diff, diffToWidget} from './diff.mjs'
+import widgetManager from '../managers/widgets.mjs'
+import {deepCopy} from '../utils.mjs'
+import {defaults, widgets} from '../widgets/index.mjs'
+import UiSelectArea from '../ui/ui-selectarea.mjs'
+import UiInspector from '../ui/ui-inspector.mjs'
+import UiTree from '../ui/ui-tree.mjs'
+import UiDragResize from '../ui/ui-dragresize.mjs'
+import uiConsole from '../ui/ui-console.mjs'
+import notifications from '../ui/notifications.mjs'
+import locales from '../locales/index.mjs'
+import {leftUiSidePanel, rightUiSidePanel} from '../ui/index.mjs'
+import ipc from '../ipc/index.mjs'
+import {DOM, GRIDWIDTH, GRIDWIDTH_CSS, ENV, PXSCALE, setGRIDWIDTH, READ_ONLY} from '../globals.mjs'
+import zoom from '../ui/zoom.mjs'
-setTimeout(()=>{
- sessionManager = require('../managers/session/')
-})
+var sessionManager
+;(async()=>{
+ sessionManager = (await import('../managers/session/index.mjs')).default
+ await import('./context-menu.mjs')
+})()
+const macOs = (navigator.platform || '').match('Mac')
const HISTORY_SIZE = 50
class Editor {
constructor() {
+ zoom.editor = this
+
this.inspector = new UiInspector({selector: '#osc-inspector'})
this.inspector.on('update', (event)=>{
- var {propName, value} = event,
+ var {propName, value, preventHistory} = event,
newWidgets = [],
error = false
+ if (this.selectedWidgets.some(w=>w.getProp('lock')) && propName !== 'lock') {
+ this.select(this.selectedWidgets)
+ return
+ }
+
for (var w of this.selectedWidgets) {
let previousValue = w.props[propName]
@@ -45,12 +55,12 @@ class Editor {
try {
- newWidgets.push(updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1}))
+ newWidgets.push(updateWidget(w, {editedProps: [propName], preventSelect: this.selectedWidgets.length > 1}))
} catch (e) {
w.props[propName] = previousValue
- updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1})
+ updateWidget(w, {editedProps: [propName], preventSelect: this.selectedWidgets.length > 1})
if (uiConsole.minimized) notifications.add({
class: 'error',
@@ -59,7 +69,7 @@ class Editor {
})
console.error(
`Error while setting ${propName} to: ${JSON.stringify(value)}.\n` +
- 'It\'s probably a bug, please open a new bug ticket with the followigin informations at' +
+ 'It\'s probably a bug, please open a new bug ticket with the following informations at' +
'https://github.com/jean-emmanuel/open-stage-control/issues'
)
throw e
@@ -70,34 +80,53 @@ class Editor {
if (error) return
- this.pushHistory()
+ if (!preventHistory) this.pushHistory()
if (newWidgets.length > 1) this.select(newWidgets)
})
- this.widgetTree = new UiTree({selector: '#osc-tree'})
+ this.widgetTree = new UiTree({selector: '#osc-tree', parent: leftUiSidePanel})
this.widgetTree.on('sorted', (event)=>{
- var {widget, oldIndex, newIndex} = event,
- propName = widget.props.tabs && widget.props.tabs.length ? 'tabs' : 'widgets'
+ var {oldIndex, newIndex, from, to} = event,
+ propName = from.childrenType + 's',
+ container
- if (widget.props[propName].length < 2) return
+ if (from === to) {
- widget.props[propName].splice(newIndex, 0, widget.props[propName].splice(oldIndex, 1)[0])
+ if (to.props[propName].length < 2) return
- var indices = [newIndex, oldIndex]
- if (Math.abs(oldIndex - newIndex) > 1) {
- for (var i = Math.min(newIndex, oldIndex) + 1; i < Math.max(newIndex, oldIndex); i++) {
- indices.push(i)
+ to.props[propName].splice(newIndex, 0, to.props[propName].splice(oldIndex, 1)[0])
+
+ var indices = [newIndex, oldIndex]
+ if (Math.abs(oldIndex - newIndex) > 1) {
+ for (var i = Math.min(newIndex, oldIndex) + 1; i < Math.max(newIndex, oldIndex); i++) {
+ indices.push(i)
+ }
}
+
+ container = updateWidget(to, {removedIndexes: indices, addedIndexes: indices, preventSelect: true})
+
+ this.pushHistory({removedIndexes: indices, addedIndexes: indices})
+ this.select(container.children[newIndex])
+
+ } else {
+
+ to.props[propName].splice(newIndex, 0, from.props[propName][oldIndex])
+ from.props[propName].splice(oldIndex, 1)
+
+ updateWidget(from, {removedIndexes: [oldIndex], preventSelect: true})
+ container = updateWidget(to, {addedIndexes: [newIndex], preventSelect: true})
+
+ this.pushHistory()
+ this.select(container.children[newIndex])
+
}
- var container = updateWidget(widget, {removedIndexes: indices, addedIndexes: indices, preventSelect: true})
+ if (!event.ignoreTree) this.widgetTree.showWidget(container.children[newIndex])
- this.pushHistory({removedIndexes: indices, addedIndexes: indices})
- this.select(container.children[newIndex])
})
@@ -109,9 +138,14 @@ class Editor {
this.widgetDragResize.on('move', (e)=>{
var left = Math.round(e.left / GRIDWIDTH) * GRIDWIDTH,
top = Math.round(e.top / GRIDWIDTH) * GRIDWIDTH
- var dX = left - e.initLeft,
- dY = top - e.initTop
- this.moveWidget(dX, dY)
+
+ if (e.copying) {
+ this.duplicateWidget(left, top, e.shiftKey)
+ } else {
+ var dX = left - e.initLeft,
+ dY = top - e.initTop
+ this.moveWidget(dX, dY)
+ }
})
this.widgetDragResize.on('drag-resize', (e)=>{
var width = Math.round(e.width / GRIDWIDTH) * GRIDWIDTH,
@@ -124,13 +158,14 @@ class Editor {
this.selectedWidgets = []
this.clipboard = null
+ this.tmpClipboard = null
this.idClipboard = null
ipc.on('clipboard', (data)=>{
this.clipboard = data.clipboard
this.idClipboard = data.idClipboard
})
- this.usePercents = false
+ this.usePercents = !!ENV.usepercents
this.enabled = false
this.grid = true
@@ -158,6 +193,8 @@ class Editor {
'mod + x',
'mod + v',
'mod + shift + v',
+ 'mod + d',
+ 'mod + shift + d',
macOs ? 'backspace' : 'delete',
'alt + up',
'alt + down',
@@ -177,35 +214,75 @@ class Editor {
'pagedown',
'home',
'end',
- 't'
+ 't',
+ 'y',
+ 'f2',
+ 'h',
+ 'mod + f'
]
for (let c of combos) {
keyboardJS.bind(c, (e)=>{
- this.handleKeyboard(c, e)
+ e.catchedByEditor = true
+ this.handleKeydown(c, e)
+ }, (e)=>{
+ e.catchedByEditor = true
+ this.handleKeyup(c, e)
})
}
})
- this.selectarea = new UiSelectArea('[data-widget]:not(.not-editable)', (elements)=>{
+ this.selectarea = new UiSelectArea('[data-widget]:not(.not-editable)', (elements, e)=>{
- elements = elements.map(e => widgetManager.getWidgetByElement(e, ':not(.not-editable)')).filter(e => e)
+ var widgets = 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, lassoEnd: i == elements.length - 1})
+ if (e.ctrlKey) {
+
+ // only add siblings to current selection
+
+ for (var i in widgets) {
+ this.select(widgets[i], {multi:true, fromLasso:true, lassoEnd: i == widgets.length - 1})
+ }
+
+ } else {
+
+ // select the largest group of siblings in area
+
+ var groups = {}
+ for (var w of widgets) {
+ var g = w.parent.hash
+ if (!g) continue
+ if (!groups[g]) groups[g] = []
+ if (!groups[g].includes(w)) groups[g].push(w)
+ }
+
+ groups = Object.values(groups)
+
+ // if the event started from a container widget (but not in the project tree)
+ // remove groups that are more than one level away from that container
+ if (e.target.tagName !== 'LI' && this.selectedWidgets[0].childrenType !== undefined) {
+ groups = groups.filter(g=>g[0].parent === this.selectedWidgets[0] || g[0].parent === this.selectedWidgets[0].parent)
+ }
+
+ var lengths = groups.map(g=>g.length),
+ selection = groups[lengths.lastIndexOf(Math.max(...lengths))]
+
+ if (selection) this.select(selection)
}
+
+
})
}
- handleKeyboard(combo, e){
+ handleKeydown(combo, e){
if (
this.inspector.helpModalOpened ||
- e && e.target && e.target.tagName.match(/INPUT|TEXTAREA|SELECT/)
+ e && e.target && e.target.tagName.match(/INPUT|TEXTAREA|SELECT|OSC-CONSOLE/)
) return
if (e) e.preventDefault()
@@ -237,6 +314,14 @@ class Editor {
this.pasteWidget(this.mousePosition.x, this.mousePosition.y, true)
break
+ case 'mod + d':
+ this.duplicateWidget(this.mousePosition.x, this.mousePosition.y, false)
+ break
+
+ case 'mod + shift + d':
+ this.duplicateWidget(this.mousePosition.x, this.mousePosition.y, true)
+ break
+
case 'backspace':
case 'delete':
this.deleteWidget()
@@ -246,7 +331,7 @@ class Editor {
case 'alt + down':
case 'alt + right':
case 'alt + left':
- if (!this.selectedWidgets.length) return
+ if (!this.selectedWidgets.length || this.selectedWidgets[0].parent === widgetManager) 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
@@ -263,10 +348,10 @@ class Editor {
break
- case 'up':
- case 'down':
- case 'right':
- case 'left':
+ case 'mod + up':
+ case 'mod + down':
+ case 'mod + right':
+ case 'mod + left':
if (!this.selectedWidgets.length) return
if (this.selectedWidgets[0].props.top === undefined && e.key.match(/Arrow(Up|Down)/)) return
@@ -301,33 +386,26 @@ class Editor {
}
break
- case 'mod + up':
- case 'mod + down':
- case 'mod + right':
- case 'mod + left':
+ case 'up':
+ case 'down':
+ case 'right':
+ case 'left':
if (!this.selectedWidgets.length) return
var curWidget = this.selectedWidgets[0],
toSelect = null
- if (e.key === 'ArrowUp' && curWidget.parent !== widgetManager) {
+ if (e.key === 'ArrowLeft' && curWidget.parent !== widgetManager) {
toSelect = curWidget.parent
- } else if (e.key === 'ArrowDown') {
+ } else if (e.key === 'ArrowRight') {
- 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
- }
+ if (curWidget.children[0] && !curWidget.children[0].meta.not_editable) {
+ toSelect = curWidget.children[0]
}
- }
- else if((e.key == 'ArrowLeft') || (e.key == 'ArrowRight')){
+ } else if((e.key == 'ArrowUp') || (e.key == 'ArrowDown')){
if (curWidget.parent === widgetManager) return
@@ -337,7 +415,7 @@ class Editor {
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
+ var nextIdx = (idx + (e.key === 'ArrowUp' ? -1 : 1 ) + toSelectList.length) % toSelectList.length
toSelect = toSelectList[nextIdx]
}
}
@@ -353,7 +431,7 @@ class Editor {
case 'pageup':
case 'home':
case 'end':
- if (!this.selectedWidgets.length || this.selectedWidgets[0].parent.children.length <= 1) return
+ if (this.selectedWidgets.length !== 1 || this.selectedWidgets[0].parent.children.length <= 1) return
var curWidget2 = this.selectedWidgets[0],
index = curWidget2.parent.children.indexOf(curWidget2),
@@ -367,9 +445,11 @@ class Editor {
if (index !== newIndex) {
this.widgetTree.trigger('sorted', {
- widget: curWidget2.parent,
+ from: curWidget2.parent,
+ to: curWidget2.parent,
oldIndex: index,
- newIndex: newIndex
+ newIndex: newIndex,
+ ignoreTree: true
})
}
break
@@ -377,21 +457,75 @@ class Editor {
case 't':
if (!this.selectedWidgets.length) return
this.widgetTree.showWidget(editor.selectedWidgets[0])
+ this.widgetTree.blinkSelected()
+ break
+ case 'y':
+ if (!this.selectedWidgets.length) return
+ for (let w of editor.selectedWidgets) {
+ this.widgetTree.showWidgetInSession(w)
+ }
+ this.widgetTree.showWidget(editor.selectedWidgets[0])
+ break
+ case 'f2':
+ if (!this.selectedWidgets.length) return
+ if (this.selectedWidgets[0].props.label === undefined && this.selectedWidgets[0].props.html === undefined) return
+ if (!this.inspector.expandedCategories.includes('style')) {
+ var header = DOM.get(this.inspector.container, '.category-header[data-name="style"]')[0]
+ if (header) {
+ header.parentNode.classList.add('expanded')
+ this.inspector.expandedCategories.push('style')
+ }
+ }
+ var labelProp = this.selectedWidgets[0].props.label === undefined ? 'html' : 'label'
+ var input = DOM.get(this.inspector.container, `textarea[name="${labelProp}"]`)[0]
+ if (input) {
+ if (input._ace_input) {
+ input._ace_input.focus()
+ } else {
+ input.focus()
+ input.setSelectionRange(0, input.value.length)
+ input.scrollIntoView({block: 'center'})
+ }
+ }
+ break
+ case 'h':
+ document.body.classList.add('editor-hide-selection')
+ break
+ case 'mod + f':
+ if (this.widgetTree.parent.minimized) this.widgetTree.parent.restore()
+ this.widgetTree.filter.focus()
break
-
}
}
+ handleKeyup(combo, e){
+
+ if (
+ this.inspector.helpModalOpened ||
+ (e && e.target && e.target.tagName && e.target.tagName.match(/INPUT|TEXTAREA|SELECT/))
+ ) return
+
+ if (e) e.preventDefault()
+
+ switch (combo) {
+
+ case 'h':
+ document.body.classList.remove('editor-hide-selection')
+ break
+
+ }
+ }
+
toggleGrid() {
this.grid = !this.grid
- GRIDWIDTH = this.grid ? 10 : 1
+ setGRIDWIDTH(this.grid ? GRIDWIDTH_CSS : 1)
- document.documentElement.style.setProperty('--grid-width', GRIDWIDTH)
+ document.body.style.setProperty('--grid-width', GRIDWIDTH)
document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
}
@@ -403,13 +537,19 @@ class Editor {
this.enabled = true
document.body.classList.add('editor-enabled')
+ document.body.classList.remove('editor-disabled')
this.widgetTree.updateTree(this.selectedWidgets)
leftUiSidePanel.enable()
rightUiSidePanel.enable()
+
+ // keyboardJS hack: prevent releaseAllKeys when switching context
+ var locale = keyboardJS._locale
+ keyboardJS._locale = null
keyboardJS.setContext('editing')
+ keyboardJS._locale = locale
this.oscContainer.addEventListener('mousemove', this.mouveMoveHandler)
this.oscContainer.addEventListener('mouseleave', this.mouveLeaveHandler)
@@ -420,13 +560,17 @@ class Editor {
disable() {
-
this.unselect()
this.selectedWidgets = []
+ document.body.classList.add('editor-disabled')
document.body.classList.remove('editor-enabled')
+ // keyboardJS hack: prevent releaseAllKeys when switching context
+ var locale = keyboardJS._locale
+ keyboardJS._locale = null
keyboardJS.setContext('global')
+ keyboardJS._locale = locale
this.oscContainer.removeEventListener('mousemove', this.mouveMoveHandler)
this.oscContainer.removeEventListener('mouseleave', this.mouveLeaveHandler)
@@ -491,6 +635,16 @@ class Editor {
}
+ if (this.selectedWidgets.length) {
+ var parent = this.selectedWidgets[0].parent
+ while (parent !== widgetManager) {
+ if (parent.getProp('lock')) {
+ this.selectedWidgets = [parent]
+ }
+ parent = parent.parent
+ }
+ }
+
if (options.fromLasso && !options.lassoEnd) return
this.unselect()
@@ -518,6 +672,9 @@ class Editor {
}
this.widgetTree.select(this.selectedWidgets)
this.widgetDragResize.create(this.selectedWidgets)
+ if (!this.widgetTree.parent.minimized) {
+ this.widgetTree.showWidget(editor.selectedWidgets[editor.selectedWidgets.length-1])
+ }
}
@@ -534,7 +691,7 @@ class Editor {
}
- copyWidget() {
+ copyWidget(tmp) {
if (!this.selectedWidgets.length) return
if (this.selectedWidgets[0].getProp('type') === 'root') return
@@ -549,6 +706,19 @@ class Editor {
}
+ duplicateWidget(x, y, increment) {
+
+ if (!this.selectedWidgets.length) return
+ if (this.selectedWidgets[0].getProp('type') === 'root') return
+
+ this.tmpClipboard = deepCopy(this.selectedWidgets.map((w)=>w.props))
+ var index = Math.max(...this.selectedWidgets.map(w=>w.parent.children.indexOf(w)))
+ this.select(this.selectedWidgets[0].parent)
+ this.pasteWidget(x, y, increment, index + 1, true)
+ this.select(this.selectedWidgets[0].children[index + 1])
+
+ }
+
cutWidget() {
this.copyWidget()
@@ -556,16 +726,21 @@ class Editor {
}
- pasteWidget(x, y, increment) {
+ pasteWidget(x, y, increment, index, tmp) {
+
+ if (!this.selectedWidgets.length) return
+
+ var clipboard = tmp ? this.tmpClipboard : this.clipboard
+
+ if (clipboard === null) return
- if (!this.selectedWidgets.length || this.clipboard === null) return
if (
this.selectedWidgets[0].childrenType === undefined ||
- this.clipboard[0].type === 'tab' && this.selectedWidgets[0].childrenType === 'widget' ||
- this.clipboard[0].type !== 'tab' && this.selectedWidgets[0].childrenType === 'tab'
+ clipboard[0].type === 'tab' && this.selectedWidgets[0].childrenType === 'widget' ||
+ clipboard[0].type !== 'tab' && this.selectedWidgets[0].childrenType === 'tab'
) return
- var pastedData = deepCopy(this.clipboard),
+ var pastedData = deepCopy(clipboard),
minTop = Infinity,
minLeft = Infinity
@@ -601,18 +776,27 @@ class Editor {
for (let i in pastedData) {
- if (pastedData[i]._pleft) {
- pastedData[i].left = ((pastedData[i]._aleft - minLeft + x) * 100 / this.selectedWidgets[0].widget.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
- } else {
- pastedData[i].left += - minLeft + x
+ if (!String(pastedData[i].left).match(/\{/)) {
+
+ if (pastedData[i]._pleft) {
+ pastedData[i].left = ((pastedData[i]._aleft - minLeft + x) * 100 / this.selectedWidgets[0].widget.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
+ } else {
+ pastedData[i].left += - minLeft + x
+ }
+
}
- if (pastedData[i]._ptop) {
- pastedData[i].top = ((pastedData[i]._atop - minTop + y) * 100 / this.selectedWidgets[0].widget.offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
- } else {
- pastedData[i].top += - minTop + y
+ if (!String(pastedData[i].top).match(/\{/)) {
+
+ if (pastedData[i]._ptop) {
+ pastedData[i].top = ((pastedData[i]._atop - minTop + y) * 100 / this.selectedWidgets[0].widget.offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
+ } else {
+ pastedData[i].top += - minTop + y
+ }
+
}
+
}
}
@@ -620,20 +804,27 @@ class Editor {
// paste data
- var store = this.clipboard[0].type === 'tab' ? 'tabs' : 'widgets'
+ var store = clipboard[0].type === 'tab' ? 'tabs' : 'widgets'
this.selectedWidgets[0].props[store] = this.selectedWidgets[0].props[store] || []
- this.selectedWidgets[0].props[store] = this.selectedWidgets[0].props[store].concat(pastedData)
- var indexes = {addedIndexes: []}
+ var indexes = {addedIndexes: []},
+ start = index || this.selectedWidgets[0].props[store].length
+
+ this.selectedWidgets[0].props[store].splice(start, 0, ...pastedData)
+
for (let i = 0; i < pastedData.length; i++) {
- indexes.addedIndexes.push(this.selectedWidgets[0].props[store].length - 1 - i )
+ indexes.addedIndexes.push(start + pastedData.length - 1 - i )
}
+ if (index)indexes.reuseChildren=false
+
updateWidget(this.selectedWidgets[0], indexes)
this.pushHistory(indexes)
+ if (!leftUiSidePanel.minimized) this.widgetTree.showWidget(this.selectedWidgets[0].children[0])
+
}
pasteWidgetAsClone(x, y) {
@@ -673,8 +864,12 @@ class Editor {
var indexes = {addedIndexes: [this.selectedWidgets[0].props.widgets.length -1]}
updateWidget(this.selectedWidgets[0], indexes)
+
this.pushHistory(indexes)
+ if (!leftUiSidePanel.minimized) this.widgetTree.showWidget(this.selectedWidgets[0].children[0])
+
+
}
@@ -710,51 +905,92 @@ class Editor {
}
- resizeWidget(deltaW, deltaH, ui) {
+ /* Utility function to retrieve the first sizable node */
+ getWidgetParentContainer(widget) {
+
+ while (widget.parent instanceof widgets.folder) {
+ widget = widget.parent
+ }
+
+ return widget.container.parentNode
+
+ }
+
+ resizeWidget(deltaW, deltaH) {
if (!this.selectedWidgets.length) return
- var newWidgets = []
+ if (this.selectedWidgets.some(w=>w.getProp('lock'))) {
+ this.createSelectionBlock()
+ return
+ }
+
+ var newWidgets = [],
+ area = this.widgetDragResize,
+ editedProps = []
for (var i = 0; i < this.selectedWidgets.length; i++) {
let w = this.selectedWidgets[i],
- nW, nH
+ nW, nH, nL, nT
- if (i === 0 && ui) {
- nW = ui.originalSize.width + deltaW
- nH = ui.originalSize.height + deltaH
+ nW = w.container.offsetWidth + deltaW * w.container.offsetWidth / area.initWidth
+ nH = w.container.offsetHeight + deltaH * w.container.offsetHeight / area.initHeight
- } else {
- nW = w.container.offsetWidth + deltaW
- nH = w.container.offsetHeight + deltaH
+ if (this.selectedWidgets.length > 1) {
+ nL = w.container.offsetLeft + deltaW * (w.container.offsetLeft - area.initLeft) / area.initWidth
+ nT = w.container.offsetTop + deltaH * (w.container.offsetTop - area.initTop) / area.initHeight
}
- if (w.props.width !== undefined && w.parent.getProp('layout') !== 'vertical') {
+ if (deltaW !== 0 && w.props.width !== undefined && w.parent.getProp('layout') !== 'vertical') {
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).replace(/\.?0+$/, '') + '%'
+ w.props.width = (100 * PXSCALE * newWidth / this.getWidgetParentContainer(w).offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.width = newWidth
}
+ editedProps.push('width')
+
+ if (this.selectedWidgets.length > 1) {
+ var newLeft = Math.max(nL, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.left === 'string' && w.props.left.indexOf('%') > -1) {
+ w.props.left = (100 * PXSCALE * newLeft / this.getWidgetParentContainer(w).offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
+ } else if (w.props.left !== 'auto'){
+ w.props.left = newLeft
+ }
+ editedProps.push('left')
+ }
+
}
- if (w.props.height !== undefined && w.parent.getProp('layout') !== 'horizontal') {
+ if (deltaH !== 0 && w.props.height !== undefined && w.parent.getProp('layout') !== 'horizontal') {
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).replace(/\.?0+$/, '') + '%'
+ w.props.height = (100 * PXSCALE * newHeight / this.getWidgetParentContainer(w).offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.height = newHeight
}
+ editedProps.push('height')
+
+ if (this.selectedWidgets.length > 1) {
+ var newTop = Math.max(nT, GRIDWIDTH) / PXSCALE
+ if (typeof w.props.top === 'string' && w.props.top.indexOf('%') > -1) {
+ w.props.top = (100 * PXSCALE * newTop / this.getWidgetParentContainer(w).offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
+ } else if (w.props.top !== 'auto'){
+ w.props.top = newTop
+ }
+ editedProps.push('top')
+ }
}
- if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {changedProps: ['width', 'height'], preventSelect: this.selectedWidgets.length > 1}))
+ if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {editedProps: editedProps, preventSelect: this.selectedWidgets.length > 1}))
}
this.pushHistory()
- if (newWidgets.length > 1) this.select(newWidgets, {preventSelect: this.selectedWidgets.length > 1})
+ // if (newWidgets.length > 1) this.select(newWidgets, {preventSelect: this.selectedWidgets.length > 1})
+ this.createSelectionBlock()
}
@@ -762,30 +998,36 @@ class Editor {
if (!this.selectedWidgets.length) return
+ if (this.selectedWidgets.some(w=>w.getProp('lock'))) {
+ this.createSelectionBlock()
+ return
+ }
+
var newWidgets = []
for (var w of this.selectedWidgets) {
var newTop = Math.max(parseInt(w.container.offsetTop) / PXSCALE + deltaY, 0)
if (typeof w.props.top === 'string' && w.props.top.indexOf('%') > -1) {
- w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
+ w.props.top = (100 * PXSCALE * newTop / this.getWidgetParentContainer(w).offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.top = newTop
}
var newLeft = Math.max(parseInt(w.container.offsetLeft) / PXSCALE + deltaX, 0)
if (typeof w.props.left === 'string' && w.props.left.indexOf('%') > -1) {
- w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
+ w.props.left = (100 * PXSCALE * newLeft / this.getWidgetParentContainer(w).offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.left = newLeft
}
- newWidgets.push(updateWidget(w, {changedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
+ newWidgets.push(updateWidget(w, {editedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
}
this.pushHistory()
- if (newWidgets.length > 1) this.select(newWidgets)
+ // if (newWidgets.length > 1) this.select(newWidgets)
+ this.createSelectionBlock()
}
@@ -793,7 +1035,9 @@ class Editor {
pushHistory(indexes) {
- this.unsavedSession = true
+ if (!ENV.noWarning) {
+ this.unsavedSession = true
+ }
if (this.historyState > -1) {
this.history.splice(0, this.historyState + 1)
@@ -866,7 +1110,7 @@ class Editor {
if (indexes) {
options = {...indexes}
} else {
- options.changedProps = Object.keys(subpatch)
+ options.editedProps = Object.keys(subpatch)
options.reuseChildren = false
}
@@ -889,6 +1133,4 @@ class Editor {
var editor = new Editor()
-module.exports = editor
-
-require('./context-menu')
+export default editor
diff --git a/src/client/events/click.js b/src/client/events/click.mjs
similarity index 69%
rename from src/client/events/click.js
rename to src/client/events/click.mjs
index 206072c0..44f76794 100644
--- a/src/client/events/click.js
+++ b/src/client/events/click.mjs
@@ -1,4 +1,7 @@
-const iOS = require('../ui/ios')
+import iOS from '../ui/ios.mjs'
+import editor from '../editor/index.mjs'
+import {DOM, FOCUSABLE, ENV} from '../globals.mjs'
+
const macOs = (navigator.platform || '').match('Mac')
var longTouchTimer = false,
@@ -18,7 +21,11 @@ if (macOs) {
})
} else {
document.body.addEventListener('contextmenu', (event)=>{
- if (event.target && (!event.target.tagName.match(/INPUT|TEXTAREA|OSC-CONSOLE|OSC-CONSOLE-MESSAGE/))) event.preventDefault()
+ if (
+ event.target &&
+ !event.target.classList.contains('ace_content') &&
+ !event.target.tagName.match(/INPUT|TEXTAREA|OSC-CONSOLE|OSC-CONSOLE-MESSAGE/)
+ ) event.preventDefault()
})
}
@@ -33,6 +40,10 @@ function mouseToFastClick(event) {
DOM.dispatchEvent(e.target, name, e)
+ if (!FOCUSABLE && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
+ console.debug('ELECTRON.BLUR()')
+ }
+
}
function touchToFastClick(event) {
@@ -59,6 +70,10 @@ function touchToFastClick(event) {
}, 600)
+ if (ENV.nofocus && !editor.enabled && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
+ console.debug('ELECTRON.BLUR()')
+ }
+
}
if (!iOS) document.addEventListener('pointerdown', mouseToFastClick, true)
diff --git a/src/client/events/dom-event.mjs b/src/client/events/dom-event.mjs
new file mode 100644
index 00000000..24c81d77
--- /dev/null
+++ b/src/client/events/dom-event.mjs
@@ -0,0 +1,42 @@
+export default function(eventName, options={}){
+
+ var widget_storage_key = '_' + eventName + '_widget'
+
+ function closestWidgetContainer(target) {
+ var container = target
+ while (container !== null) {
+ if (container[widget_storage_key]) {
+ return container
+ } else {
+ container = container.parentNode
+ }
+ }
+ return null
+ }
+
+ function triggerWidgetEvent(target, event) {
+ var container = closestWidgetContainer(target)
+ if (container) container[widget_storage_key].trigger(eventName, event)
+ }
+
+ document.addEventListener(eventName, (event)=>{
+ triggerWidgetEvent(event.target, event)
+ }, {passive: !!options.passive, capture: !!options.capture})
+
+ return {
+
+ setup: function(options) {
+ var {element} = options || {element: this.container}
+ element[widget_storage_key] = this
+ },
+
+ teardown: function(options) {
+ var {element} = options || {element: this.container}
+ delete element[widget_storage_key]
+ }
+
+
+ }
+
+
+}
diff --git a/src/client/events/double-click.js b/src/client/events/double-click.mjs
similarity index 91%
rename from src/client/events/double-click.js
rename to src/client/events/double-click.mjs
index cba97f49..1649c411 100644
--- a/src/client/events/double-click.js
+++ b/src/client/events/double-click.mjs
@@ -1,4 +1,6 @@
-module.exports = (element, callback, options={})=>{
+import {DOUBLE_TAP_TIME} from '../globals.mjs'
+
+export default (element, callback, options={})=>{
var lastTapTime = 0,
lastTapX,
diff --git a/src/client/events/drag.js b/src/client/events/drag.js
deleted file mode 100644
index ce403607..00000000
--- a/src/client/events/drag.js
+++ /dev/null
@@ -1,331 +0,0 @@
-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)
-
- if (event.traversingStack) {
-
- event.target = event.target.closest('.drag-event')
-
- var widget = event.target.closest('.drag-event')._drag_widget,
- local = event.traversingStack.stack[event.traversingStack.stack.length - 1]
-
- if (widget.getProp) event.traversingStack.firstType = widget.getProp('type')
-
- if (local.mode === TRAVERSING_SAMEWIDGET && local.type && local.type !== event.traversingStack.firstType) {
- event.traversing = false
- } else {
- event.traversing = true
- }
-
- }
-
- targets[event.pointerId] = event.target
- 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')
-
- var local = null
- if (target && event.traversingStack) {
- for (var i = event.traversingStack.stack.length - 1; i > -1; i--) {
- if (event.traversingStack.stack[i].container.contains(target)) {
- local = event.traversingStack.stack[i]
- break
- }
- }
- if (!local) {
- target = null
- } else if (local.mode === TRAVERSING_SAMEWIDGET && local.type) {
- var widget = target.closest('.drag-event')._drag_widget
- if (widget.getProp && local.type !== widget.getProp('type')) target = null
- }
- }
-
-
-
-
- if (target && event.isTouch) {
- resetEventOffset(event, target)
- }
-
- if (previousTarget !== target) {
- triggerWidgetEvent(previousTarget, 'dragend', event)
- }
-
-
- if (target && event.traversing) {
- 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.pointerType === 'touch') return
- // event.pointerId = 'mouse'
- event.multitouch = multitouch
- pointerDownHandler(event)
-}
-
-function mouseMoveCapture(event) {
- if (event.pointerType === 'touch') return
- // event.pointerId = 'mouse'
- event.inertia = event.ctrlKey ? 10 : 1
- pointerMoveFilter(event)
-}
-
-function mouseUpCapture(event){
- if (event.pointerType === 'touch') 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.traversingStack) {
- touchEvent.traversingStack = event.traversingStack
- }
-
- 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('pointermove', mouseMoveCapture, true)
- if (!iOS) document.addEventListener('pointerup', mouseUpCapture, true)
- document.addEventListener('touchmove', touchMoveCapture, true)
- DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
-
-})
-
-module.exports = {
-
- setup: function(options) {
-
- if (
- this._customBindings['drag'] !== 0 ||
- this._customBindings['draginit'] !== 0 ||
- this._customBindings['dragend'] !== 0 ||
- !options || options.ignoreCustomBindings
- ) {
- 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('pointerdown', mouseMultiWrapper)
- } else {
- element.addEventListener('touchstart', touchDownCapture, false)
- if (!iOS) element.addEventListener('pointerdown', mouseDownCapture)
- }
-
- },
-
- teardown: function(options) {
-
- if (
- this._customBindings['drag'] !== 0 ||
- this._customBindings['draginit'] !== 0 ||
- this._customBindings['dragend'] !== 0 ||
- !options || options.ignoreCustomBindings
- ) {
- 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('pointerdown', mouseMultiWrapper)
- } else {
- element.removeEventListener('touchstart', touchDownCapture, false)
- if (!iOS) element.removeEventListener('pointerdown', mouseDownCapture)
- }
-
- },
-
- enableTraversingGestures: function(element, options={}) {
-
- if (element._traversing) return
-
- var traversing = options.type ? TRAVERSING_SAMEWIDGET : true,
- traversingType = options.type === 'auto' ? '' : options.type
-
- element._traversing = traversing
-
- function makeEventTraversing(event) {
- if (event.ctrlKey) return
- if (!event.traversingStack) event.traversingStack = {firstType: '', stack: []}
- event.traversingStack.stack.push({
- container: element,
- mode: traversing,
- type: traversingType
- })
-
- }
-
- if (!iOS) element.addEventListener('pointerdown', makeEventTraversing, true)
- element.addEventListener('touchstart', makeEventTraversing, true)
-
- element.addEventListener('disableTraversingGestures', (e)=>{
- e.stopPropagation()
- if (!iOS) element.removeEventListener('pointerdown', makeEventTraversing, true)
- element.removeEventListener('touchstart', makeEventTraversing, true)
-
- })
-
- },
-
- disableTraversingGestures: function(element) {
-
- if (!element._traversing) return
-
- delete element._traversing
-
- DOM.dispatchEvent(element, 'disableTraversingGestures')
-
- }
-
-}
diff --git a/src/client/events/drag.mjs b/src/client/events/drag.mjs
new file mode 100644
index 00000000..66799589
--- /dev/null
+++ b/src/client/events/drag.mjs
@@ -0,0 +1,426 @@
+import {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} from './utils.mjs'
+import iOS from '../ui/ios.mjs'
+import {DOM} from '../globals.mjs'
+
+var targets = {},
+ previousPointers = {}
+
+function pointerDownHandler(event) {
+
+ if (event.capturedByEditor || event.touchPunch) return event
+
+ if (!event.target._drag_multitouch) {
+ for (var i in targets) {
+ if (targets[i] == event.target) return event
+ }
+ }
+
+ event = normalizeDragEvent(event)
+ event.stopPropagation = true
+
+ var target = closestDragContainer(event.target)
+
+ if (!target) return event
+
+ if (event.traversingStack) {
+
+ var widget = target._drag_widget,
+ local = event.traversingStack.stack[event.traversingStack.stack.length - 1]
+
+ if (widget.getProp) {
+ // if first touched widget is a container, wait until another widget is touched while moving
+ event.traversingStack.firstType = widget.isContainer ? '?' : widget.getProp('type')
+ }
+
+ if (local.mode === TRAVERSING_SAMEWIDGET) {
+ if (local.type === '') {
+ local.type = event.traversingStack.firstType
+ }
+ event.traversing = local.type === event.traversingStack.firstType || event.traversingStack.firstType === '?'
+ } else {
+ event.traversing = true
+ }
+
+ }
+
+ targets[event.pointerId] = target
+ previousPointers[event.pointerId] = event
+
+
+ if (event.pointerType !== 'mouse') domObserver.activate()
+
+ triggerWidgetEvent(targets[event.pointerId], 'draginit', event)
+
+ if (event.cancelDragEvent) clearPointer(event)
+
+ return 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 = closestDragContainer(target)
+
+ var local = null,
+ containersOnly = false,
+ backupTarget = target
+
+ if (target && event.traversingStack) {
+ for (var i = event.traversingStack.stack.length - 1; i > -1; i--) {
+ if (event.traversingStack.stack[i].container.contains(target)) {
+ local = event.traversingStack.stack[i]
+ break
+ }
+ }
+ if (!local) {
+ target = null
+ } else if (local.mode === TRAVERSING_SAMEWIDGET) {
+ var widget = target._drag_widget
+ if (local.type === '?' && widget.getProp && !widget.isContainer) local.type = widget.getProp('type')
+ if (widget.getProp && local.type !== widget.getProp('type')) target = null
+ }
+ }
+
+
+
+
+ if (target && event.isTouch) {
+ resetEventOffset(event, target)
+ }
+
+ if (previousTarget !== target && !containersOnly) {
+ triggerWidgetEvent(previousTarget, 'dragend', event)
+ }
+
+
+ if (target) {
+
+ if (previousTarget === target) {
+
+ triggerWidgetEvent(target, 'drag', event)
+
+ } else {
+ triggerWidgetEvent(target, 'draginit', event)
+
+ }
+
+ } else {
+
+ // notify container of move events if no draggable widget is under the pointer
+ triggerWidgetEvent(backupTarget, 'drag', event, true)
+
+ }
+
+ targets[event.pointerId] = target
+
+
+ } else {
+ triggerWidgetEvent(targets[event.pointerId], 'drag', event)
+ }
+
+ previousPointers[event.pointerId] = event
+
+}
+
+function pointerUpHandler(event) {
+
+ event = normalizeDragEvent(event, previousPointers[event.pointerId])
+ event.stopPropagation = true
+
+ triggerWidgetEvent(targets[event.pointerId], 'dragend', event)
+
+ clearPointer(event)
+
+}
+
+function clearPointer(event) {
+
+ delete targets[event.pointerId]
+ delete previousPointers[event.pointerId]
+
+ if (domObserver.active) {
+ var t
+ for (var k in targets) {t=targets[k]}
+ if (t === undefined) domObserver.deactivate()
+ }
+
+}
+
+
+// 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 mouseDownCapture(event) {
+ if (event.pointerType === 'touch') return
+ event.stopPropagation()
+ // event.pointerId = 'mouse'
+ pointerDownHandler(event)
+}
+
+function mouseMoveCapture(event) {
+ if (event.pointerType === 'touch') return
+ // event.pointerId = 'mouse'
+ event.inertia = event.ctrlKey ? 10 : 1
+ pointerMoveFilter(event)
+}
+
+function mouseUpCapture(event){
+ if (event.pointerType === 'touch') return
+ // event.pointerId = 'mouse'
+ pointerUpFilter(event)
+}
+
+
+// Touch events wrappers
+
+// Touchend event is not emitted when target element is removed/detached
+// Watch for DOM mutations and simulate pointerUp if a registered
+// target is removed/detached
+const domObserver = new MutationObserver(function(mutations) {
+ for (var id in targets) {
+ var event = previousPointers[id],
+ target = targets[id]
+
+ if (!event || event.pointerType === 'mouse') continue
+
+ for (var mutation of mutations) {
+ for (var node of mutation.removedNodes) {
+ if (node == target || node.contains(target)){
+ pointerUpHandler(event)
+ }
+ }
+ }
+ }
+})
+domObserver.active = false
+domObserver.activate = ()=>{
+ if (!domObserver.active) {
+ domObserver.observe(DOM.get('#osc-container')[0], {subtree: true, childList: true})
+ domObserver.active = true
+ }
+}
+domObserver.deactivate = ()=>{
+ if (domObserver.active) {
+ domObserver.disconnect()
+ domObserver.active = false
+ }
+}
+
+function touchDownCapture(event) {
+
+ var preventDefault = true
+
+ event.stopPropagation()
+
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+
+ if (event.traversingStack) {
+ touchEvent.traversingStack = event.traversingStack
+ }
+
+ touchEvent.pointerId = touchEvent.identifier
+
+ touchEvent = pointerDownHandler(touchEvent)
+
+ // allow scroll if drag is cancelled or widget is a container
+ if (touchEvent.cancelDragEvent || touchEvent.allowScroll) preventDefault = false
+ }
+ if (preventDefault) event.preventDefault()
+}
+
+function touchMoveCapture(event) {
+ for (var i in event.changedTouches) {
+ if (isNaN(i) || !event.changedTouches[i]) continue
+ var touchEvent = event.changedTouches[i]
+ touchEvent.fingers = 0
+ for (var j in event.touches) {
+ if (event.touches[j].target && event.touches[j].target.isSameNode(touchEvent.target)) {
+ touchEvent.fingers += 1
+ }
+ }
+
+ 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)
+ }
+}
+
+
+
+function ancestorDragContainers(target) {
+ var containers = [],
+ container = target
+ while (container !== null) {
+ if (container._drag_widget) {
+ containers.splice(0, 0, container._drag_widget)
+ if (container._drag_widget.root) break
+ }
+ container = container.parentNode
+ }
+ return containers
+}
+
+function closestDragContainer(target) {
+ var container = target
+ while (container !== null) {
+ if (container._drag_widget) {
+ return container
+ } else {
+ container = container.parentNode
+ }
+ }
+ return null
+}
+
+// Callback trigger
+
+function triggerWidgetEvent(target, name, event, containersOnly) {
+
+ // trigger drag events from parent to child
+ var widgets = ancestorDragContainers(target),
+ widget
+
+ for (widget of widgets) {
+ if (containersOnly && !widget.isContainer) continue
+ widget.trigger(name, event)
+ if (event.preventDefault) break
+ }
+
+ // if child is a container, let it scroll
+ if (widget && widget.scroll) event.allowScroll = true
+}
+
+// init
+if (!iOS) {
+ document.addEventListener('pointermove', mouseMoveCapture, true)
+ if ('onwebkitmouseforcechanged' in document) document.addEventListener('webkitmouseforcechanged', mouseMoveCapture, true)
+}
+if (!iOS) document.addEventListener('pointerup', mouseUpCapture, true)
+
+document.addEventListener('touchmove', touchMoveCapture, true)
+
+if ('ontouchforcechange' in document) document.addEventListener('touchforcechange', touchMoveCapture, true)
+
+DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
+
+if (!iOS) document.addEventListener('pointerdown', mouseDownCapture)
+
+export function setup(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options || options.ignoreCustomBindings
+ ) {
+ return
+ }
+
+ var {element, multitouch} = options
+
+ element.addEventListener('touchstart', touchDownCapture, false)
+ element._drag_widget = this
+ element._drag_multitouch = multitouch
+
+}
+
+export function teardown(options) {
+
+ if (
+ this._customBindings['drag'] !== 0 ||
+ this._customBindings['draginit'] !== 0 ||
+ this._customBindings['dragend'] !== 0 ||
+ !options || options.ignoreCustomBindings
+ ) {
+ return
+ }
+
+ var {element} = options
+
+ element.style.touchAction = ''
+ element.removeEventListener('touchstart', touchDownCapture, false)
+ delete element._drag_widget
+ delete element._drag_multitouch
+
+}
+
+export function enableTraversingGestures(element, options={}) {
+
+ if (element._traversing) return
+
+ var traversing = options.type ? TRAVERSING_SAMEWIDGET : true,
+ traversingType = options.type === 'smart' || options.type === 'auto' ? '' : options.type
+
+ element._traversing = traversing
+
+ function makeEventTraversing(event) {
+ if (event.ctrlKey) return
+ if (!event.traversingStack) event.traversingStack = {firstType: '', stack: []}
+ event.traversingStack.stack.push({
+ container: element.parentNode,
+ mode: traversing,
+ type: traversingType
+ })
+
+ }
+
+ if (!iOS) element.addEventListener('pointerdown', makeEventTraversing, true)
+ element.addEventListener('touchstart', makeEventTraversing, true)
+
+ element.addEventListener('disableTraversingGestures', (e)=>{
+ e.stopPropagation()
+ if (!iOS) element.removeEventListener('pointerdown', makeEventTraversing, true)
+ element.removeEventListener('touchstart', makeEventTraversing, true)
+
+ })
+
+}
+
+export function disableTraversingGestures(element) {
+
+ if (!element._traversing) return
+
+ delete element._traversing
+
+ DOM.dispatchEvent(element, 'disableTraversingGestures')
+
+}
diff --git a/src/client/events/event-emitter.js b/src/client/events/event-emitter.mjs
similarity index 82%
rename from src/client/events/event-emitter.js
rename to src/client/events/event-emitter.mjs
index 1cdffd61..8e0f020d 100644
--- a/src/client/events/event-emitter.js
+++ b/src/client/events/event-emitter.mjs
@@ -1,13 +1,25 @@
-var customEvents = {}
-setTimeout(()=>{
- customEvents['draginit'] = customEvents['drag'] = customEvents['dragend'] = require('./drag')
- customEvents['resize'] = require('./resize')
-})
+import domEvent from './dom-event.mjs'
+import * as drag from './drag.mjs'
+import * as resize from './resize.mjs'
+
+var customEvents = {
+ 'draginit': drag,
+ 'drag': drag,
+ 'dragend': drag,
+ 'resize': resize,
+ 'wheel': domEvent('wheel'),
+ 'scroll': domEvent('scroll', {capture: true}),
+ 'click': domEvent('click'),
+ 'fast-click': domEvent('fast-click'),
+ 'focus': domEvent('focus', {capture: true}),
+ 'blur': domEvent('blur', {capture: true}),
+ 'change': domEvent('change')
+}
// micro optimisation from eventemitter3
var has = Object.prototype.hasOwnProperty
-module.exports = class EventEmitter {
+export default class EventEmitter {
constructor() {
@@ -31,6 +43,8 @@ module.exports = class EventEmitter {
}
// Event bubbling
+ // DOM events won't bubble
+ // Virtual events will unless data.stopPropagation is set
if (!data || !data.stopPropagation) {
if (this.parent) this.parent.trigger(evt, data)
}
diff --git a/src/client/events/resize.js b/src/client/events/resize.js
deleted file mode 100644
index f7cf8f9a..00000000
--- a/src/client/events/resize.js
+++ /dev/null
@@ -1,64 +0,0 @@
-var elements = []
-
-function checkResizes(context, force){
- // Iterate over all elements to which the 'resize' event is bound.
- var resizedElems = [],
- cachedStyles = []
- for (let i = elements.length - 1; i >= 0; i--) {
- var elem = elements[i]
-
- if (!context.contains(elem)) continue
-
- var style = window.getComputedStyle(elem),
- width = parseInt(style['width']) - parseInt(style['padding-left']) - parseInt(style['padding-right']),
- height = parseInt(style['height']) - parseInt(style['padding-top']) - parseInt(style['padding-bottom'])
-
- if (!width || !height) continue
-
- // If element size has changed since the last time, update the element
- // data store and trigger the 'resize' event.
- if (force || width != elem.resizedataw || height != elem.resizedatah) {
- elem.resizedataw = width
- elem.resizedatah = height
- resizedElems.push(elem)
- cachedStyles.push(style)
- }
- }
- for (let i = resizedElems.length - 1; i >= 0; i--) {
- resizedElems[i]._resize_widget.trigger('resize', {
- width: resizedElems[i].resizedataw,
- height: resizedElems[i].resizedatah,
- style:cachedStyles[i],
- stopPropagation: true
- })
- }
-
-}
-
-window.addEventListener('resize', ()=>{checkResizes(document)})
-
-module.exports = {
-
- setup: function(options) {
-
- if (!options) return
- if (elements.indexOf(options.element) == -1) {
- elements.push(options.element)
- options.element._resize_widget = this
- }
-
- },
- teardown: function(options) {
-
- if (!options) return
-
- if (elements.indexOf(options.element) != -1) {
- elements.splice(elements.indexOf(options.element), 1)
- delete options.element._resize_widget
- }
-
- },
-
- check: checkResizes
-
-}
diff --git a/src/client/events/resize.mjs b/src/client/events/resize.mjs
new file mode 100644
index 00000000..fab074f9
--- /dev/null
+++ b/src/client/events/resize.mjs
@@ -0,0 +1,63 @@
+import fastdom from 'fastdom'
+
+var elements = []
+
+export function check(context, force){
+ fastdom.measure(()=>{
+ // Iterate over all elements to which the 'resize' event is bound.
+ let 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', ()=>{check(document)})
+
+export function setup(options) {
+
+ if (!options) return
+ if (elements.indexOf(options.element) == -1) {
+ elements.push(options.element)
+ options.element._resize_widget = this
+ }
+
+}
+
+export function teardown(options) {
+
+ if (!options) return
+
+ if (elements.indexOf(options.element) != -1) {
+ elements.splice(elements.indexOf(options.element), 1)
+ delete options.element._resize_widget
+ }
+
+}
diff --git a/src/client/events/transform-coords.js b/src/client/events/transform-coords.mjs
similarity index 92%
rename from src/client/events/transform-coords.js
rename to src/client/events/transform-coords.mjs
index 4e3b5c96..7978dc3f 100644
--- a/src/client/events/transform-coords.js
+++ b/src/client/events/transform-coords.mjs
@@ -4,9 +4,12 @@
Disabled for now
+
*/
+
+/* global WebKitCSSMatrix */
var I = new WebKitCSSMatrix()
function Point(x, y, z) {
@@ -45,7 +48,7 @@ function getTransformationMatrix(w) {
}
-module.exports = function cssTransformCoords(node, x, y) {
+export default function cssTransformCoords(node, x, y) {
return new Point(x, y, 0).transformBy(getTransformationMatrix(node).inverse())
diff --git a/src/client/events/utils.js b/src/client/events/utils.js
deleted file mode 100644
index d6a3d944..00000000
--- a/src/client/events/utils.js
+++ /dev/null
@@ -1,106 +0,0 @@
-const Touch = window.Touch || class Touch {}
-// const cssTransformCoords = require('./transform-coords')
-
-
-module.exports = {
-
- fix: function(e) {
-
- return {
-
- target: e.target,
- firstTarget: null,
- 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,
- traversingStack: e.traversingStack,
- multitouch: e.multitouch,
- isTouch: e instanceof Touch
- }
- },
-
- normalizeDragEvent: function(event, previousEvent) {
-
- event = module.exports.fix(event)
-
- event.firstTarget = previousEvent ? previousEvent.firstTarget : event.target
-
- 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
- if (previousEvent.traversingStack) event.traversingStack = previousEvent.traversingStack
-
- if (previousEvent.multitouch) {
- event.multitouch = previousEvent.multitouch
- event.inertia = 1
- }
-
- }
-
-
- // if (!event.traversing) {
- // // css transfom fix (doesn't work well with traversing gestures)
- // var transformedCoords = cssTransformCoords(event.firstTarget, event.movementX, event.movementY)
- // event.movementX = transformedCoords.x
- // event.movementY = transformedCoords.y
- // }
-
- return event
-
- },
-
- resetEventOffset: function(event, target) {
-
- var off = DOM.offset(target)
-
- event.offsetX = event.pageX - off.left
- event.offsetY = event.pageY - off.top
-
- // if (!event.traversing) {
- // // css transfom fix (doesn't work well with traversing gestures)
- // var transformedCoords = cssTransformCoords(event.firstTarget, event.offsetX, event.offsetY)
- // event.offsetX = transformedCoords.x
- // event.offsetY = transformedCoords.y
- // }
-
- },
-
- TRAVERSING_SAMEWIDGET: 1
-
-}
diff --git a/src/client/events/utils.mjs b/src/client/events/utils.mjs
new file mode 100644
index 00000000..850191a7
--- /dev/null
+++ b/src/client/events/utils.mjs
@@ -0,0 +1,123 @@
+import {DOM} from '../globals.mjs'
+
+var zoom
+setTimeout(async()=>{
+ // use setTimeout to fix init order in safari...
+ zoom = (await import('../ui/zoom.mjs')).default
+})
+
+// impot cssTransformCoords from './transform-coords.mjs'
+
+const Touch = window.Touch || class Touch {}
+
+
+export function fix(e) {
+
+ var localZoom = zoom.editor && zoom.editor.enabled ? zoom.localZoom : 1
+
+ return {
+
+ target: e.target === document ? null : e.target, // firefox passes document when outside the page
+ firstTarget: null,
+ offsetX: e.offsetX,
+ offsetY: e.offsetY,
+ pageX: e.pageX,
+ pageY: e.pageY,
+ clientX: e.clientX,
+ clientY: e.clientY,
+ movementX: e.movementX === undefined ? undefined : e.movementX / localZoom,
+ movementY: e.movementY === undefined ? undefined : e.movementY / localZoom,
+ pointerId: e.pointerId,
+ pointerType: e.pointerType,
+ button: e.button,
+ altKey: e.altKey,
+ ctrlKey: e.ctrlKey,
+ shiftKey: e.shiftKey,
+ inertia: e.multitouch ? 1 : e.inertia,
+ traversing: e.traversing,
+ traversingStack: e.traversingStack,
+ multitouch: e.multitouch,
+ isTouch: e instanceof Touch,
+ force: e.webkitForce || e.force || 0,
+ radiusX: e.radiusX,
+ radiusY: e.radiusY,
+ rotationAngle: e.rotationAngle,
+ // iOS only
+ altitudeAngle: e.altitudeAngle,
+ azimuthAngle: e.azimuthAngle,
+ touchType: e.touchType
+ }
+
+}
+
+export function normalizeDragEvent(event, previousEvent) {
+
+ event = fix(event)
+
+ event.firstTarget = previousEvent ? previousEvent.firstTarget : event.target
+
+ if (event.movementX === undefined) {
+
+ event.movementX = previousEvent ? event.pageX - previousEvent.pageX : 0
+ event.movementY = previousEvent ? event.pageY - previousEvent.pageY : 0
+
+ }
+
+ if (event.isTouch && !previousEvent) {
+
+ resetEventOffset(event, event.target)
+
+ } else if (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
+ if (previousEvent.traversingStack) event.traversingStack = previousEvent.traversingStack
+
+ if (previousEvent.multitouch) {
+ event.multitouch = previousEvent.multitouch
+ event.inertia = 1
+ }
+
+ }
+
+
+ // if (!event.traversing) {
+ // // css transform fix (doesn't work well with traversing gestures)
+ // var transformedCoords = cssTransformCoords(event.firstTarget, event.movementX, event.movementY)
+ // event.movementX = transformedCoords.x
+ // event.movementY = transformedCoords.y
+ // }
+
+ return event
+
+}
+
+export function resetEventOffset(event, target) {
+
+ var off = DOM.offset(target)
+
+ event.offsetX = event.pageX - off.left
+ event.offsetY = event.pageY - off.top
+
+ // if (!event.traversing) {
+ // // css transform fix (doesn't work well with traversing gestures)
+ // var transformedCoords = cssTransformCoords(event.firstTarget, event.offsetX, event.offsetY)
+ // event.offsetX = transformedCoords.x
+ // event.offsetY = transformedCoords.y
+ // }
+
+}
+
+export const TRAVERSING_SAMEWIDGET = 1
diff --git a/src/client/globals.js b/src/client/globals.js
deleted file mode 100644
index e23cf22c..00000000
--- a/src/client/globals.js
+++ /dev/null
@@ -1,31 +0,0 @@
-window.IP = window.IP || ''
-window.ENV = window.ENV || {}
-location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, (s,k,v)=>{
- ENV[k]=v
-})
-
-window.LANG = ENV.lang === 'debug' ? 'debug' : (ENV.lang || navigator.language || '').substr(0, 2).toLowerCase()
-
-window.PACKAGE = require('../../package.json')
-
-window.LOADING = null
-
-window.READ_ONLY = window.READ_ONLY || false
-window.GRIDWIDTH = 10
-
-
-window.ELECTRON_NOGPU = false
-window.CANVAS_FRAMERATE = parseFloat(ENV.framerate || 60)
-window.CANVAS_SCALING = parseFloat(ENV.forceHdpi) || ( ENV.hdpi ? window.devicePixelRatio : 1 )
-window.INITIALZOOM = ENV.zoom ? parseFloat(ENV.zoom) : 1
-window.PXSCALE = INITIALZOOM
-document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
-
-window.DOUBLE_TAP_TIME = ENV.doubletap ? parseInt(ENV.doubletap) : 375
-
-
-window.JSON.parseFlex = require('json5').parse
-
-window.DOM = require('./dom')
-
-window.TITLE = PACKAGE.productName + ' v' + PACKAGE.version
diff --git a/src/client/globals.mjs b/src/client/globals.mjs
new file mode 100644
index 00000000..6dabbaf3
--- /dev/null
+++ b/src/client/globals.mjs
@@ -0,0 +1,61 @@
+import json5 from 'json5'
+import pkg from '../../package.json'
+import * as dom from './dom.mjs'
+
+export var IP = window.IP || ''
+export var ENV = window.ENV || {}
+location.search.replace(/[?&]+([^=&j]+)=([^&]*)/gi, (s,k,v)=>{
+ ENV[k]=v
+})
+for (var k in ENV) {
+ ENV[k.toLowerCase()] = ENV[k]
+}
+
+export var LANG = ENV.lang === 'debug' ? 'debug' : (ENV.lang || navigator.language || '').substr(0, 2).toLowerCase()
+
+export var PACKAGE = pkg
+
+export var LOADING = null
+
+export var READ_ONLY = window.READ_ONLY || false
+export var KIOSK = window.KIOSK || false
+export var GRIDWIDTH_CSS = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
+export function setGRIDWIDTH_CSS(x) {GRIDWIDTH_CSS = x}
+export var GRIDWIDTH = GRIDWIDTH_CSS
+export function setGRIDWIDTH(x) {GRIDWIDTH = x}
+
+
+
+
+
+
+export var ELECTRON_NOGPU = false
+export var CANVAS_FRAMERATE = parseFloat(ENV.framerate || 60)
+export var CANVAS_SCALING = parseFloat(ENV.forcehdpi) || ( ENV.hdpi ? window.devicePixelRatio : 1 )
+export var INITIALZOOM = ENV.zoom ? parseFloat(ENV.zoom) : 1
+export var PXSCALE = INITIALZOOM
+export function setPXSCALE(x) {PXSCALE = x}
+document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+
+export var DOUBLE_TAP_TIME = ENV.doubletap ? parseInt(ENV.doubletap) : 375
+
+export var CLIENT_SYNC = parseInt(ENV.clientSync) !== 0
+
+export var TOGGLE_ALT_TRAVERSING = !!ENV.altTraversing
+
+export var VIRTUAL_KEYBOARD = !!ENV.virtualKeyboard
+export function setVIRTUAL_KEYBOARD(x) {
+ VIRTUAL_KEYBOARD = x
+}
+
+export var FOCUSABLE = !ENV.noFocus
+if (!FOCUSABLE) console.debug('ELECTRON.SETFOCUSABLE(0)')
+else console.debug('ELECTRON.SETFOCUSABLE(1)')
+export function setFOCUSABLE(x) {FOCUSABLE = x}
+
+
+export var JSON5 = json5
+
+export var DOM = dom
+
+export var TITLE = ENV.title || (PACKAGE.productName + ' v' + PACKAGE.version)
diff --git a/src/client/index.js b/src/client/index.js
deleted file mode 100644
index bf932fbf..00000000
--- a/src/client/index.js
+++ /dev/null
@@ -1,39 +0,0 @@
-document.addEventListener('DOMContentLoaded', function(event) {
-
- require('./globals')
- require('./stacktrace')
-
- var locales = require('./locales'),
- html = require('nanohtml')
-
- DOM.get(document, '#osc-greeting-header')[0].appendChild(html`${PACKAGE.productName} v${PACKAGE.version}`)
-
- DOM.init()
-
- var uiLoading = require('./ui/ui-loading')
- uiLoading(locales('loading_server'))
-
- setTimeout(()=>{
-
- var ipc = require('./ipc/'),
- backup = require('./backup')
-
- ipc.init()
-
-
- require('./ui/init')
-
- document.title = TITLE
-
- ipc.send('open', {hotReload: backup.exists})
-
- window.onunload = ()=>{
- ipc.send('close')
- }
-
- backup.load()
-
-
- }, 100)
-
-})
diff --git a/src/client/index.mjs b/src/client/index.mjs
new file mode 100644
index 00000000..630e8834
--- /dev/null
+++ b/src/client/index.mjs
@@ -0,0 +1,25 @@
+import {TITLE} from './globals.mjs'
+import './stacktrace.mjs'
+import './ui/init.mjs'
+
+import locales from './locales/index.mjs'
+import uiLoading from './ui/ui-loading.mjs'
+import ipc from './ipc/index.mjs'
+import * as backup from './backup.mjs'
+
+uiLoading(locales('loading_server'))
+
+ipc.init(()=>{
+
+
+ document.title = TITLE
+
+ ipc.send('open', {hotReload: backup.exists})
+
+ window.onunload = ()=>{
+ ipc.send('close')
+ }
+
+ backup.load()
+
+})
diff --git a/src/client/ipc/callbacks.js b/src/client/ipc/callbacks.js
deleted file mode 100644
index ba881fbd..00000000
--- a/src/client/ipc/callbacks.js
+++ /dev/null
@@ -1,129 +0,0 @@
-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'),
- UiModal = require('../ui/ui-modal'),
- uiLoading = require('../ui/ui-loading'),
- notifications = require('../ui/notifications'),
- raw = require('nanohtml/raw'),
- backup = require('../backup')
-
-module.exports = {
-
- bundle: function(data) {
- for (let i in data) {
- osc.receive(data[i])
- }
- },
-
- receiveOsc: function(data){
- osc.receive(data)
- },
-
- connected:function(){
- uiLoading(false)
- },
-
- sessionOpen: function(data){
-
- session.open(data)
-
- },
-
- sessionNew: function(){
-
- session.create()
-
- },
-
- sessionSaved: function(data){
-
- editor.unsavedSession = false
-
- },
-
- stateLoad: function(data){
-
- state.load(data.state, data.send, data.path)
-
- },
-
- stateSend:function(){
- notifications.add({
- icon: 'wifi',
- message: locales('loading_newclient')
- })
-
- setTimeout(function(){
-
- osc.syncOnly = true
- state.send()
- osc.syncOnly = false
-
- },200)
-
- },
-
- editorDisable: function(data){
-
- editor.disable(data.permanent)
-
- },
-
- error: function(data){
- new UiModal({title: raw(utils.icon('exclamation-triangle') + ' ' + locales('error')), content: raw(data), closable:true})
- },
-
- reloadCss: function(){
- var queryString = '?reload=' + Date.now()
- DOM.each(document, 'link[rel="stylesheet"][hot-reload]', (el)=>{
- el.href = el.href.replace(/\?.*|$/, queryString)
- })
-
- setTimeout(()=>{
- var root = widgetManager.getWidgetById('root')[0]
- if (root) root.onPropChanged('color')
- GRIDWIDTH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
- },200)
-
-
- },
-
- reload: function(){
-
- backup.save()
- editor.unsavedSession = false
- window.location.href = window.location.href
-
- },
-
- notify: function(data) {
-
- var message = data.message || ''
-
- if (data.locale) message = locales(data.locale) + message
-
- notifications.add({
- icon: data.icon,
- class: data.class,
- message: message
- })
-
- },
-
- setTitle: function(data) {
-
- document.title = TITLE + (data ? ' (' + data + ')' : '')
-
- },
-
- serverTargets: function(data) {
-
- if (data) osc.serverTargets = data
-
- }
-
-}
diff --git a/src/client/ipc/callbacks.mjs b/src/client/ipc/callbacks.mjs
new file mode 100644
index 00000000..990a7e61
--- /dev/null
+++ b/src/client/ipc/callbacks.mjs
@@ -0,0 +1,171 @@
+import raw from 'nanohtml/raw'
+import fastdom from 'fastdom'
+import osc from '../osc.mjs'
+import session from '../managers/session/index.mjs'
+import widgetManager from '../managers/widgets.mjs'
+import state from '../managers/state.mjs'
+import editor from '../editor/index.mjs'
+import locales from '../locales/index.mjs'
+import UiModal from '../ui/ui-modal.mjs'
+import uiLoading from '../ui/ui-loading.mjs'
+import notifications from '../ui/notifications'
+import * as backup from '../backup.mjs'
+import {updateMobileThemeColor, icon} from '../ui/utils.mjs'
+import {CLIENT_SYNC, DOM, ENV, TITLE, setGRIDWIDTH_CSS} from '../globals.mjs'
+
+export default {
+
+ bundle: function(data) {
+ for (let i in data) {
+ osc.receive(data[i])
+ }
+ },
+
+ receiveOsc: function(data){
+ osc.receive(data)
+ },
+
+ connected:function(){
+ uiLoading(false)
+ },
+
+ sessionOpen: function(data){
+
+ session.open(data)
+
+ },
+
+ sessionNew: function(){
+
+ session.create()
+
+ },
+
+ sessionSaved: function(data){
+
+ editor.unsavedSession = false
+
+ },
+
+ fragmentLoad: function(data){
+
+ session.setFragment(data)
+
+ },
+
+ stateLoad: function(data){
+
+ state.load(data.state, data.send, data.path)
+
+ },
+
+ stateSend:function(){
+
+ if (!CLIENT_SYNC) return
+
+ notifications.add({
+ icon: 'wifi',
+ class: 'client-connected',
+ message: locales('loading_newclient')
+ })
+
+ setTimeout(function(){
+
+ osc.syncOnly = true
+ state.send()
+ osc.syncOnly = false
+
+ },200)
+
+ },
+
+ editorDisable: function(data){
+
+ editor.disable(data.permanent)
+
+ },
+
+ error: function(data){
+ new UiModal({title: raw(icon('exclamation-triangle') + ' ' + locales('error')), content: raw(data), closable:true})
+ },
+
+ errorLog: function(data) {
+
+ console.error(data)
+
+ },
+
+ reloadCss: function(){
+ var queryString = '?__OSC_ASSET__=1&reload=' + Date.now()
+ var sheets = DOM.get(document, 'link[rel="stylesheet"][hot-reload]')
+ var loaded = 0
+
+ for (let stylesheet of sheets) {
+ stylesheet.href = stylesheet.href.replace(/\?.*|$/, queryString)
+
+ // use image hack to catch stylesheet load event
+ let img = document.createElement('img')
+ document.body.appendChild(img)
+
+ img.onerror = img.onload = ()=>{
+ img.onerror = img.onload = null
+ document.body.removeChild(img)
+
+ if (++loaded === sheets.length) {
+ var root = widgetManager.getWidgetById('root')[0]
+ if (root) root.onPropChanged('colorWidget')
+ fastdom.measure(()=>{
+ setGRIDWIDTH_CSS(parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width')))
+ fastdom.mutate(()=>{
+ editor.toggleGrid()
+ editor.toggleGrid()
+ })
+ })
+ updateMobileThemeColor(root)
+ }
+ }
+
+ img.src = stylesheet.href
+
+
+ }
+
+ },
+
+ reload: function(){
+
+ backup.save()
+ editor.unsavedSession = false
+ window.location.href = window.location.href
+
+ },
+
+ notify: function(data) {
+
+ var message = data.message || ''
+
+ if (data.locale) message = locales(data.locale) + message
+
+ notifications.add({
+ icon: data.icon,
+ class: data.class,
+ message: message
+ })
+
+ },
+
+ setTitle: function(data) {
+
+ if (ENV.title) return
+
+ document.title = TITLE + (data ? ' (' + data + ')' : '')
+
+ },
+
+ serverTargets: function(data) {
+
+ if (data) osc.serverTargets = data
+
+ }
+
+}
diff --git a/src/client/ipc/index.js b/src/client/ipc/index.mjs
similarity index 57%
rename from src/client/ipc/index.js
rename to src/client/ipc/index.mjs
index 1bed84f9..9a3d4275 100644
--- a/src/client/ipc/index.js
+++ b/src/client/ipc/index.mjs
@@ -1,10 +1,22 @@
-var EventEmitter = require('../events/event-emitter'),
- cache = require('../managers/cache'),
- {nanoid} = require('nanoid'), uuid,
- notifications,
- locales
+import {nanoid} from 'nanoid'
+import EventEmitter from '../events/event-emitter.mjs'
+import cache from '../managers/cache.mjs'
+import {ENV} from '../globals.mjs'
-var localUuid = ENV.id || cache.get('osc.uuid', false)
+var notifications, locales, callbacks
+
+var loadDeps = (async()=>{
+ notifications = (await import('../ui/notifications.mjs')).default
+ locales = (await import('../locales/index.mjs')).default
+ callbacks = (await import('./callbacks.mjs')).default
+
+ // wait for other js chunks too since we'll connect to the server once this provise resolves
+ await import('../editor/context-menu.mjs')
+ await import('../remote-control.mjs')
+ await import('../ui/ui-keyboard.mjs')
+})()
+
+var uuid, localUuid = ENV.id || cache.get('uuid', false)
if (localUuid) {
uuid = localUuid
} else {
@@ -12,12 +24,7 @@ if (localUuid) {
cache.set('uuid', uuid, false)
}
-setTimeout(()=>{
- notifications = require('../ui/notifications')
- locales = require('../locales')
-})
-
-var reconnectTimeout = 2000,
+var reconnectTimeout = 500,
hearbeatInterval = 5000,
hearbeatTimeout = 3000,
protocol = document.location.protocol === 'https:' ? 'wss://' : 'ws://'
@@ -33,7 +40,9 @@ class Ipc extends EventEmitter {
this.queue = []
this.disconnected = false
- this.reconnect = undefined
+
+ this.reconnectTimeout = undefined
+ this.disconnectTimeout = undefined
this.hearbeat = undefined
this.hearbeatTimeout = undefined
@@ -46,32 +55,36 @@ class Ipc extends EventEmitter {
document.cookie = 'client_id=' + uuid + ';samesite=strict'
- try {
- this.open()
- } catch(e) {
- console.warn('Could not open a WebSocket connection')
- console.log(e)
- }
-
}
- init() {
+ init(callback) {
- var callbacks = require('./callbacks')
+ loadDeps.then(()=>{
- for (let i in callbacks) {
- let callback = callbacks[i]
- this.on(i, (data)=>{
- callback(data)
- })
- }
+ for (let i in callbacks) {
+ let callback = callbacks[i]
+ this.on(i, (data)=>{
+ callback(data)
+ })
+ }
+
+ try {
+ this.open()
+ } catch(e) {
+ console.warn('Could not open a WebSocket connection')
+ console.log(e)
+ }
+
+ callback()
+
+ })
}
open() {
- this.socket = new WebSocket(protocol + window.location.host + '/' + uuid)
+ this.socket = new WebSocket(protocol + window.location.host + '/' + uuid + '/' + window.AUTH)
this.socket.onclose = this.socket.onerror = ()=>{
if (!this.connected()) this.close()
@@ -89,10 +102,13 @@ class Ipc extends EventEmitter {
if (notifications && this.disconnected) notifications.add({
icon: 'wifi',
+ class: 'server-connected',
message: locales('server_connected'),
id: 'ipc_state'
})
+ this.disconnected = false
+
this.trigger('connect')
this.flush()
@@ -115,18 +131,23 @@ class Ipc extends EventEmitter {
clearInterval(this.hearbeat)
clearTimeout(this.hearbeatTimeout)
- notifications.add({
- icon: 'wifi',
- class: 'error',
- message: locales('server_disconnected'),
- id: 'ipc_state',
- duration: Infinity
- })
+ clearTimeout(this.disconnectTimeout)
+ this.disconnectTimeout = setTimeout(()=>{
+ // delay notification in case reconnection succeeds quickly
+ if (notifications && !this.connected()) notifications.add({
+ icon: 'wifi',
+ class: 'error',
+ message: locales('server_disconnected'),
+ id: 'ipc_state',
+ duration: Infinity
+ })
+ this.disconnected = true
- this.disconnected = true
+ }, reconnectTimeout * 2)
- clearTimeout(this.reconnect)
- this.reconnect = setTimeout(()=>{
+
+ clearTimeout(this.reconnectTimeout)
+ this.reconnectTimeout = setTimeout(()=>{
this.open()
}, reconnectTimeout)
@@ -182,4 +203,4 @@ class Ipc extends EventEmitter {
var ipc = new Ipc()
-module.exports = ipc
+export default ipc
diff --git a/src/client/locales/de.mjs b/src/client/locales/de.mjs
new file mode 100644
index 00000000..ecf7a2c0
--- /dev/null
+++ b/src/client/locales/de.mjs
@@ -0,0 +1,141 @@
+export default {
+
+ // console
+ console: 'Konsole',
+ console_enabled: 'Aktiv',
+ console_clear: 'Konsole leeren',
+
+
+ // editor
+ editor: 'Editor',
+ editor_enabled: 'Aktiv',
+ editor_grid: 'Raster',
+ editor_tree: 'Projektbaum',
+ editor_inspector: 'Inspektor',
+ editor_percents: 'Relative Einheiten (%)',
+
+ // editor context-menu
+ editor_show_in_tree: 'Zeige in Baum',
+ editor_show_in_session: 'Zeige in Sitzung',
+ editor_front: 'In den Vordergrund',
+ editor_closer: 'Eine Ebene nach vorne',
+ editor_back: 'In den Hintergrund',
+ editor_farther: 'Eine Ebene nach hinten',
+ editor_copy: 'Kopieren',
+ editor_cut: 'Ausschneiden',
+ editor_paste: 'Einfügen',
+ editor_pasteindent: 'ID + 1',
+ editor_clone: 'Duplizieren',
+ editor_addwidget: 'Widget hinzufügen',
+ editor_addtab: 'Tab hinzufügen',
+ editor_delete: 'Löschen',
+
+ editor_fragment: 'Fragment',
+ editor_fragment_export: 'Export',
+ editor_fragment_import: 'Import',
+
+ editor_ace_help: 'Hilfe',
+ editor_ace_help_title: 'Tastenkombinationen für den Code-Editor',
+
+ // loadings
+ loading_upload: 'Datei wird hochgeladen…',
+ loading_newclient: 'Neuer Client verbindet sich…',
+ loading_server: 'Server verbinden…',
+ loading_session: 'Sitzung laden…',
+
+ // file
+ file_open: 'Öffnen',
+ file_open_recent: 'Kürzlich geöffnet',
+ file_open_recent_wait: 'Liste noch nicht geladen, bitte schließen Sie das Menü und öffnen Sie es erneut',
+ file_save: 'Speichern',
+ file_save_as: 'Speichern unter…',
+ file_backup: 'Backup speichern',
+ file_import: 'Importieren',
+ file_export: 'Exportieren',
+
+ // keyboard
+ keyboard: 'Virtuelle Tastatur',
+ keyboard_layout: {
+ default: [
+ '{esc} ` 1 2 3 4 5 6 7 8 9 0 - = {zrck}',
+ '{tab} q w e r t z u i o p [ ] \\',
+ '{lock} a s d f g h j k l ; \' {enter}',
+ '{shift} z x c v b n m , . / {shift}',
+ '{leer}'
+ ],
+ shift: [
+ '{esc} ~ ! @ # $ % ^ & * ( ) _ + {zrck}',
+ '{tab} Q W E R T Y U I O P { } |',
+ '{lock} A S D F G H J K L : " {enter}',
+ '{shift} Z X C V B N M < > ? {shift}',
+ '{leer}'
+ ]
+ },
+ keyboard_escape: 'Esc',
+
+ // fragment mode
+ fragment_mode: 'Fragment Modus',
+ fragment_mode_warning: 'Fragment Modus aktiviert',
+ fragment_mode_explanation: 'Die Sitzung wird als Fragment gespeichert: nur das erste untergeordnete Element von root wird gespeichert.',
+
+ // fullscreen
+ fullscreen: 'Vollbild',
+ fullscreen_unnavailable: 'Vollbild nicht verfügbar',
+ fullscreen_addtohome: 'Sie müssen diese Seite zu Ihrem Startbildschirm hinzufügen, um sie im Vollbildmodus zu starten',
+
+ // inspector
+ inspector_error: 'Es ist ein Fehler aufgetreten. Öffne die Konsole, um mehr zu lesen.',
+ inspector_zoom_in: 'Vergrößern',
+ inspector_zoom_reset: 'Zoom zurücksetzen',
+ inspector_zoom_ou: 'Verkleinern',
+ inspector_reset_selection: 'Widget(s) abwählen',
+ inspector_toggle_grid: 'Raster ein-/ausblenden',
+
+ // nosleep
+ nosleep: 'Prevent sleep',
+
+ // notifications
+ notifications: 'Benachrichtigungen',
+
+ // remote save
+ remotesave_open: 'Öffnen (auf dem Server)',
+ remotesave_save: 'Speichern (auf dem Server)',
+ remotesave_overwrite: 'Diese Datei existiert bereits, möchtest du sie überschreiben?',
+ remotesave_fail: 'Die Datei konnte nicht auf dem Server gespeichert werden, verwende stattdessen "export".',
+ remotesave_success: 'Datei erfolgreich gespeichert',
+ remotesave_forbidden: 'Speichern auf dem Server nicht möglich, verwende stattdessen "exportieren".',
+
+ // server
+ server_disconnected: 'Die Verbindung zum Server ist unterbrochen worden',
+ server_connected: 'Die Verbindung zum Server wurde wiederhergestellt',
+
+ // session
+ session: 'Sitzung',
+ session_new: 'Neue Sitzung',
+ session_malformed: 'Fehlerhafte Sitzungsdatei.',
+ session_parsingerror: 'Fehler beim Parsing.',
+ session_uploaderror: 'Hochladen der Sitzungsdatei fehlgeschlagen.',
+ session_unsaved: 'Die Änderungen gehen verloren, wenn du diese Sitzung schließt, ohne zu speichern. Fortfahren?',
+ session_oldversion_title: 'Warnung',
+ session_oldversion: 'Diese Sitzung wurde mit einer älteren Version dieser Software erstellt - eine automatische Konvertierung wurde durchgeführt. Nach dem Speichern wird diese Sitzung wahrscheinlich nicht korrekt mit älteren Versionen geladen, es wird empfohlen, eine Sicherungskopie davon zu erstellen.',
+
+ // state
+ state: 'Status',
+ state_store: 'Laden',
+ state_recall: 'Abrufen',
+ state_send: 'Alle senden',
+ state_import: 'Import',
+ state_export: 'Export',
+ state_uploaderror: 'Hochladen der Statusdatei fehlgeschlagen.',
+ state_storesuccess: 'Status gespeichert',
+ state_recallsuccess: 'Status abgerufen',
+ state_sendsuccess: 'Status gesendet',
+
+ // tree
+ tree_filter: 'Filter',
+
+ // misc
+ error: 'Error'
+
+
+}
diff --git a/src/client/locales/en.js b/src/client/locales/en.mjs
similarity index 56%
rename from src/client/locales/en.js
rename to src/client/locales/en.mjs
index 9bd95e30..99b6531f 100644
--- a/src/client/locales/en.js
+++ b/src/client/locales/en.mjs
@@ -1,4 +1,4 @@
-module.exports = {
+export default {
// console
console: 'Console',
@@ -16,6 +16,7 @@ module.exports = {
// editor context-menu
editor_show_in_tree: 'Show in tree',
+ editor_show_in_session: 'Show in session',
editor_front: 'Bring to front',
editor_closer: 'Bring closer',
editor_back: 'Send to back',
@@ -29,41 +30,80 @@ module.exports = {
editor_addtab: 'Add tab',
editor_delete: 'Delete',
+ editor_fragment: 'Fragment',
+ editor_fragment_export: 'Export',
+ editor_fragment_import: 'Import',
+
+ editor_ace_help: 'Help',
+ editor_ace_help_title: 'Code editor keyboard shortcuts',
+
// loadings
- loading_upload: 'Uploading file...',
- loading_newclient: 'New client connecting...',
- loading_server: 'Connecting server...',
- loading_session: 'Loading session...',
+ loading_upload: 'Uploading file…',
+ loading_newclient: 'New client connecting…',
+ loading_server: 'Connecting server…',
+ loading_session: 'Loading session…',
// file
file_open: 'Open',
file_open_recent: 'Open recent',
file_open_recent_wait: 'List not loaded yet, please close and reopen the menu',
file_save: 'Save',
- file_save_as: 'Save as...',
+ file_save_as: 'Save as…',
+ file_backup: 'Save backup',
file_import: 'Import',
file_export: 'Export',
+ // keyboard
+ keyboard: 'Virtual keyboard',
+ keyboard_layout: {
+ default: [
+ '{esc} ` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
+ '{tab} q w e r t y u i o p [ ] \\',
+ '{lock} a s d f g h j k l ; \' {enter}',
+ '{shift} z x c v b n m , . / {shift}',
+ '{space}'
+ ],
+ shift: [
+ '{esc} ~ ! @ # $ % ^ & * ( ) _ + {bksp}',
+ '{tab} Q W E R T Y U I O P { } |',
+ '{lock} A S D F G H J K L : " {enter}',
+ '{shift} Z X C V B N M < > ? {shift}',
+ '{space}'
+ ]
+ },
+ keyboard_escape: 'Esc',
+
+ // fragment mode
+ fragment_mode: 'Fragment mode',
+ fragment_mode_warning: 'Fragment mode enabled',
+ fragment_mode_explanation: 'The session will be saved as a fragment: only the first child of root will be saved.',
+
// fullscreen
fullscreen: 'Fullscreen',
fullscreen_unnavailable: 'Fullscreen not available',
fullscreen_addtohome: 'You must add this page to your home screen to launch it in fullscreen',
// inspector
- inspector_color_confirm: 'Confirm',
- inspector_color_apply: 'Apply',
- inspector_error: 'An error just occured, open the console to read more.',
+ inspector_error: 'An error just occurred, open the console to read more.',
+ inspector_zoom_in: 'Zoom in',
+ inspector_zoom_reset: 'Reset zoom',
+ inspector_zoom_ou: 'Zoom out',
+ inspector_reset_selection: 'Unselect widget(s)',
+ inspector_toggle_grid: 'Show/hide the grid',
// nosleep
nosleep: 'Prevent sleep',
+ // notifications
+ notifications: 'Notifications',
+
// remote save
remotesave_open: 'Open (on the server)',
remotesave_save: 'Save (on the server)',
- remotesave_overwrite: 'This file already exists, do you want to overwrite it ?',
+ remotesave_overwrite: 'This file already exists, do you want to overwrite it?',
remotesave_fail: 'The file could not be saved on the server, use "export" instead',
remotesave_success: 'File saved successfully',
- remotesave_forbidden: 'You\'re note allowed to save on server, use "export instead"',
+ remotesave_forbidden: 'You\'re note allowed to save on server, use "export" instead',
// server
server_disconnected: 'The connection to the server has been interrupted',
@@ -75,9 +115,9 @@ module.exports = {
session_malformed: 'Malformed session file.',
session_parsingerror: 'Parsing error.',
session_uploaderror: 'Failed to upload session file.',
- session_unsaved: 'Your changes will be lost if you close this session without saving, continue ?',
+ session_unsaved: 'Your changes will be lost if you close this session without saving, continue?',
session_oldversion_title: 'Warning',
- session_oldversion: 'This session was created with an older version, an automatic conversion has been done.',
+ session_oldversion: 'This session was created with an older version of this software, an automatic conversion has been done. Once saved, this session will probably not load correctly with older versions, it is recommended to make a backup copy of it.',
// state
state: 'State',
@@ -91,6 +131,9 @@ module.exports = {
state_recallsuccess: 'State recalled',
state_sendsuccess: 'State sent',
+ // tree
+ tree_filter: 'Filter',
+
// misc
error: 'Error'
diff --git a/src/client/locales/fr.js b/src/client/locales/fr.mjs
similarity index 59%
rename from src/client/locales/fr.js
rename to src/client/locales/fr.mjs
index 85b98fab..05f6c9b3 100644
--- a/src/client/locales/fr.js
+++ b/src/client/locales/fr.mjs
@@ -1,4 +1,4 @@
-module.exports = {
+export default {
// console
console: 'Console',
@@ -15,6 +15,7 @@ module.exports = {
// editor context-menu
editor_show_in_tree: 'Voir dans l\'arborescence',
+ editor_show_in_session: 'Voir dans la session',
editor_front: 'Amener devant',
editor_closer: 'Amener plus près',
editor_back: 'Envoyer à l\'arrière',
@@ -28,34 +29,74 @@ module.exports = {
editor_addtab: 'Ajouter onglet',
editor_delete: 'Supprimer',
+ editor_fragment: 'Fragment',
+ editor_fragment_export: 'Exporter',
+ editor_fragment_import: 'Importer',
+
+ editor_ace_help: 'Aide',
+ editor_ace_help_title: 'Raccourcis claviers de l\'éditeur',
+
// loadings
- loading_upload: 'Téléversement...',
- loading_newclient: 'Connexion d\'un nouveau client...',
- loading_server: 'Connexion au serveur...',
- loading_session: 'Chargement de la session...',
+ loading_upload: 'Téléversement…',
+ loading_newclient: 'Connexion d\'un nouveau client…',
+ loading_server: 'Connexion au serveur…',
+ loading_session: 'Chargement de la session…',
// file
file_open: 'Ouvrir',
file_open_recent: 'Récemment ouvert(s)',
file_open_recent_wait: 'Liste non chargée, veuillez fermer puis ouvrir le menu à nouveau',
file_save: 'Enregistrer',
- file_save_as: 'Enregistrer sous...',
+ file_save_as: 'Enregistrer sous…',
+ file_backup: 'Enregistrer une sauvegarde',
file_import: 'Importer',
file_export: 'Exporter',
+ // keyboard
+ keyboard: 'Clavier virtuel',
+ keyboard_layout: {
+ default: [
+ '{esc} \u00B2 & \u00E9 \" \' ( - \u00E8 _ \u00E7 \u00E0 ) = {bksp}',
+ '{tab} a z e r t y u i o p ^ $',
+ '{lock} q s d f g h j k l m \u00F9 * {enter}',
+ '{shift} < w x c v b n , ; : ! {shift}',
+ '{space}',
+ ],
+ shift: [
+ '{esc} ` 1 2 3 4 5 6 7 8 9 0 \u00B0 + {bksp}',
+ '{tab} A Z E R T Y U I O P \u00A8 \u00A3',
+ '{lock} Q S D F G H J K L M % \u00B5 {enter}',
+ '{shift} > W X C V B N ? . / \u00A7 {shift}',
+ '{space}'
+ ]
+ },
+ keyboard_escape: 'Échap',
+
// fullscreen
fullscreen: 'Plein écran',
fs_unnavailable: 'Plein écran indisponible',
fs_addtohome: 'Vous devez ajouter cette page à votre écran d\'accueil pour pouvoir l\'ouvrir en plein écran.',
+ // fragment mode
+ fragment_mode: 'Mode fragment',
+ fragment_mode_warning: 'Mode fragment activé',
+ fragment_mode_explanation: 'La session sera enregistrée sous forme de fragment : seul le premier descendant de l\'élément root sera sauvegardé.',
+
// inspector
- inspector_color_confirm: 'Confirmer',
- inspector_color_apply: 'Appliquer',
inspector_error: 'Une erreur vient de survenir, ouvrez la console pour en savoir plus.',
+ inspector_zoom_in: 'Zoom avant',
+ inspector_zoom_reset: 'Zoom initial',
+ inspector_zoom_out: 'Zoom arrière',
+ inspector_reset_selection: 'Déséléctionner',
+ inspector_toggle_grid: 'Afficher / masquer la grille',
+
// nosleep
nosleep: 'Empêcher la veille',
+ // notifications
+ notifications: 'Notifications',
+
// remote save
remotesave_open: 'Ouvrir (sur le serveur)',
remotesave_save: 'Enregistrer (sur le serveur)',
@@ -76,7 +117,7 @@ module.exports = {
session_uploaderror: 'Échec à l\'envoi du fichier de session.',
session_unsaved: 'Vos modifications seront perdues si vous fermez la session actuelle sans sauvegarder, continuer ?',
session_oldversion_title: 'Attention',
- session_oldversion: 'Cette session a été créée avec une ancienne version, une conversion automatique a été appliquée.',
+ session_oldversion: 'Cette session a été créée avec une ancienne version de ce logiciel, une conversion automatique a été appliquée. Une fois sauvegardée, cette session risque de ne plus charger correctement avec les anciennes versions, il est recommandé d\'en faire une copie de sauvegarde.',
// state
state: 'État',
@@ -90,6 +131,9 @@ module.exports = {
state_recallsuccess: 'État de l\'interface restauré',
state_sendsuccess: 'État de de l\'interface envoyé',
+ // tree
+ tree_filter: 'Filtrer',
+
// misc
error: 'Erreur'
diff --git a/src/client/locales/index.js b/src/client/locales/index.js
deleted file mode 100644
index 5fccd784..00000000
--- a/src/client/locales/index.js
+++ /dev/null
@@ -1,9 +0,0 @@
-var locales = {
- debug: {/* empty */},
- en: require('./en'),
- fr: require('./fr')
-}
-
-var lang = locales[LANG] ? LANG : 'en'
-
-module.exports = key=>locales[lang][key] || `!${key}!`
diff --git a/src/client/locales/index.mjs b/src/client/locales/index.mjs
new file mode 100644
index 00000000..3f8920f7
--- /dev/null
+++ b/src/client/locales/index.mjs
@@ -0,0 +1,17 @@
+import en from './en.mjs'
+import fr from './fr.mjs'
+import de from './de.mjs'
+import pl from './pl.mjs'
+import {LANG} from '../globals.mjs'
+
+var locales = {
+ en, fr, de, pl,
+ debug: {
+ /* empty */
+ keyboard_layout: en.keyboard_layout
+ }
+}
+
+var lang = locales[LANG] ? LANG : 'en'
+
+export default key=>locales[lang][key] || `!${key}!`
diff --git a/src/client/locales/pl.mjs b/src/client/locales/pl.mjs
new file mode 100644
index 00000000..059f7cc7
--- /dev/null
+++ b/src/client/locales/pl.mjs
@@ -0,0 +1,141 @@
+export default {
+
+ // console
+ console: 'Terminal',
+ console_enabled: 'Włączony',
+ console_clear: 'Wyczyść terminal',
+
+
+ // editor
+ editor: 'Edytor',
+ editor_enabled: 'Włączony',
+ editor_grid: 'Siatka',
+ editor_tree: 'Drzewo projekty',
+ editor_inspector: 'Inspektor',
+ editor_percents: 'Jednostki względne (%)',
+
+ // editor context-menu
+ editor_show_in_tree: 'Pokaż w drzewie',
+ editor_show_in_session: 'Pokaż w sesji',
+ editor_front: 'Przenieś na pierwszy plan',
+ editor_closer: 'Przenieś wyżej',
+ editor_back: 'Przenieś na ostatni plan',
+ editor_farther: 'Przenieś niżej',
+ editor_copy: 'Kopiuj',
+ editor_cut: 'Wytnij',
+ editor_paste: 'Wklej',
+ editor_pasteindent: 'Wklej i zwiększ ID o 1',
+ editor_clone: 'Sklonuj',
+ editor_addwidget: 'Dodaj widget',
+ editor_addtab: 'Dodaj kartę',
+ editor_delete: 'Usuń',
+
+ editor_fragment: 'Fragment',
+ editor_fragment_export: 'Eksportuj',
+ editor_fragment_import: 'Importuj',
+
+ editor_ace_help: 'Pomoc',
+ editor_ace_help_title: 'Skróty klawiszowe edytora kodu',
+
+ // loadings
+ loading_upload: 'Wysyłanie pliku…',
+ loading_newclient: 'Nowy klient podłączony…',
+ loading_server: 'Podłączanie do serwera…',
+ loading_session: 'Wczytywanie sesji…',
+
+ // file
+ file_open: 'Otwórz',
+ file_open_recent: 'Ostatnio otwierane',
+ file_open_recent_wait: 'Lista nie jest jeszcze załadowana, zamknij i otwórz ponownie to menu',
+ file_save: 'Zapisz',
+ file_save_as: 'Zapisz jako…',
+ file_backup: 'Zapisz kopię zapasową',
+ file_import: 'Importuj',
+ file_export: 'Eksportuj',
+
+ // keyboard
+ keyboard: 'Klawiatura wirtualna',
+ keyboard_layout: {
+ default: [
+ '{esc} ` 1 2 3 4 5 6 7 8 9 0 - = {bksp}',
+ '{tab} q w e r t y u i o p [ ] \\',
+ '{lock} a s d f g h j k l ; \' {enter}',
+ '{shift} z x c v b n m , . / {shift}',
+ '{space}'
+ ],
+ shift: [
+ '{esc} ~ ! @ # $ % ^ & * ( ) _ + {bksp}',
+ '{tab} Q W E R T Y U I O P { } |',
+ '{lock} A S D F G H J K L : " {enter}',
+ '{shift} Z X C V B N M < > ? {shift}',
+ '{space}'
+ ]
+ },
+ keyboard_escape: 'Esc',
+
+ // fragment mode
+ fragment_mode: 'Tryb fragmentów',
+ fragment_mode_warning: 'Tryb fragmentów włączony',
+ fragment_mode_explanation: 'Ta sesja zostanie zapisana jako fragment: tylko pierwsze dziecko roota zostanie zapisane.',
+
+ // fullscreen
+ fullscreen: 'Tryb pełnoekranowy',
+ fullscreen_unnavailable: 'Tryb pełnoekranowy niedostęĻny',
+ fullscreen_addtohome: 'Musisz dodać tę stronę do Twojego ekranu domowego by otworzyć ja w trybie pełnoekranowym',
+
+ // inspector
+ inspector_error: 'Wystąpił błąd, otwórz terminal by dowiedzieć się więcej.',
+ inspector_zoom_in: 'Przybliż',
+ inspector_zoom_reset: 'Domyślny stopień przybliżenia',
+ inspector_zoom_ou: 'Oddal',
+ inspector_reset_selection: 'Odznacz widget(y)',
+ inspector_toggle_grid: 'Pokaż/ukryj siatkę',
+
+ // nosleep
+ nosleep: 'Nie pozwalaj na uśpienie ekranu',
+
+ // notifications
+ notifications: 'Powiadomienia',
+
+ // remote save
+ remotesave_open: 'Otwórz (na serwerze)',
+ remotesave_save: 'Sapisz (na serwerze)',
+ remotesave_overwrite: 'Ten plik już istnieje, czy chcesz go nadpisać?',
+ remotesave_fail: 'Ten plik nie mógł zostać zapisany na serwerze, użyj eksportu',
+ remotesave_success: 'Plik zapisany pomyślnie',
+ remotesave_forbidden: 'Nie masz uprawnień do zapisania pliku na serwerze, użyj eksportu',
+
+ // server
+ server_disconnected: 'Połączenie z serwerem zostało przerwane',
+ server_connected: 'Połączenie z serwerem zostało nawiązane',
+
+ // session
+ session: 'Sesja',
+ session_new: 'Nowa sesja',
+ session_malformed: 'Niewłaściwy plik sesji.',
+ session_parsingerror: 'Błąd parsowania pliku sesji.',
+ session_uploaderror: 'Nie udało się przesłać pliku sesji.',
+ session_unsaved: 'Jeśli zamkniesz tę sesję bez uprzedniego zapisu, wprowadzone zmiany zostaną utracone. Czy chcesz kontynuować?',
+ session_oldversion_title: 'Ostrzeżenie',
+ session_oldversion: 'Ta sesja została stworzona przy użyciu starszej wersji tego oprogramowania - dokonano automatycznej konwersji. Po zapisaniu, sesja ta prawdopodobnie nie będzie ładować się poprawnie ze starszymi wersjami, zaleca się wykonanie kopii bezpieczeństwa.',
+
+ // state
+ state: 'Stan',
+ state_store: 'Zachowaj',
+ state_recall: 'Przywołaj',
+ state_send: 'Wyślij wszystkie',
+ state_import: 'Importuj',
+ state_export: 'Eksportuj',
+ state_uploaderror: 'Nie udało się przesłać pliku stanu.',
+ state_storesuccess: 'Zapisano stan',
+ state_recallsuccess: 'Przywołano stan',
+ state_sendsuccess: 'Wysłano stan',
+
+ // tree
+ tree_filter: 'Filtruj',
+
+ // misc
+ error: 'Błąd'
+
+
+}
diff --git a/src/client/managers/cache.js b/src/client/managers/cache.mjs
similarity index 51%
rename from src/client/managers/cache.js
rename to src/client/managers/cache.mjs
index 854f3e17..1d1cee77 100644
--- a/src/client/managers/cache.js
+++ b/src/client/managers/cache.mjs
@@ -4,17 +4,33 @@ class Cache {
set(key, value, persistent = true) {
- var storage = persistent ? localStorage : sessionStorage
+ try {
+
+ var storage = persistent ? localStorage : sessionStorage
+
+ storage.setItem(keyPrefix + key, JSON.stringify(value))
+
+ } catch(e){
+ console.error(`Could not write to ${persistent ? 'localStorage' : 'sessionStorage'}: ${e}`)
+ console.debug(e)
+ }
- storage.setItem(keyPrefix + key, JSON.stringify(value))
}
get(key, persistent = true) {
- var storage = persistent ? localStorage : sessionStorage
+ try {
- return JSON.parse(storage.getItem(keyPrefix + key))
+ var storage = persistent ? localStorage : sessionStorage
+
+ return JSON.parse(storage.getItem(keyPrefix + key))
+
+ } catch(e){
+ console.error(`Could not read from ${persistent ? 'localStorage' : 'sessionStorage'}: ${e}`)
+ console.debug(e)
+ return null
+ }
}
@@ -52,4 +68,4 @@ class Cache {
}
-module.exports = new Cache()
+export default new Cache()
diff --git a/src/client/managers/session/index.js b/src/client/managers/session/index.mjs
similarity index 54%
rename from src/client/managers/session/index.js
rename to src/client/managers/session/index.mjs
index b11af14f..80fc4d16 100644
--- a/src/client/managers/session/index.js
+++ b/src/client/managers/session/index.mjs
@@ -1,22 +1,28 @@
-var ipc = require('../../ipc/'),
- parser = require('../../parser'),
- editor = require('../../editor/'),
- uiFilebrowser = require('../../ui/ui-filebrowser'),
- uiFileupload = require('../../ui/ui-fileupload'),
- UiModal = require('../../ui/ui-modal'),
- uiLoading = require('../../ui/ui-loading'),
- uiConsole = require('../../ui/ui-console'),
- {saveAs} = require('file-saver'),
- widgetManager = require('../widgets'),
- locales = require('../../locales'),
- Session = require('./session')
+import {saveAs} from 'file-saver'
+import ipc from '../../ipc/index.mjs'
+import parser from '../../parser.mjs'
+import editor from '../../editor/index.mjs'
+import uiFilebrowser from '../../ui/ui-filebrowser.mjs'
+import uiFileupload from '../../ui/ui-fileupload.mjs'
+import UiModal from '../../ui/ui-modal.mjs'
+import uiLoading from '../../ui/ui-loading.mjs'
+import uiConsole from '../../ui/ui-console'
+import widgetManager from '../widgets.mjs'
+import locales from '../../locales/index.mjs'
+import Session from './session.mjs'
+import EventEmitter from '../../events/event-emitter.mjs'
+import {deepEqual} from '../../utils.mjs'
+import {DOM, READ_ONLY, PACKAGE, CLIENT_SYNC} from '../../globals.mjs'
-
-var SessionManager = class SessionManager {
+var SessionManager = class SessionManager extends EventEmitter {
constructor() {
+ super()
+
this.session = null
+ this.saveMode = 'session'
+ this.fragments = {}
this.lock = false
this.lastDir = null
this.setSessionPath('')
@@ -41,7 +47,7 @@ var SessionManager = class SessionManager {
try {
uiConsole.clear()
- this.session = new Session(session)
+ this.session = new Session(session, 'session')
container.innerHTML = ''
parser.reset()
parser.parse({
@@ -50,7 +56,9 @@ var SessionManager = class SessionManager {
parent: widgetManager
})
editor.clearHistory()
+ editor.widgetTree.filter.value = ''
DOM.get(document, '#osc-greeting-header')[0].classList.add('hidden')
+ this.setSaveMode(this.session.isFragment ? 'fragment' : 'session')
} catch (err) {
uiLoading(false)
@@ -62,7 +70,7 @@ var SessionManager = class SessionManager {
for (var h in widgetManager.widgets) {
if (widgetManager.widgets[h].value !== undefined) {
- widgetManager.trigger('change', {
+ widgetManager.trigger('value-changed', {
widget: widgetManager.widgets[h],
id: widgetManager.widgets[h].getProp('id'),
linkId: widgetManager.widgets[h].getProp('linkId'),
@@ -71,7 +79,10 @@ var SessionManager = class SessionManager {
}
}
- if (editor.enabled) editor.disable()
+ if (editor.enabled) {
+ editor.disable()
+ editor.enable()
+ }
DOM.dispatchEvent(window, 'resize')
@@ -87,19 +98,47 @@ var SessionManager = class SessionManager {
}
- save(path) {
+ save(path, backup=false) {
if (!this.session || READ_ONLY) return
if (path) this.setSessionPath(path)
+ if (editor.inspector.focusedInput) {
+ editor.inspector.onChange()
+ }
+
if (!this.sessionPath) return this.saveAs()
- ipc.send('sessionSave', {
- session: this.session.toJSON(),
- path: this.sessionPath
- })
+ if (this.saveMode === 'session') {
+ ipc.send('sessionSave', {
+ session: this.session.toJSON(),
+ path: this.sessionPath,
+ backup: backup
+ })
+
+ } else {
+
+ var data = this.session.data.content.widgets.length ?
+ this.session.data.content.widgets[0] :
+ this.session.data.content.tabs[0]
+
+ ipc.send('sessionSave', {
+ session: new Session({
+ content: data,
+ version: PACKAGE.version
+ }, 'fragment'),
+ path: this.sessionPath,
+ backup: backup
+ })
+
+ }
+
+ }
+
+ saveBackup() {
+ this.save('', true)
}
saveAs() {
@@ -126,9 +165,9 @@ var SessionManager = class SessionManager {
open(data) {
- this.load(data.session, ()=>{
+ this.load(data.fileContent, ()=>{
this.setSessionPath(data.path)
- ipc.send('sessionOpened', {path: data.path})
+ ipc.send('sessionOpened', {path: data.path, sync: CLIENT_SYNC})
})
}
@@ -190,8 +229,70 @@ var SessionManager = class SessionManager {
}
+ setFragment(data) {
+
+ var {path, fileContent, raw, notFound} = data,
+ update = false
+
+ if (notFound) {
+ this.trigger('fragment-not-found', {path: path})
+ return
+ }
+
+ if (raw) {
+ if (this.fragments[path] !== fileContent) {
+ this.fragments[path] = fileContent
+ update = true
+ }
+ } else {
+ var fragment = new Session(fileContent, 'fragment')
+ if (!deepEqual(this.fragments[path], fragment)) {
+ this.fragments[path] = fragment
+ update = true
+ }
+ }
+
+ if (update) this.trigger('fragment-updated', {path: path})
+
+
+ }
+
+ getFragment(path, data) {
+
+ return this.fragments[path]
+
+ }
+
+ saveFragment(data) {
+
+ uiFilebrowser({extension: 'json', save:true, directory: this.lastDir}, (path)=>{
+ this.lastDir = path[0]
+ ipc.send('sessionSave', {
+ session: new Session({
+ content: data,
+ version: PACKAGE.version
+ }, 'fragment'),
+ path: path
+ })
+ })
+
+ }
+
+ loadFragment(path, raw=false) {
+
+ ipc.send('fragmentLoad', {path, raw})
+
+ }
+
+ setSaveMode(mode) {
+
+ this.saveMode = mode
+ document.body.classList.toggle('fragment-mode', mode === 'fragment')
+
+ }
+
}
var sessionManager = new SessionManager()
-module.exports = sessionManager
+export default sessionManager
diff --git a/src/client/managers/session/session.js b/src/client/managers/session/session.mjs
similarity index 66%
rename from src/client/managers/session/session.js
rename to src/client/managers/session/session.mjs
index 614ae3e2..0a8eff48 100644
--- a/src/client/managers/session/session.js
+++ b/src/client/managers/session/session.mjs
@@ -1,15 +1,16 @@
-var semver = require('semver'),
- UiModal = require('../../ui/ui-modal'),
- locales = require('../../locales')
+import semver from 'semver'
+import UiModal from '../../ui/ui-modal.mjs'
+import locales from '../../locales/index.mjs'
+import {PACKAGE} from '../../globals.mjs'
-module.exports = class Session {
+class Session {
- constructor(data) {
+ constructor(data, type) {
if (data === null) {
data = {
- session: {type: 'root'}
+ content: {type: 'root'}
}
@@ -23,9 +24,9 @@ module.exports = class Session {
if (semver.lte(version, converter.version)) {
if (converter.global) data = converter.global(data)
- if (converter.widget) this.applyConvert(data.session, converter.widget)
+ if (converter.widget) this.applyConvert(data.session || data.content, converter.widget)
- if (converter.warning) warning = true
+ if (converter.warning && type !== 'fragment') warning = true
}
@@ -36,13 +37,35 @@ module.exports = class Session {
new UiModal({title: locales('session_oldversion_title'), content: locales('session_oldversion'), icon: 'exclamation-triangle', closable:true})
-
}
}
+
+
+ if (type === 'session' && data.type === 'fragment') {
+ // opening fragment as a session
+ if (data.content.type === 'tab') {
+ data.content = {type: 'root', tabs: [data.content]}
+ } else {
+ data.content = {type: 'root', widgets: [data.content]}
+ }
+ this.isFragment = true
+ }
+
+ if (type === 'fragment' && data.type === 'session') {
+ // opening session as a fragment
+ data.content.type = 'panel'
+ }
+
+ data.createdWith = PACKAGE.productName
data.version = PACKAGE.version
- data.type = PACKAGE.productName + ' ' + 'session'
+ if (type) data.type = type
+
+ // push content to end of file
+ var c = data.content
+ delete data.content
+ data.content = c
this.data = data
@@ -68,7 +91,7 @@ module.exports = class Session {
getRoot() {
- return this.data.session
+ return this.data.content
}
@@ -189,7 +212,7 @@ var converters = [
}
break
case 'eq':
- data.filter = data.value
+ data.filters = data.value
data.value = ''
break
@@ -202,12 +225,15 @@ var converters = [
data.script = `
// converted from keys widget data
if (type === 'keyup') {
- ${String(data.keyUp).replace(/^JS{{(.*)}}$/, '$1')}
+ ${String(data.keyUp).trim().replace(/JS\{\{(.*)\}\}/s, '$1').trim()}
} else if (type === 'keydown') {
- ${String(data.keyDown).replace(/^JS{{(.*)}}$/, '$1')}
+ ${String(data.keyDown).trim().replace(/JS\{\{(.*)\}\}/s, '$1').trim()}
}
`
break
+ case 'script':
+ data.script = String(data.script).trim().replace(/JS\{\{(.*)\}\}/s, '$1').trim()
+ break
}
@@ -251,5 +277,75 @@ var converters = [
}
}
+ },
+ {
+ version: '1.8.15',
+ global: (data)=>{
+
+ data.content = data.session
+ delete data.session
+ return data
+
+ }
+ },
+ {
+ version: '1.13.2',
+ warning: true,
+ widget: (data)=>{
+
+ if (data.script !== undefined) {
+ if (data.type === 'script') {
+ if (data.event === 'once') {
+ data.onCreate = data.script
+ } else if (data.event === 'keyboard') {
+ data.onKeyboard = data.script
+ } else if (data.event === 'value') {
+ data.onValue = data.script
+ }
+ } else {
+ data.onValue = data.script
+ }
+ }
+ if (data.type === 'canvas') {
+ if (data.draw !== undefined) data.onDraw = data.draw
+ if (data.touch !== undefined) data.onTouch = data.touch
+ }
+
+ }
+ },
+ {
+ version: '1.23.0',
+ widget: (data)=>{
+ if (data.type === 'patchbay' && data.exclusive === true) {
+ data.exclusive = 'in'
+ }
+ else if ((data.type === 'panel' || data.type === 'root') && data.verticalTabs === true) {
+ data.tabsPosition = 'left'
+ delete data.verticalTabs
+ }
+ }
+ },
+ {
+ version: '1.24.2',
+ widget: (data)=>{
+ if (data.type === 'menu') {
+ if (data.toggle) {
+ data.mode = data.doubleTap ? 'toggle' : 'doubleTap-toggle'
+ } else if (data.doubleTap) {
+ data.mode = 'doubleTap'
+ } else {
+ data.mode = 'default'
+ }
+ delete data.toggle
+ delete data.doubleTap
+ }
+ }
}
]
+
+Session.converters = {}
+for (var i in converters) {
+ Session.converters[converters[i].version] = converters[i]
+}
+
+export default Session
diff --git a/src/client/managers/state.js b/src/client/managers/state.mjs
similarity index 87%
rename from src/client/managers/state.js
rename to src/client/managers/state.mjs
index ec488813..606a436b 100644
--- a/src/client/managers/state.js
+++ b/src/client/managers/state.mjs
@@ -1,12 +1,12 @@
-var ipc = require('../ipc'),
- widgetManager = require('./widgets'),
- cache = require('./cache'),
- uiFilebrowser = require('../ui/ui-filebrowser'),
- uiFileupload = require('../ui/ui-fileupload'),
- notifications = require('../ui/notifications'),
- {saveAs} = require('file-saver'),
- locales = require('../locales'),
- {deepCopy} = require('../utils')
+import {saveAs} from 'file-saver'
+import ipc from '../ipc/index.mjs'
+import widgetManager from './widgets.mjs'
+import cache from './cache.mjs'
+import uiFilebrowser from '../ui/ui-filebrowser.mjs'
+import uiFileupload from '../ui/ui-fileupload.mjs'
+import notifications from '../ui/notifications.mjs'
+import locales from '../locales/index.mjs'
+import {deepCopy} from '../utils.mjs'
var StateManager = class StateManager {
@@ -63,9 +63,9 @@ var StateManager = class StateManager {
for (var j = widgets.length - 1; j >= 0; j--) {
- if (widgets[j].setValue) {
+ if (widgets[j].setValue && !widgets[j].noValueState) {
- widgets[j].setValue(value, {send:send, sync:true, fromState:true})
+ widgets[j].setValue(value, {send:send, sync:true})
}
@@ -150,6 +150,7 @@ var StateManager = class StateManager {
this.set(state, send)
notifications.add({
icon: 'sliders-h',
+ class: 'state-recall',
message: locales('state_recallsuccess')
})
} catch(e) {
@@ -224,7 +225,8 @@ var StateManager = class StateManager {
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, fromState:true, fromEdit: true})
+ if (w.noValueState) continue
+ w.setValue(this.valueStateQueue[id], {sync: true, script: false})
}
}
}
@@ -232,7 +234,8 @@ var StateManager = class StateManager {
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, fromState:true})
+ if (w.noValueState) continue
+ w.setValue(w.getProp('value'), {sync: true})
}
}
}
@@ -257,4 +260,4 @@ var StateManager = class StateManager {
var stateManager = new StateManager()
-module.exports = stateManager
+export default stateManager
diff --git a/src/client/managers/widgets.js b/src/client/managers/widgets.mjs
similarity index 80%
rename from src/client/managers/widgets.js
rename to src/client/managers/widgets.mjs
index 940b8f92..cf569d9a 100644
--- a/src/client/managers/widgets.js
+++ b/src/client/managers/widgets.mjs
@@ -1,5 +1,5 @@
-var EventEmitter = require('../events/event-emitter'),
- ipc = require('../ipc/')
+import EventEmitter from '../events/event-emitter.mjs'
+import ipc from '../ipc/index.mjs'
class WidgetManager extends EventEmitter {
@@ -17,31 +17,29 @@ class WidgetManager extends EventEmitter {
this.linkIdLock = []
this.linkIdLockDepth = 0
- this.scrollingWidgets = []
-
this.preArgsSeparator = '||||'
- this.on('change', this.onChange.bind(this))
+ this.on('value-changed', this.onChange.bind(this))
ipc.on('connect', ()=>{
for (var hash in this.widgets) {
this.registerWidget(this.widgets[hash])
}
})
- setInterval(()=>{
-
- this.trigger('root-nav-changed')
- }, 1000)
}
onChange(e) {
+ if (!e) return
+
var {id, widget, linkId, options} = e
if (linkId) {
if (!Array.isArray(linkId)) linkId = [linkId]
linkId = linkId.map(x=>String(x).replace(/^>>\s*/, '')).filter(x=>x.indexOf('<<') < 0)
+ // scopable; prefix linkId with the closest (most restrictive) scope
+ if (widget.scopes.length) linkId = linkId.map(x => x + widget.scopes[0])
linkId = linkId.filter(x=>this.linkIdLock.indexOf(x)<0)
this.linkIdLock = this.linkIdLock.concat(linkId)
this.linkIdLockDepth++
@@ -51,12 +49,17 @@ class WidgetManager extends EventEmitter {
widgetsByLinkId = linkId ? this.getWidgetByLinkId(linkId) : []
// Widget that share the same id will update each other
- // without sending any extra osc message
+ // without sending any extra osc message or running scripts
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, id})
+ // Because of sync:false, updated widgets that use @{this}
+ // in their properties wont update them, we trigger it manually
+ if (widgetsById[i].linkedPropsValue['this']) {
+ widgetsById[i].onLinkedPropsChanged({id, widget: widgetsById[i], options: {send: false, sync: false, id}}, 'value-changed')
+ }
}
}
}
@@ -67,7 +70,7 @@ class WidgetManager extends EventEmitter {
let v = widget.getValue()
for (let i in widgetsByLinkId) {
if (widgetsByLinkId[i] !== widget) {
- widgetsByLinkId[i].setValue(v,{send: options.send,sync: true, id})
+ widgetsByLinkId[i].setValue(v,{send: options.send, sync: true, script:options.script, widget, id})
}
}
}
@@ -78,7 +81,6 @@ class WidgetManager extends EventEmitter {
this.linkIdLock = []
}
}
-
}
createAddressRef(widget, preArgs, address) {
@@ -102,9 +104,7 @@ class WidgetManager extends EventEmitter {
var hash = widget.hash,
address = this.createAddressRef(widget),
id = widget.getProp('id'),
- linkId = widget.getProp('linkId'),
- scroll = widget.getProp('scroll')
-
+ linkId = widget.getProp('linkId')
this.widgets[hash] = widget
@@ -119,6 +119,8 @@ class WidgetManager extends EventEmitter {
if (linkId) {
if (!Array.isArray(linkId)) linkId = [linkId]
linkId = linkId.map(x=>String(x).replace(/^<<\s*/, '')).filter(x=>x.indexOf('>>') < 0)
+ // scopable; prefix linkId with the closest (most restrictive) scope
+ if (widget.scopes.length) linkId = linkId.map(x => x + widget.scopes[0])
for (var i in linkId) {
if (linkId[i]) {
if (!this.linkIdRoute[linkId[i]]) this.linkIdRoute[linkId[i]] = []
@@ -127,10 +129,6 @@ class WidgetManager extends EventEmitter {
}
}
- if (scroll) {
- this.scrollingWidgets.push(hash)
- }
-
this.registerWidget(widget)
}
@@ -165,11 +163,12 @@ class WidgetManager extends EventEmitter {
var hash = widget.hash,
address = this.createAddressRef(widget),
linkId = widget.getProp('linkId'),
- id = widget.getProp('id'),
- scroll = widget.getProp('scroll')
+ id = widget.getProp('id')
if (this.widgets[hash]) {
- if (this.widgets[hash].onRemove) this.widgets[hash].onRemove()
+ if (this.widgets[hash].onRemove) {
+ this.widgets[hash].onRemove()
+ }
delete this.widgets[hash]
@@ -178,14 +177,16 @@ class WidgetManager extends EventEmitter {
})
widget.trigger('widget-removed', {widget: widget})
+ widget.off('widget-removed')
}
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]
- linkId = linkId.map(x=>String(x))
+ linkId = linkId.map(x=>String(x).replace(/^<<\s*/, '')).filter(x=>x.indexOf('>>') < 0)
+ // scopable; prefix linkId with the closest (most restrictive) scope
+ if (widget.scopes.length) linkId = linkId.map(x => x + widget.scopes[0])
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)
}
@@ -225,12 +226,6 @@ class WidgetManager extends EventEmitter {
}
}
- for (let i in this.scrollingWidgets) {
- if (!this.widgets[this.scrollingWidgets[i]]) {
- this.scrollingWidgets.splice(i, 1)
- }
- }
-
}
reset() {
@@ -239,7 +234,7 @@ class WidgetManager extends EventEmitter {
this.off()
- this.on('change', this.onChange.bind(this))
+ this.on('value-changed', this.onChange.bind(this))
}
@@ -271,7 +266,22 @@ class WidgetManager extends EventEmitter {
}
- getWidgetById(id) {
+ getWidgetById(id, scope) {
+
+ /*
+ scopable: return matching widgets only for the closest scope with results
+ */
+ if (scope && scope.length) {
+ if (!Array.isArray(scope)) scope = [scope]
+ for (var prefix of scope) {
+ var prefixedId = Array.isArray(id) ? id.map(i=>prefix + i) : prefix + id
+
+ var widgets = this.getWidgetBy(prefixedId, this.idRoute)
+
+ if (widgets.length) return widgets
+ }
+ return []
+ }
return this.getWidgetBy(id, this.idRoute)
@@ -337,4 +347,4 @@ class WidgetManager extends EventEmitter {
var widgetManager = new WidgetManager()
-module.exports = widgetManager
+export default widgetManager
diff --git a/src/client/osc.js b/src/client/osc.js
deleted file mode 100644
index 947f6b0e..00000000
--- a/src/client/osc.js
+++ /dev/null
@@ -1,82 +0,0 @@
-var widgetManager = require('./managers/widgets'),
- EventEmitter = require('./events/event-emitter'),
- ipc = require('./ipc/'),
- {deepEqual} = require('./utils')
-
-var Osc = class Osc extends EventEmitter {
-
- constructor() {
-
- super()
-
- this.syncOnly = false
- this.remoteControl = {}
- this.serverTargets = []
-
- setTimeout(()=>{
- osc.remoteControl = require('./remote-control')
- })
-
- }
-
- send(data) {
-
- if (this.syncOnly) {
-
- this.sync(data)
-
- } else {
-
- ipc.send('sendOsc', data)
-
- }
-
- }
-
- sync(data) {
-
- ipc.send('syncOsc', data)
-
- }
-
- receive(data){
-
- if (typeof this.remoteControl.exists === 'function' && 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'),
- match = true
-
- if (data._rawTarget) {
- // 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 exact same target
- match = deepEqual(widgetTarget, data._rawTarget)
- } else if (data.host === 'midi') {
- // if the message comes from a midi port, only update widgets that send to that port
- let widgetArrayTarget = Array.isArray(widgetTarget) ? widgetTarget : [widgetTarget],
- strTarget = data.host + ':' + data.port
-
- match = widgetArrayTarget.includes(strTarget) ||
- (!widgetArrayTarget.includes(null) && this.serverTargets.includes(strTarget))
-
- }
-
- if (match) {
- widgets[i].setValue(restArgs,{send:false,sync:true,fromExternal:!data.target})
- }
-
- }
-
- this.trigger(data.address, data.args)
-
- }
-
-}
-
-
-var osc = new Osc()
-
-module.exports = osc
diff --git a/src/client/osc.mjs b/src/client/osc.mjs
new file mode 100644
index 00000000..08223ccb
--- /dev/null
+++ b/src/client/osc.mjs
@@ -0,0 +1,94 @@
+import widgetManager from './managers/widgets.mjs'
+import EventEmitter from './events/event-emitter.mjs'
+import ipc from './ipc/index.mjs'
+import {deepEqual} from './utils.mjs'
+import {CLIENT_SYNC} from './globals.mjs'
+
+var Osc = class Osc extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.syncOnly = false
+ this.remoteControl = {}
+ this.serverTargets = []
+
+ ;(async()=>{
+ this.remoteControl = (await import('./remote-control.mjs')).default
+ })()
+
+ }
+
+ send(data) {
+
+ if (this.syncOnly) {
+
+ this.sync(data)
+
+ } else {
+
+ if (!CLIENT_SYNC) data.noSync = 1
+
+ ipc.send('sendOsc', data)
+
+ }
+
+ }
+
+ sync(data) {
+
+ if (CLIENT_SYNC) ipc.send('syncOsc', data)
+
+ }
+
+ match(widget, data) {
+
+ let widgetTarget = widget.getProp('target'),
+ match = true
+
+ if (data._rawTarget) {
+ // 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 exact same target
+ match = deepEqual(widgetTarget, data._rawTarget)
+
+ } else if (data.host === 'midi') {
+ // if the message comes from a midi port, only update widgets that send to that port
+ let widgetArrayTarget = Array.isArray(widgetTarget) ? widgetTarget : [widgetTarget],
+ strTarget = data.host + ':' + data.port
+
+ match = widgetArrayTarget.includes(strTarget) ||
+ (!widgetArrayTarget.includes(null) && this.serverTargets.includes(strTarget))
+
+ }
+
+ return match
+
+ }
+
+ receive(data){
+
+ if (data._rawTarget && !CLIENT_SYNC) return
+
+ if (typeof this.remoteControl.exists === 'function' && this.remoteControl.exists(data.address)) this.remoteControl.exec(data.address, data.args, data.cm)
+
+ var [widgets, restArgs] = widgetManager.getWidgetByAddressAndArgs(data.address, data.args)
+
+ for (let i in widgets) {
+
+ if (this.match(widgets[i], data)) {
+ widgets[i].setValue(restArgs,{send:false,sync:true,fromExternal:!data.target})
+ }
+
+ }
+
+ this.trigger(data.address, data)
+
+ }
+
+}
+
+
+var osc = new Osc()
+
+export default osc
diff --git a/src/client/parser.js b/src/client/parser.mjs
similarity index 80%
rename from src/client/parser.js
rename to src/client/parser.mjs
index 28702e57..38d6da48 100644
--- a/src/client/parser.js
+++ b/src/client/parser.mjs
@@ -1,6 +1,6 @@
-var widgetManager = require('./managers/widgets'),
- stateManager = require('./managers/state'),
- {deepCopy} = require('./utils')
+import widgetManager from './managers/widgets.mjs'
+import stateManager from './managers/state.mjs'
+import {deepCopy} from './utils.mjs'
var Parser = class Parser {
@@ -10,6 +10,13 @@ var Parser = class Parser {
this.widgets = {}
this.defaults = {}
+ ;(async()=>{
+ this.widgets = (await import('./widgets/index.mjs')).widgets
+ for (var k in this.widgets) {
+ this.defaults[k] = this.widgets[k].defaults()._props()
+ }
+ })()
+
}
getIterator(id) {
@@ -37,7 +44,9 @@ var Parser = class Parser {
children,
index,
hash,
- locals
+ locals,
+ variables,
+ meta
} = options
var props = data
@@ -58,7 +67,7 @@ var Parser = class Parser {
if (i.indexOf('_') !== 0 && props[i] === undefined) props[i] = deepCopy(defaults[i])
}
- // Genrate widget's id, based on its type
+ // Generate widget's id, based on its type
if (props.id === 'auto' || !props.id) {
var id
while (!id || widgetManager.getWidgetById(id).length) {
@@ -81,12 +90,12 @@ var Parser = class Parser {
children,
hash,
locals,
+ variables,
+ meta
})
widgetManager.addWidget(widget)
- widget.created(index)
-
// set widget's initial state
var defaultValue = widget.getProp('default'),
currentValue = widget.getProp('value')
@@ -97,10 +106,12 @@ var Parser = class Parser {
} else if (defaultValue !== '' && defaultValue !== undefined) {
- widget.setValue(defaultValue)
+ widget.setValue(defaultValue, {defaultInit: true})
}
+ widget.created(index)
+
parentNode.appendChild(widget.container)
widget.mounted = true
@@ -114,9 +125,4 @@ var Parser = class Parser {
var parser = new Parser()
-module.exports = parser
-
-parser.widgets = require('./widgets/').widgets
-for (var k in parser.widgets) {
- parser.defaults[k] = parser.widgets[k].defaults()._props()
-}
+export default parser
diff --git a/src/client/remote-control.js b/src/client/remote-control.mjs
similarity index 64%
rename from src/client/remote-control.js
rename to src/client/remote-control.mjs
index f0aa4c36..10526a5d 100644
--- a/src/client/remote-control.js
+++ b/src/client/remote-control.mjs
@@ -1,19 +1,21 @@
-var {updateWidget} = require('./editor/data-workers'),
- editor = require('./editor'),
- widgetManager = require('./managers/widgets'),
- stateManager = require('./managers/state'),
- sessionManager = require('./managers/session'),
- deepExtend = require('deep-extend'),
- notifications = require('./ui/notifications')
+import deepExtend from 'deep-extend'
+import {updateWidget} from './editor/data-workers.mjs'
+import editor from './editor/index.mjs'
+import widgetManager from './managers/widgets.mjs'
+import stateManager from './managers/state.mjs'
+import sessionManager from './managers/session'
+import notifications from './ui/notifications.mjs'
+import uiConsole from './ui/ui-console.mjs'
+import {READ_ONLY, JSON5} from './globals.mjs'
var callbacks = {
- '/EDIT': function(args) {
+ '/EDIT': function(args, custom_module) {
- if (READ_ONLY) return
+ if (READ_ONLY && !custom_module) return
var [id, json, opts] = args,
- newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
- options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
+ newdata = typeof json == 'string' ? JSON5.parse(json) : json,
+ options = typeof opts == 'string' ? JSON5.parse(opts) : {},
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
@@ -29,7 +31,7 @@ var callbacks = {
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs),
- changedProps: Object.keys(newdata)
+ editedProps: Object.keys(newdata)
})
}
@@ -39,13 +41,13 @@ var callbacks = {
if (options.noWarning) editor.unsavedSession = false
},
- '/EDIT/MERGE': function(args) {
+ '/EDIT/MERGE': function(args, custom_module) {
- if (READ_ONLY) return
+ if (READ_ONLY && !custom_module) return
var [id, json, opts] = args,
- newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
- options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
+ newdata = typeof json == 'string' ? JSON5.parse(json) : json,
+ options = typeof opts == 'string' ? JSON5.parse(opts) : {},
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
@@ -59,7 +61,7 @@ var callbacks = {
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs),
- changedProps: Object.keys(newdata)
+ editedProps: Object.keys(newdata)
})
}
@@ -69,16 +71,16 @@ var callbacks = {
if (options.noWarning) editor.unsavedSession = false
},
- '/EDIT/UNDO': function(args) {
+ '/EDIT/UNDO': function(args, custom_module) {
- if (READ_ONLY) return
+ if (READ_ONLY && !custom_module) return
editor.undo()
},
- '/EDIT/REDO': function(args) {
+ '/EDIT/REDO': function(args, custom_module) {
- if (READ_ONLY) return
+ if (READ_ONLY && !custom_module) return
editor.redo()
@@ -205,12 +207,13 @@ var callbacks = {
},
'/STATE/SET': function(args) {
- if (Array.isArray(args)) args = args[0]
+ if (!Array.isArray(args)) args = [args]
- var json = args,
- data = typeof json == 'string' ? JSON.parseFlex(json) : json
+ var json = args[0],
+ data = typeof json == 'string' ? JSON5.parse(json) : json,
+ send = !(args[1] === 0 || args[1] === false)
- stateManager.set(data)
+ stateManager.set(data, send)
},
'/STATE/STORE': function(args) {
@@ -222,6 +225,11 @@ var callbacks = {
stateManager.quickLoad()
+ },
+ '/STATE/SEND': function(args) {
+
+ stateManager.send()
+
},
'/STATE/OPEN': function(args) {
@@ -241,10 +249,28 @@ var callbacks = {
if (!Array.isArray(args)) args = [args]
+ var icon
+ if (args.length > 1 && typeof args[0] === 'string' && args[0].indexOf(' ') === -1) {
+ icon = args.shift()
+ }
+
notifications.add({
- message: args.join('\n') || ' '
+ message: args.join('\n') || ' ',
+ icon: icon
})
+ },
+ '/LOG': function(args) {
+
+ console.log(args)
+
+ },
+ '/SESSION/CREATE': function(args) {
+
+ editor.unsavedSession = false
+
+ sessionManager.create()
+
},
'/SESSION/OPEN': function(args) {
@@ -259,16 +285,39 @@ var callbacks = {
sessionManager.save(args[0])
+ },
+ '/TABS': function(args) {
+
+ if (!Array.isArray(args)) args = [args]
+
+ for (let id of args) {
+ let ws = widgetManager.getWidgetById(id)
+ for (let w of ws) {
+ if (w.getProp('type') === 'tab') {
+ var index = w.parent.children.indexOf(w)
+ w.parent.setValue(index, {sync: true, send: false})
+ }
+ }
+ }
+ },
+ '/SCRIPT': function(args) {
+
+ if (!Array.isArray(args)) args = [args]
+
+ uiConsole.script.run({input_code: args[0]}, {sync: true, send: true})
+
+ },
+ '/RELOAD': function(args) {
+
+ window.location.href = window.location.href
+
}
-
-
-
}
-module.exports = {
- exec: function(name, args){
+export default {
+ exec: function(name, args, custom_module){
if (callbacks[name]) {
- callbacks[name](args)
+ callbacks[name](args, custom_module)
}
},
exists: function(name){
diff --git a/src/client/stacktrace.js b/src/client/stacktrace.js
deleted file mode 100644
index 692b2f21..00000000
--- a/src/client/stacktrace.js
+++ /dev/null
@@ -1,33 +0,0 @@
-var StackTrace = require('stacktrace-js'),
- ipc = require('./ipc'),
- uiConsole
-
-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')
-
- if (!uiConsole) uiConsole = require('./ui/ui-console')
- uiConsole.log('error', `${msg}\n${stringifiedStack}`)
- ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n${stringifiedStack}`)
-
- }).catch(()=>{
-
- if (!uiConsole) uiConsole = require('./ui/ui-console')
- uiConsole.log('error', `${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
- ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
-
- })
-
-}
diff --git a/src/client/stacktrace.mjs b/src/client/stacktrace.mjs
new file mode 100644
index 00000000..e25bfd2f
--- /dev/null
+++ b/src/client/stacktrace.mjs
@@ -0,0 +1,21 @@
+import StackTrace from 'stacktrace-js'
+import ipc from './ipc/index.mjs'
+import uiConsole from './ui/ui-console.mjs'
+
+window.onerror = function(msg,url,row,col, error) {
+
+ StackTrace.fromError(error).then((stackframes)=>{
+
+ var stringifiedStack = ' ' + stackframes.join('\n ')
+
+ uiConsole.log('error', `${msg}\n${stringifiedStack}`)
+ ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n${stringifiedStack}`)
+
+ }).catch(()=>{
+
+ uiConsole.log('error', `${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
+ ipc.send('errorLog', `(ERROR, CLIENT) ${msg}\n at ${url}:${row}:${col}\n (no stacktrace available)`)
+
+ })
+
+}
diff --git a/src/client/ui/context-menu.js b/src/client/ui/context-menu.mjs
similarity index 88%
rename from src/client/ui/context-menu.js
rename to src/client/ui/context-menu.mjs
index 13b4dd78..9630f4d8 100644
--- a/src/client/ui/context-menu.js
+++ b/src/client/ui/context-menu.mjs
@@ -1,10 +1,11 @@
-var html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
- UiWidget = require('./ui-widget'),
- mod = (navigator.platform || '').match('Mac') ? 'cmd' : 'ctrl',
- MENU_CONTAINER
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import UiWidget from './ui-widget.mjs'
+import {DOM, PXSCALE} from '../globals.mjs'
+var mod = (navigator.platform || '').match('Mac') ? 'cmd' : 'ctrl',
+ MENU_CONTAINER
class ContextMenu extends UiWidget {
@@ -50,6 +51,7 @@ class ContextMenu extends UiWidget {
})
this.container.addEventListener('touchstart', (e)=>{
+ if (e.target.classList.contains('has-sub')) e.preventDefault()
if (!e.target.classList.contains('focus')) {
DOM.each(e.target.parentNode, '.focus', (el)=>{
el.classList.remove('focus')
@@ -81,18 +83,28 @@ class ContextMenu extends UiWidget {
iclass = typeof action.class === 'function' ? action .class() : action.class,
item = html`${raw(label)}`
- item.appendChild(submenu)
+ if (action.disabled) {
+
+ item.classList.add('disabled')
+
+ } else {
+
+ item.appendChild(submenu)
+
+ this.parse(action.action, submenu)
+
+ }
+
node.appendChild(item)
- this.parse(action.action, submenu)
-
-
} else {
let label = typeof action.label === 'function' ? action.label() : action.label,
iclass = typeof action.class === 'function' ? action.class() : action.class,
item = html`${raw(label)}`
+ if (action.disabled) item.classList.add('disabled')
+
item._action = action.action
node.appendChild(item)
@@ -185,6 +197,8 @@ class ContextMenu extends UiWidget {
for (let action of actions) {
+ if (action.disabled) continue
+
if (Array.isArray(action.action)) {
this.bindShortcuts(action.action)
@@ -204,4 +218,4 @@ class ContextMenu extends UiWidget {
}
-module.exports = ContextMenu
+export default ContextMenu
diff --git a/src/client/ui/fullscreen.js b/src/client/ui/fullscreen.mjs
similarity index 70%
rename from src/client/ui/fullscreen.js
rename to src/client/ui/fullscreen.mjs
index cb069a36..af0787fb 100644
--- a/src/client/ui/fullscreen.js
+++ b/src/client/ui/fullscreen.mjs
@@ -1,7 +1,7 @@
-var screenfull = require('screenfull'),
- UiModal = require('./ui-modal'),
- locales = require('../locales'),
- iOS = require('./ios')
+import screenfull from 'screenfull'
+import UiModal from './ui-modal.mjs'
+import locales from '../locales/index.mjs'
+import iOS from './ios.mjs'
var fullscreen
@@ -38,5 +38,6 @@ if (screenfull.isEnabled && !iOS) {
}
+window.ELECTRON_FULLSCREEN = ()=>{fullscreen.toggle()}
-module.exports = fullscreen
+export default fullscreen
diff --git a/src/client/ui/index.js b/src/client/ui/index.js
deleted file mode 100644
index f49195cc..00000000
--- a/src/client/ui/index.js
+++ /dev/null
@@ -1,7 +0,0 @@
-var UiSidePanel = require('./ui-sidepanel'),
- locales = require('../locales')
-
-module.exports = {
- leftUiSidePanel: new UiSidePanel({selector: 'osc-panel-container.left', label: locales('editor_tree')}),
- rightUiSidePanel: new UiSidePanel({selector: 'osc-panel-container.right', label: locales('editor_inspector')})
-}
diff --git a/src/client/ui/index.mjs b/src/client/ui/index.mjs
new file mode 100644
index 00000000..62a03c9b
--- /dev/null
+++ b/src/client/ui/index.mjs
@@ -0,0 +1,5 @@
+import UiSidePanel from './ui-sidepanel.mjs'
+import locales from '../locales/index.mjs'
+
+export const leftUiSidePanel = new UiSidePanel({selector: 'osc-panel-container.left', label: locales('editor_tree')})
+export const rightUiSidePanel= new UiSidePanel({selector: 'osc-panel-container.right', label: locales('editor_inspector')})
diff --git a/src/client/ui/init.js b/src/client/ui/init.js
deleted file mode 100644
index a93d9d2f..00000000
--- a/src/client/ui/init.js
+++ /dev/null
@@ -1,7 +0,0 @@
-require('./zoom')
-require('../events/click')
-require('./ios')
-require('./notifications')
-require('./ui-workspace')
-require('./main-menu')
-require('./ui-console')
diff --git a/src/client/ui/init.mjs b/src/client/ui/init.mjs
new file mode 100644
index 00000000..072a3341
--- /dev/null
+++ b/src/client/ui/init.mjs
@@ -0,0 +1,14 @@
+import './zoom.mjs'
+import '../events/click.mjs'
+import './ios.mjs'
+import './notifications.mjs'
+import './ui-workspace.mjs'
+import './main-menu.mjs'
+import './ui-console.mjs'
+import {updateMobileThemeColor, device} from './utils.mjs'
+
+updateMobileThemeColor()
+
+if (!device.is('mobile') && !device.is('tablet')) {
+ import('./ui-keyboard.mjs')
+}
diff --git a/src/client/ui/ios.js b/src/client/ui/ios.js
deleted file mode 100644
index 64372b29..00000000
--- a/src/client/ui/ios.js
+++ /dev/null
@@ -1,42 +0,0 @@
-// Prevent iOS Pull-To-Refresh
-
-var iOS13 = (
- navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 // iPad
- || navigator.userAgent.match(/iPhone OS (1[3-9])/) // iPhone
- ),
- iOS = navigator.platform.match(/iPhone|iPod|iPad/) || iOS13
-
-if (iOS && !iOS13) {
-
- // prevent overscroll
- // breaks scrolling on iOS13 (besides it doesn't seem to be needed)
-
- var supportsPassiveOption = false
- try {
- document.createElement('div').addEventListener('test', function() {}, {
- get passive() {
- supportsPassiveOption = true
- return false
- }
- })
- } catch(e) {}
-
- iOS = true
-
- var preventNextMove = false
-
- document.addEventListener('touchstart', (e)=>{
- if (e.touches.length === 1 && !e.target._drag_widget) preventNextMove = true
- }, supportsPassiveOption ? {passive: false} : false)
-
- document.addEventListener('touchmove', (e)=>{
- // preventDefault the first overscrolling touchmove
- if (preventNextMove) {
- preventNextMove = false
- e.preventDefault()
- }
- }, supportsPassiveOption ? {passive: false} : false)
-
-}
-
-module.exports = iOS
diff --git a/src/client/ui/ios.mjs b/src/client/ui/ios.mjs
new file mode 100644
index 00000000..c9f3267e
--- /dev/null
+++ b/src/client/ui/ios.mjs
@@ -0,0 +1,59 @@
+import {DOM} from '../globals.mjs'
+import {device, os} from './utils.mjs'
+
+
+var iOS = (device.is('mobile') || device.is('tablet')) && os.is('ios')
+
+// Prevent iOS Pull-To-Refresh
+
+if (iOS && parseInt(os.version.split('.')[0]) < 13) {
+
+ // prevent overscroll
+ // breaks scrolling on iOS <= 13 (besides it doesn't seem to be needed)
+
+ var supportsPassiveOption = false
+ try {
+ document.createElement('div').addEventListener('test', function() {}, {
+ get passive() {
+ supportsPassiveOption = true
+ return false
+ }
+ })
+ } catch(e) {}
+
+ iOS = true
+
+ var preventNextMove = false
+
+ document.addEventListener('touchstart', (e)=>{
+ if (e.touches.length === 1 && !e.target._drag_widget) preventNextMove = true
+ }, supportsPassiveOption ? {passive: false} : false)
+
+ document.addEventListener('touchmove', (e)=>{
+ // preventDefault the first overscrolling touchmove
+ if (preventNextMove) {
+ preventNextMove = false
+ e.preventDefault()
+ }
+ }, supportsPassiveOption ? {passive: false} : false)
+
+
+}
+
+if (iOS) {
+ // when waking from sleep, iOS may have trouble rendering the session properly
+ // this attempts to force a full redraw by shortly resizing the main container
+ document.onvisibilitychange = ()=>{
+ if (document.visibilityState === 'visible') {
+ var main = DOM.get('osc-panel-container#main')[0]
+ main.style.marginBottom = '1px'
+ main.style.marginRight = '1px'
+ setTimeout(()=>{
+ main.style.marginBottom = ''
+ main.style.marginRight = ''
+ })
+ }
+ }
+}
+
+export default iOS
diff --git a/src/client/ui/main-menu.js b/src/client/ui/main-menu.mjs
similarity index 55%
rename from src/client/ui/main-menu.js
rename to src/client/ui/main-menu.mjs
index 72cb9777..092c002a 100644
--- a/src/client/ui/main-menu.js
+++ b/src/client/ui/main-menu.mjs
@@ -1,13 +1,16 @@
-var UiToolbar = require('./ui-toolbar'),
- ipc = require('../ipc'),
- locales = require('../locales'),
- notifications = require('./notifications'),
- fullscreen = require('./fullscreen'),
- editor = require('../editor'),
- sessionManager = require('../managers/session/'),
- stateManager = require('../managers/state'),
- {leftUiSidePanel, rightUiSidePanel} = require('../ui/'),
- uiConsole = require('../ui/ui-console')
+import NoSleep from 'nosleep.js'
+import UiToolbar from './ui-toolbar.mjs'
+import ipc from '../ipc/index.mjs'
+import locales from '../locales/index.mjs'
+import notifications from './notifications.mjs'
+import fullscreen from './fullscreen.mjs'
+import editor from '../editor/index.mjs'
+import sessionManager from '../managers/session/index.mjs'
+import stateManager from '../managers/state.mjs'
+import {leftUiSidePanel, rightUiSidePanel} from '../ui/index.mjs'
+import uiConsole from '../ui/ui-console.mjs'
+import {READ_ONLY, KIOSK, VIRTUAL_KEYBOARD, setVIRTUAL_KEYBOARD} from '../globals.mjs'
+import {device} from './utils.mjs'
var recentSessions = [{label: locales('file_open_recent_wait'), class: 'disabled'}]
@@ -15,11 +18,12 @@ var menuEntries = [
{
label: locales('session'),
+ disabled: READ_ONLY,
action: [
{
label: locales('session_new'),
action: sessionManager.create.bind(sessionManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'session-new'
},
{
separator: true
@@ -28,7 +32,7 @@ var menuEntries = [
label: locales('file_open'),
action: sessionManager.browse.bind(sessionManager),
shortcut: 'mod + o',
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'session-open'
},
{
label: locales('file_open_recent'),
@@ -42,13 +46,31 @@ var menuEntries = [
label: locales('file_save'),
action: sessionManager.save.bind(sessionManager),
shortcut: 'mod + s',
- class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ class: ()=>{return sessionManager.session === null ? 'disabled' :''},
+ id: 'session-save'
},
{
label: locales('file_save_as'),
action: sessionManager.saveAs.bind(sessionManager),
shortcut: 'mod + shift + s',
- class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ class: ()=>{return sessionManager.session === null ? 'disabled' :''},
+ id: 'session-save-as'
+ },
+ {
+ label: locales('fragment_mode'),
+ class: ()=>{return 'toggle ' + (sessionManager.saveMode === 'fragment' ? 'on' : 'off')},
+ action: ()=>{sessionManager.setSaveMode(sessionManager.saveMode === 'session' ? 'fragment' : 'session')},
+ id: 'session-fragment'
+ },
+ {
+ separator: true
+ },
+ {
+ label: locales('file_backup'),
+ action: sessionManager.saveBackup.bind(sessionManager),
+ shortcut: 'mod + b',
+ class: ()=>{return sessionManager.session === null || !sessionManager.sessionPath ? 'disabled' :''},
+ id: 'session-backup'
},
{
separator: true
@@ -56,28 +78,32 @@ var menuEntries = [
{
label: locales('file_import'),
action: sessionManager.import.bind(sessionManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'session-import'
},
{
label: locales('file_export'),
action: sessionManager.export.bind(sessionManager),
- class: ()=>{return READ_ONLY || sessionManager.session === null ? 'disabled' :''}
+ class: ()=>{return sessionManager.session === null ? 'disabled' :''},
+ id: 'session-export'
},
]
},
{
label: locales('state'),
+ disabled: READ_ONLY,
class: ()=>{return sessionManager.session === null ? 'disabled' : ''},
action: [
{
label: locales('state_store'),
- action: stateManager.quickSave.bind(stateManager)
+ action: stateManager.quickSave.bind(stateManager),
+ id: 'state-store'
},
{
label: locales('state_recall'),
class: ()=>{return stateManager.quickState === null ? 'disabled' : ''},
- action: stateManager.quickLoad.bind(stateManager)
+ action: stateManager.quickLoad.bind(stateManager),
+ id: 'state-recall'
},
{
label: locales('state_send'),
@@ -87,7 +113,8 @@ var menuEntries = [
icon: 'sliders-h',
message: locales('state_sendsuccess')
})
- }
+ },
+ id: 'state-send'
},
{
separator: true
@@ -95,17 +122,17 @@ var menuEntries = [
{
label: locales('file_open'),
action: stateManager.browse.bind(stateManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'state-open'
},
{
label: locales('file_save'),
action: stateManager.save.bind(stateManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'state-save'
},
{
label: locales('file_save_as'),
action: stateManager.saveAs.bind(stateManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'state-save-as'
},
{
separator: true
@@ -113,18 +140,19 @@ var menuEntries = [
{
label: locales('file_import'),
action: stateManager.import.bind(stateManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'state-import'
},
{
label: locales('file_export'),
action: stateManager.export.bind(stateManager),
- class: ()=>{return READ_ONLY ? 'disabled' :''}
+ id: 'state-export'
},
]
},
{
label: locales('editor'),
- class: ()=>{return sessionManager.session === null || READ_ONLY ? 'disabled' : ''},
+ disabled: READ_ONLY,
+ class: ()=>{return sessionManager.session === null ? 'disabled' : ''},
action: [
{
label: locales('editor_enabled'),
@@ -133,7 +161,8 @@ var menuEntries = [
if (editor.enabled) editor.disable()
else editor.enable()
},
- shortcut: 'mod + e'
+ shortcut: 'mod + e',
+ id: 'editor-enabled'
},
{
separator: true
@@ -142,22 +171,22 @@ var menuEntries = [
label: locales('editor_grid'),
class: ()=>{return 'toggle ' + (editor.grid ? 'on' : 'off')},
action: editor.toggleGrid.bind(editor),
- shortcut: 'mod + g'
-
+ shortcut: 'mod + g',
+ id: 'editor-grid'
},
{
label: locales('editor_tree'),
class: ()=>{return 'toggle ' + (leftUiSidePanel.minimized ? 'off' : 'on')},
action: ()=>{return leftUiSidePanel.minimized ? leftUiSidePanel.restore() : leftUiSidePanel.minimize()},
- shortcut: 'mod + t'
-
-
+ shortcut: 'mod + t',
+ id: 'editor-tree'
},
{
label: locales('editor_inspector'),
class: ()=>{return 'toggle ' + (rightUiSidePanel.minimized ? 'off' : 'on')},
action: ()=>{return rightUiSidePanel.minimized ? rightUiSidePanel.restore() : rightUiSidePanel.minimize()},
- shortcut: 'mod + i'
+ shortcut: 'mod + i',
+ id: 'editor-inspector'
},
{
separator: true
@@ -165,18 +194,28 @@ var menuEntries = [
{
label: locales('editor_percents'),
class: ()=>{return 'toggle ' + (editor.usePercents ? 'on' : 'off')},
- action: ()=>{editor.usePercents = !editor.usePercents}
+ action: ()=>{editor.usePercents = !editor.usePercents},
+ id: 'editor-percents'
}
]
},
{
label: locales('console'),
+ disabled: READ_ONLY,
action: [
{
label: locales('console_enabled'),
class: ()=>{return 'toggle ' + (uiConsole.minimized ? 'off' : 'on')},
- action: ()=>{return uiConsole.minimized ? uiConsole.restore() : uiConsole.minimize()},
- shortcut: 'mod + k'
+ action: ()=>{
+ if (uiConsole.minimized) {
+ uiConsole.restore()
+ uiConsole.input.focus()
+ } else {
+ uiConsole.minimize()
+ }
+ },
+ shortcut: 'mod + k',
+ id: 'console-enabled'
},
{
separator: true
@@ -184,6 +223,9 @@ var menuEntries = [
{
label: locales('console_clear'),
action: uiConsole.clear.bind(uiConsole),
+ shortcut: 'mod + l',
+ id: 'console-clear'
+
},
]
},
@@ -192,29 +234,72 @@ var menuEntries = [
},
{
label: locales('fullscreen'),
+ disabled: KIOSK && navigator.userAgent.match(/OpenStageControl/), // built-in electron client only
class: ()=>{return 'toggle ' + (fullscreen.isFullscreen ? 'on' : 'off')},
action: ()=>{
if (fullscreen.isEnabled) fullscreen.toggle()
},
- shortcut: 'f11'
+ shortcut: 'f11',
+ id: 'fullscreen'
+ },
+ {
+ label: locales('notifications'),
+ class: ()=>{return 'toggle ' + (notifications.visible ? 'on' : 'off')},
+ action: ()=>{
+ notifications.setVisibility(!notifications.visible)
+ },
+ id: 'notifications'
}
]
-if (navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) {
+if (device.is('mobile') || device.is('tablet')) {
- var NoSleep = require('nosleep.js'),
- noSleep = new NoSleep(),
- noSleepState = false
+
+ var noSleep = new NoSleep(),
+ noSleepState = false,
+ wakeLock = null
menuEntries.push({
label: locales('nosleep'),
class: ()=>{return 'toggle ' + (noSleepState ? 'on' : 'off')},
action:()=>{
noSleepState = !noSleepState
- if (noSleepState) noSleep.disable()
- else noSleep.enable()
- }
+ if (noSleepState) {
+ if ('wakeLock' in navigator) {
+ navigator.wakeLock.request('screen').then((l)=>{
+ wakeLock = l
+ wakeLock.addEventListener('release', ()=>{
+ noSleepState = false
+ })
+ }).catch((err)=>{
+ console.error(`Could not acquire wake lock:\n${err.name}, ${err.message}`)
+ wakeLock = null
+ })
+ }
+ if (wakeLock === null) noSleep.enable()
+ } else {
+ if ('wakeLock' in navigator && wakeLock !== null) {
+ wakeLock.release().then(()=>{
+ wakeLock = null
+ })
+ } else {
+ noSleep.disable()
+ }
+ }
+ },
+ id: 'prevent-sleep'
+ })
+
+} else {
+
+ menuEntries.push({
+ label: locales('keyboard'),
+ class: ()=>{return 'toggle ' + (VIRTUAL_KEYBOARD ? 'on' : 'off')},
+ action: ()=>{
+ setVIRTUAL_KEYBOARD(!VIRTUAL_KEYBOARD)
+ },
+ id: 'virtual-keyboard'
})
}
@@ -246,4 +331,4 @@ class MainMenu extends UiToolbar {
}
-module.exports = new MainMenu({selector: '#main-menu', position: [40, 1], entries: menuEntries})
+export default new MainMenu({selector: '#main-menu', position: [40, 1], entries: menuEntries})
diff --git a/src/client/ui/notifications.js b/src/client/ui/notifications.mjs
similarity index 68%
rename from src/client/ui/notifications.js
rename to src/client/ui/notifications.mjs
index 2a5f329a..19bafba5 100644
--- a/src/client/ui/notifications.js
+++ b/src/client/ui/notifications.mjs
@@ -1,5 +1,9 @@
-var html = require('nanohtml'),
- morph = require('nanomorph')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import morph from 'nanomorph'
+import UiWidget from './ui-widget.mjs'
+import {DOM, ENV} from '../globals.mjs'
+import {icon} from './utils'
var DEFAULT_DURATION = 3500
@@ -18,8 +22,8 @@ class Toast {
this.expires = Date.now() + (data.duration || DEFAULT_DURATION)
var toast = html`
-
-
+
+ ${raw(icon(data.icon || (data.class === 'error' ? 'exclamation' : 'bell')))}
`
@@ -53,14 +57,24 @@ class Toast {
}
-class Notifications {
+class Notifications extends UiWidget {
- constructor() {
+ constructor(options) {
+
+ super(options)
- this.container = DOM.get('#notifications')[0]
this.toasts = []
this.loop = null
+ this.visible = undefined
+
+ this.setVisibility(ENV.notifications != 0)
+
+ this.container.addEventListener('fast-click', (e)=>{
+ for (var toast of this.toasts) {
+ if (toast.html.contains(e.target)) this.remove(toast)
+ }
+ })
}
@@ -116,6 +130,13 @@ class Notifications {
}
+ setVisibility(v) {
+
+ this.visible = v
+ this.container.style.display = v ? '' : 'none'
+
+ }
+
}
-module.exports = new Notifications()
+export default new Notifications({selector: '#notifications'})
diff --git a/src/client/ui/scrollbar-color.js b/src/client/ui/scrollbar-color.js
deleted file mode 100644
index 6606903e..00000000
--- a/src/client/ui/scrollbar-color.js
+++ /dev/null
@@ -1,27 +0,0 @@
-var chroma = require('chroma-js')
-
-module.exports = (container)=>{
-
- setTimeout(()=>{
-
- var computedStyle = window.getComputedStyle(container),
- alpha = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar')),
- alphaOn = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar-on')),
- color = computedStyle.getPropertyValue('--color-fill').trim()
-
- if (color === 'transparent') {
- // prevent chroma-js error
- // irrelevant case, but still...
- color = 'rgb(0, 0, 0)'
- alpha = 0
- alphaOn = 0
- }
-
- if (color) {
- container.style.setProperty('--color-scrollbar', chroma(color).alpha(alpha).css())
- container.style.setProperty('--color-scrollbar-on', chroma(color).alpha(alphaOn).css())
- }
-
- })
-
-}
diff --git a/src/client/ui/ui-code-editor.mjs b/src/client/ui/ui-code-editor.mjs
new file mode 100644
index 00000000..8998f752
--- /dev/null
+++ b/src/client/ui/ui-code-editor.mjs
@@ -0,0 +1,343 @@
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import UiModal from './ui-modal.mjs'
+import locales from '../locales/index.mjs'
+import {icon} from '../ui/utils.mjs'
+import scriptVm from '../widgets/scripts/script-vm.mjs'
+import modeJavascript from 'ace-builds/src-noconflict/mode-javascript.js'
+import modeCss from 'ace-builds/src-noconflict/mode-css.js'
+import modeHtml from 'ace-builds/src-noconflict/mode-html.js'
+import {DOM} from '../globals.mjs'
+
+
+var scriptGlobals = scriptVm.globals,
+ editors = {}, editorModes = {
+ javascript: modeJavascript,
+ css: modeCss,
+ html: modeHtml
+ },
+ codeEditorModKey = (navigator.platform || '').match('Mac') ? 'Cmd' : 'Ctrl'
+
+
+const ace = window.ace
+ace.config.set('basePath', '/__APP_DIR__/client/ace/')
+
+function setCommandEnabled(editor, name, enabled) {
+ var command = editor.commands.byName[name]
+ if (!command.bindKeyOriginal)
+ command.bindKeyOriginal = command.bindKey
+ command.bindKey = enabled ? command.bindKeyOriginal : null
+ editor.commands.addCommand(command)
+}
+
+
+class CodeEditor {
+
+ constructor(parent, name, language, syntaxChecker) {
+
+ this.parent = parent
+ this.name = name
+ this.language = language
+ this.syntaxChecker = syntaxChecker
+
+ this.field = null
+ this.input = null
+ this.widget = null
+ this.container = html``
+ this.helpBtn = html`${locales('editor_ace_help')}`
+ this.fsBtn = html`${raw(icon('expand'))}`
+
+ this.helpBtn.addEventListener('fast-click', (e)=>{
+ this.help()
+ })
+ this.fsBtn.addEventListener('fast-click', (e)=>{
+ this.fullscreen()
+ })
+
+ this.closeKey = ((e)=>{
+ // this handler may remain dangling if closing with ctrl+enter
+ // we ignore this as it has no effect
+ if (e.key != 'Escape') return
+ this.field.classList.remove('fullscreen')
+ this.editor.setOptions({maxLines: 30})
+ this.editor.fullscreen = false
+ document.removeEventListener('keydown', this.closeKey)
+ this.field.removeEventListener('fast-click', this.closeClick)
+ this.editor.blur()
+ this.parent.parentContainer.classList.remove('editor-breakout')
+ }).bind(this)
+
+ this.closeClick = ((e)=>{
+ if (e.target === this.field) {
+ this.closeKey({key: 'Escape'})
+ }
+ }).bind(this)
+
+ this.editor = ace.edit(this.container)
+
+ if (editorModes[language]) this.editor.getSession().setMode('ace/mode/' + language)
+
+ this.editor.setOptions({
+ autoScrollEditorIntoView: true,
+ copyWithEmptySelection: true,
+ highlightIndentGuides:false,
+ tooltipFollowsMouse: false,
+ tabSize: 2,
+ maxLines: 30,
+ dragEnabled: false,
+ useWorker: syntaxChecker !== false
+ })
+
+ this.editor.$blockScrolling = Infinity
+ this.editor.commands.bindKeys({
+ 'ctrl-l': null, 'ctrl-f': null, 'ctrl-h': null, 'ctrl-,': null,
+ 'cmd-l': null, 'cmd-f': null, 'cmd-h': null, 'cmd-,': null,
+ })
+ this.editor.renderer.setScrollMargin(4, 4, 0, 4)
+ this.editor.element = this.container
+ this.editor.element.classList.add('ace_dark')
+ this.editor.textarea = DOM.get(this.container, '.ace_text-input')[0]
+ this.editor.textarea.name = name
+ this.editor.textarea._ace = true
+ this.editor.setHighlightActiveLine(false)
+ this.editor.setHighlightGutterLine(false)
+
+ if (language === 'javascript' && syntaxChecker !== false) {
+ this.editor.getSession().$worker.send('setOptions', [{
+ asi: true, // no semicolon
+ esversion: 7,
+ strict: 'implied',
+ node: false,
+ browser: true,
+ validthis: true,
+ undef: true,
+ globals: {}
+ }])
+ }
+
+ this.container.addEventListener('mousedown', (e)=>{
+ if (e.button === 1) {
+ e.preventDefault()
+ e.stopPropagation()
+ }
+ }, {capture: true})
+
+ }
+
+ bind(widget, field) {
+
+ this.widget = widget
+ this.field = field
+ this.input = DOM.get(field, 'textarea')[0]
+
+ var editor = this.editor,
+ input = this.input
+
+ input.style.display = 'none'
+ input._ace_input = editor.textarea
+ input.tabIndex = -1
+
+ editor.setValue(input.value)
+ editor.textarea.osc_input = input
+ editor.textarea.tabIndex = 0
+
+ this.field.classList.remove('dirty')
+
+ editor.removeAllListeners('focus')
+ this.editor.on('focus', (e)=>{
+ this.parent.focusedInput = this.input
+ this.editor.setHighlightActiveLine(true)
+ this.editor.setHighlightGutterLine(true)
+
+ this.editor.removeAllListeners('blur')
+ this.editor.removeAllListeners('change')
+ this.editor.removeAllListeners('changeSelection')
+ this.editor.on('change', (e)=>{
+ this.input.value = this.editor.getValue()
+ this.editor.dirty = true
+ if (this.editor.fullscreen) {
+ this.field.classList.add('dirty')
+ }
+ })
+
+ this.typing = false
+ setCommandEnabled(this.editor, 'indent', false)
+ setCommandEnabled(this.editor, 'outdent', false)
+
+ setTimeout(()=>{
+ if (this.pos) {
+ this.editor.moveCursorTo(this.pos.row, this.pos.column)
+ } else {
+ var pos = this.editor.getCursorPosition()
+ if (pos.row === undefined || pos.column === undefined) {
+ this.editor.gotoLine(0)
+ }
+
+ }
+
+ this.typing = false
+ this.editor.on('changeSelection', ()=>{
+ if (this.typing) return
+ let pos = this.editor.getCursorPosition()
+ if (pos.row || pos.column) {
+ setCommandEnabled(this.editor, 'indent', true)
+ setCommandEnabled(this.editor, 'outdent', true)
+ }
+ this.typing = true
+ })
+ })
+
+
+ this.editor.on('blur', (e)=>{
+ this.pos = this.editor.getCursorPosition()
+ this.editor.setHighlightActiveLine(false)
+ this.editor.setHighlightGutterLine(false)
+ this.editor.selection.setRange({start:0,end:0})
+ if (this.editor.fullscreen) {
+ e.preventDefault()
+ return
+ }
+ this.input.value = this.editor.getValue()
+ this.parent.focusedInput = this.input
+ if (this.editor.dirty) {
+ this.editor.dirty = false
+ this.parent.onChange()
+ }
+ this.parent.focusedInput = null
+
+ })
+
+ })
+
+
+ editor.setOptions({maxLines: 30})
+ editor.dirty = false
+
+ if (this.language === 'javascript') {
+ let globals = {}
+
+ if (this.name === 'onKeyboard') {
+ globals = {type: true, key: true, code: true, ctrl: true, shift: true, alt: true, meta: true}
+ } else if (this.name === 'onCreate') {
+ globals = {value: true}
+ } else if (this.name === 'onValue') {
+ globals = {id: true, value: true, touch: true}
+ } else if (this.name === 'onDraw') {
+ globals = {value: true, height: true, width: true, ctx: true, cssVars: true}
+ } else if (this.name === 'onTouch') {
+ globals = this.widget.getProp('type') === 'canvas' ?
+ {value: true, height: true, width: true, event: true} :
+ {value: true, event: true, handle: true}
+ } else if (this.name === 'onResize') {
+ globals = {value: true, height: true, width: true, cssVars: true}
+ }
+
+ for (var k in scriptGlobals) {
+ globals[k] = true
+ }
+
+ globals.locals = true
+ globals.console = true
+ globals.JS = true
+ globals.this = false
+
+ if (this.syntaxChecker !== false) editor.getSession().$worker.send('changeOptions', [{
+ globals: globals
+ }])
+ }
+
+ field.appendChild(editor.element)
+ field.appendChild(this.helpBtn)
+ field.appendChild(this.fsBtn)
+
+ editor.selection.setRange({start:0,end:0})
+
+ if (this.hash !== widget.hash) {
+ // preserve undo history if widget is the same
+ editor.getSession().getUndoManager().reset()
+ this.hash = widget.hash
+ this.pos = null
+ } else if (editor.fullscreen) {
+ this.fullscreen()
+ }
+
+ editor.resize()
+
+ }
+
+ fullscreen() {
+
+ this.editor.fullscreen = this.field.classList.toggle('fullscreen')
+ this.editor.setOptions({maxLines: this.editor.fullscreen ? 0 : 30})
+ this.field.style.setProperty('--prefix', this.editor.fullscreen ? '"' + this.widget.getProp('id') + '."' : '')
+ setTimeout(()=>{
+ window.dispatchEvent(new Event('resize'))
+ })
+
+ if (this.editor.fullscreen) {
+ this.parent.parentContainer.classList.add('editor-breakout')
+ this.editor.focus()
+ document.addEventListener('keydown', this.closeKey)
+ this.field.addEventListener('fast-click', this.closeClick)
+ } else {
+ this.parent.parentContainer.classList.remove('editor-breakout')
+ document.removeEventListener('keydown', this.closeKey)
+ this.field.removeEventListener('fast-click', this.closeClick)
+ }
+ }
+
+ help() {
+
+ var keybindings = []
+ var commandMap = {}
+
+ this.editor.keyBinding.$handlers.forEach(function(handler) {
+ var ckb = handler.commandKeyBinding
+ for (var i in ckb) {
+ var key = i.replace(/(^|-)\w/g, function(x) { return x.toUpperCase() })
+ var commands = ckb[i]
+ if (!Array.isArray(commands))
+ commands = [commands]
+ commands.forEach(function(command) {
+ if (typeof command != 'string')
+ command = command.name
+ if (commandMap[command]) {
+ commandMap[command].key += '|' + key
+ } else {
+ commandMap[command] = {key: key, command: command}
+ keybindings.push(commandMap[command])
+ }
+ })
+ }
+ })
+
+ var modal = new UiModal({closable: true, title: html`${locales('editor_ace_help_title')}`, html: true, content: html`
+
+
+
+
+ Shortcut
+ Command
+
+
+ ${codeEditorModKey}-Enter save
+ ${keybindings.map(k=>html`${k.key} ${k.command} `)}
+
+
+ `})
+
+
+ this.parent.helpModalOpened = true
+
+ modal.on('close', ()=>{
+ this.parent.helpModalOpened = false
+ })
+
+ }
+
+}
+
+export default function(parent, name, language, syntaxChecker) {
+ if (!editors[name]) editors[name] = new CodeEditor(parent, name, language, syntaxChecker)
+ return editors[name]
+}
diff --git a/src/client/ui/ui-colorpicker.js b/src/client/ui/ui-colorpicker.js
deleted file mode 100644
index dc7b3576..00000000
--- a/src/client/ui/ui-colorpicker.js
+++ /dev/null
@@ -1,119 +0,0 @@
-var UiWidget = require('./ui-widget'),
- Rgb = require('../widgets/pads/rgb'),
- UiModal = require('./ui-modal'),
- html = require('nanohtml'),
- chroma = require('chroma-js'),
- resize = require('../events/resize'),
- locales = require('../locales')
-
-
-class ColorPicker extends UiWidget {
-
- constructor() {
-
- super({})
-
- this.name = ''
- this.value = ''
-
- this.rgb = new Rgb({props: {
- ...Rgb.defaults()._props(),
- type: 'rgb',
- width: 'auto',
- height: 'auto',
- alphaStroke: 0,
- snap: true,
- alpha: true
- }, parent: this})
- this.rgb.container.classList.add('not-editable')
-
- this.modal = new UiModal({
- width: 280,
- height: 320,
- closable: true,
- title: '',
- hide: true,
- html: true,
- content: html`
-
- ${this.rgb.container}
-
- ${locales('inspector_color_apply')}
- ${locales('inspector_color_confirm')}
-
-
- `,
- enterKey: this.confirm.bind(this)
- })
-
- DOM.get(this.modal.container, '.color-confirm')[0].addEventListener('click', this.confirm.bind(this))
- DOM.get(this.modal.container, '.color-apply')[0].addEventListener('click', this.apply.bind(this))
-
- this.rgb.on('change', (e)=>{
- e.stopPropagation = true
- })
- // this.rgb.on('dragend', (e)=>{
- // this.value = chroma(this.rgb.value).hex()
- // this.trigger('change')
- // })
-
- this.opened = 0
- this.label = DOM.get(this.modal.container, '.title')[0]
-
- }
-
- open() {
-
- this.label.innerHTML = this.name
- this.modal.open()
- resize.check(this.rgb.container)
- this.opened = 1
-
- }
-
- close() {
-
- this.modal.close()
- this.setName()
- this.opened = 0
-
- }
-
- apply() {
-
- this.value = chroma(this.rgb.value).hex()
- this.trigger('change')
-
- }
-
- confirm() {
-
- this.value = chroma(this.rgb.value).hex()
- this.trigger('change')
- this.close()
-
- }
-
- isVisible() {
-
- return true
-
- }
-
- setName(n = '') {
-
- this.name = n
-
- }
-
- setValue(v) {
-
- if (v === 'transparent') v = '#00000000'
-
- this.rgb.setValue(chroma(v).rgba())
-
- }
-
-}
-
-module.exports = ColorPicker
diff --git a/src/client/ui/ui-colorpicker.mjs b/src/client/ui/ui-colorpicker.mjs
new file mode 100644
index 00000000..2b6df433
--- /dev/null
+++ b/src/client/ui/ui-colorpicker.mjs
@@ -0,0 +1,119 @@
+import html from 'nanohtml'
+import chroma from 'chroma-js'
+import UiWidget from './ui-widget.mjs'
+import Rgb from '../widgets/pads/rgb.mjs'
+import * as resize from '../events/resize.mjs'
+
+
+class ColorPicker extends UiWidget {
+
+ constructor() {
+
+ super({})
+
+ this.name = ''
+ this.value = ''
+
+ this.rgb = new Rgb({props: {
+ ...Rgb.defaults()._props(),
+ type: 'rgb',
+ width: 'auto',
+ height: 'auto',
+ alphaStroke: 0,
+ snap: true,
+ alpha: true
+ }, parent: this, meta: {not_editable: true}})
+
+ this.container = html`
+
+ ${this.rgb.container}
+
+ `
+
+ this.rgb.on('value-changed', (e)=>{
+ e.stopPropagation = true
+ this.value = chroma(this.rgb.value).hex()
+ this.trigger('change', {preventHistory: true})
+ })
+
+ var dragEndCb = (e)=>{
+ this.value = chroma(this.rgb.value).hex()
+ this.trigger('change')
+ }
+ this.rgb.pad.on('dragend', dragEndCb)
+ this.rgb.hue.on('dragend', dragEndCb)
+ this.rgb.alpha.on('dragend', dragEndCb)
+
+
+ this.opened = 0
+
+ this.escKeyHandler = ((e)=>{
+ if (e.key == 'Escape') this.close()
+ }).bind(this)
+
+ this.enterKeyHandler = ((e)=>{
+ if (e.key == 'Enter') this.confirm()
+ }).bind(this)
+
+ }
+
+ open() {
+
+ this.parentNode.appendChild(this.container)
+ resize.check(this.rgb.container)
+ this.opened = 1
+
+ document.addEventListener('keydown', this.escKeyHandler)
+ document.addEventListener('keydown', this.enterKeyHandler)
+ }
+
+ close() {
+
+ if (this.parentNode && this.parentNode.contains(this.container)) {
+ this.parentNode.removeChild(this.container)
+ }
+ this.setName()
+ this.opened = 0
+
+ document.removeEventListener('keydown', this.escKeyHandler)
+ document.removeEventListener('keydown', this.enterKeyHandler)
+ }
+
+ confirm() {
+
+ this.value = chroma(this.rgb.getValue(true)).css('rgba')
+ this.trigger('change')
+ this.close()
+
+ }
+
+ isVisible() {
+
+ return true
+
+ }
+
+ setName(n = '') {
+
+ this.name = n
+
+ }
+
+ setValue(v) {
+
+ if (v === 'transparent') v = '#00000000'
+
+ this.rgb.setValue(chroma(v).rgba())
+
+ }
+
+ setParent(node) {
+
+ if (this.opened && node !== this.parentNode) this.close()
+ this.parentNode = node
+
+ }
+
+}
+
+export default ColorPicker
diff --git a/src/client/ui/ui-console.js b/src/client/ui/ui-console.mjs
similarity index 65%
rename from src/client/ui/ui-console.js
rename to src/client/ui/ui-console.mjs
index ccce4742..5c960158 100644
--- a/src/client/ui/ui-console.js
+++ b/src/client/ui/ui-console.mjs
@@ -1,10 +1,12 @@
-var UiSidePanel = require('./ui-sidepanel'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- locales = require('../locales'),
- {icon} = require('./utils'),
- Script = require('../widgets/scripts/script'),
- widgetManager = require('../managers/widgets')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import UiSidePanel from './ui-sidepanel.mjs'
+import locales from '../locales/index.mjs'
+import {icon} from './utils.mjs'
+import Script from '../widgets/scripts/script.mjs'
+import Widget from '../widgets/common/widget.mjs'
+import widgetManager from '../managers/widgets.mjs'
+import {DOM, ENV, READ_ONLY} from '../globals.mjs'
class UiConsole extends UiSidePanel {
@@ -15,7 +17,7 @@ class UiConsole extends UiSidePanel {
this.header = DOM.get(this.container, 'osc-panel-header')[0]
this.header.appendChild(html``)
- this.messages = this.content.appendChild(html` `)
+ this.messages = this.content.appendChild(html` `)
this.inputWrapper = this.content.appendChild(html``)
this.input = this.inputWrapper.appendChild(html``)
@@ -27,7 +29,7 @@ class UiConsole extends UiSidePanel {
})
this.length = 0
- this.maxLength = 200
+ this.maxLength = ENV.consolelength || 300
this.history = ['']
this.cursor = 0
@@ -37,30 +39,40 @@ class UiConsole extends UiSidePanel {
console._log = console.log
console.log = function(message){
- _this.log('log', message)
+ for (let arg of arguments) {
+ _this.log('log', arg)
+ }
console._log(...arguments)
}
console._error = console.error
console.error = function(message){
- _this.log('error', message)
+ for (let arg of arguments) {
+ _this.log('error', arg)
+ }
console._error(...arguments)
}
+ console._clear = console.clear
+ console.clear = function(){
+ _this.clear()
+ console._clear()
+ }
- this.script = new Script({props:{
- id: 'CONSOLE',
- script: 'return eval(value)',
- event: 'value'
- }, parent: widgetManager})
- this.script._not_editable = true
- this.script.hash = 'CONSOLE'
+ this.widget = new Widget({props: {id: 'CONSOLE'}, parent: widgetManager, meta: {not_editable: true}})
+ this.script = new Script({
+ widget: this.widget,
+ property: '',
+ code: 'var navigator; return eval(input_code)',
+ context: {input_code: ''}
+ })
+ this.widget.hash = 'CONSOLE'
this.input.addEventListener('keydown', (event)=>{
- if (event.keyCode === 13 && !event.shiftKey) {
+ if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
this.inputValidate()
- } else if (event.keyCode === 38) {
+ } else if (event.key == 'ArrowUp') {
if (this.cursor < this.history.length - 1) {
if (this.input.value.substr(0, this.input.selectionStart).split('\n').length !== 1) return
@@ -69,7 +81,7 @@ class UiConsole extends UiSidePanel {
this.input.value = this.history[this.cursor]
event.preventDefault()
}
- } else if (event.keyCode === 40) {
+ } else if (event.key == 'ArrowDown') {
if (this.cursor > 0) {
var nLines = this.input.value.split('\n').length
if (this.input.value.substr(0, this.input.selectionStart).split('\n').length !== nLines) return
@@ -78,7 +90,7 @@ class UiConsole extends UiSidePanel {
this.input.value = this.history[this.cursor]
event.preventDefault()
}
- } else if (event.keyCode === 9) {
+ } else if (event.key == 'DOM_VK_TAB' && this.input.value !== '') {
var cur = this.input.selectionStart,
val = this.input.value
this.input.value = val.slice(0, cur) + ' ' + val.slice(cur)
@@ -93,7 +105,13 @@ class UiConsole extends UiSidePanel {
this.inputSize()
})
- this.enable()
+ this.messages.addEventListener('keydown', (event)=>{
+ if (event.key == 'Escape') {
+ this.messages.blur()
+ }
+ })
+
+ if (!READ_ONLY) this.enable()
}
@@ -107,16 +125,17 @@ class UiConsole extends UiSidePanel {
if (this.input.value == '') return
this.log('input', `${this.input.value}`)
- var returnValue = this.script.setValue(this.input.value, {sync: true, send: true})
+
+ var returnValue = this.script.run({input_code: this.input.value}, {sync: true, send: true})
if (returnValue === undefined) {
this.log('output undefined', 'undefined')
} else {
this.log('output value', returnValue)
}
- if (this.input.value !== this.history[this.cursor] && this.input.value !== this.history[1]) {
+ if (this.input.value !== this.history[1]) {
this.history.splice(1, 0, this.input.value)
- if (this.history.length > 10) this.history.pop()
+ if (this.history.length > 50) this.history.pop()
}
this.input.value = ''
@@ -124,14 +143,14 @@ class UiConsole extends UiSidePanel {
}
- log(type, message, html) {
-
- var node = this.messages.appendChild(html`
+ log(type, message, as_html) {
+ var msg =html`
- `)
+ `
+ var node = this.messages.appendChild(msg)
if (typeof message === 'object') {
if (!(message instanceof Error)) {
try {
@@ -142,14 +161,12 @@ class UiConsole extends UiSidePanel {
}
}
- if (html) {
+ if (as_html) {
node.innerHTML = message
} else {
node.textContent = message
}
- if (type !== 'error' && node.textContent.match(/error/i)) node.classList.add('error')
-
node.scrollIntoView()
if (++this.length > this.maxLength) this.purge()
@@ -177,4 +194,4 @@ class UiConsole extends UiSidePanel {
}
-module.exports = new UiConsole({selector: '#osc-console', minSize: 40, size: 200, minimized: true})
+export default new UiConsole({selector: '#osc-console', minSize: 40, size: 200, minimized: true})
diff --git a/src/client/ui/ui-dragresize.js b/src/client/ui/ui-dragresize.mjs
similarity index 54%
rename from src/client/ui/ui-dragresize.js
rename to src/client/ui/ui-dragresize.mjs
index 179f792f..f4e62c59 100644
--- a/src/client/ui/ui-dragresize.js
+++ b/src/client/ui/ui-dragresize.mjs
@@ -1,15 +1,20 @@
-var UiWidget = require('./ui-widget'),
- keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
- html = require('nanohtml'),
- Tab, Root
+import html from 'nanohtml'
+import fastdom from 'fastdom'
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import UiWidget from './ui-widget.mjs'
+import {DOM, PXSCALE, GRIDWIDTH} from '../globals.mjs'
+
+var Tab, Root, Folder
+;(async()=>{
+ Tab = (await import('../widgets/containers/tab.mjs')).default
+ Root = (await import('../widgets/containers/root.mjs')).default
+ Folder = (await import('../widgets/containers/folder.mjs')).default
+})()
class UiDragResize extends UiWidget {
constructor(options) {
- Tab = require('../widgets/containers/tab')
- Root = require('../widgets/containers/root')
-
super(options)
this.container = html`
@@ -38,11 +43,13 @@ class UiDragResize extends UiWidget {
this.handles = DOM.get(this.container, '.handle')
this.dragging = null
+ this.copying = null
+ this.shiftKey = false
this.on('draginit', (event)=>{
var node = event.firstTarget
- if (event.shiftKey || !this.handles.includes(node)) return
+ if ((event.shiftKey && !event.altKey) || !this.handles.includes(node)) return
this.initLeft = this.left
this.initTop = this.top
@@ -85,14 +92,19 @@ class UiDragResize extends UiWidget {
this.on('dragend', (event)=>{
+ if (!this.dragging) return
+
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.shiftKey = event.shiftKey
this.trigger(this.dragging.indexOf('left') > -1 ? 'move' : 'drag-resize', this)
this.dragging = null
+ this.copying = null
+ this.shiftKey = false
}, {element: this.container})
@@ -104,9 +116,18 @@ class UiDragResize extends UiWidget {
keyboardJS.withContext('editing', ()=>{
keyboardJS.bind('alt', (e)=>{
- this.handles[0].classList.add('full')
+ if (e.target.tagName !== 'TEXTAREA') this.handles[0].classList.add('full')
}, (e)=>{
- this.handles[0].classList.remove('full')
+ if (e.target && e.target.tagName !== 'TEXTAREA') this.handles[0].classList.remove('full')
+ })
+ keyboardJS.bind('alt+c', (e)=>{
+ if (e.target.tagName === 'TEXTAREA') return
+ this.copying = true
+ this.container.classList.add('copying')
+ }, (e)=>{
+ if (e.target.tagName === 'TEXTAREA') return
+ this.copying = false
+ this.container.classList.remove('copying')
})
})
@@ -127,48 +148,71 @@ class UiDragResize extends UiWidget {
this.clear()
- this.widgets = widgets.slice().filter(w=>w.getProp('visible') && !(w instanceof Tab) && !(w instanceof Root))
+ this.widgets = widgets.slice().filter(
+ w=>w.getProp('visible') &&
+ !(w instanceof Tab) &&
+ !(w instanceof Root) &&
+ !(w instanceof Folder)
+ )
if (!this.widgets.length) return
this.updateRectangle()
- this.widgets[0].parentNode.appendChild(this.container)
- this.mounted = true
+ this.initLeft = this.left
+ this.initTop = this.top
+ this.initWidth = this.width
+ this.initHeight = this.height
+ fastdom.mutate(()=>{
+ if (this.widgets.length) {
+ this.widgets[0].parentNode.appendChild(this.container)
+ this.mounted = true
+ }
+ })
}
updateRectangle() {
var widgets = this.widgets,
- widget = widgets[0]
+ widget = widgets[0],
+ layout = String(widget.parent.getProp('layout'))
var handlesVisibility = [
- widget.parent.getProp('layout') === 'default', // nw
- widget.parent.getProp('layout').match(/horizontal|default/), // e
- widget.parent.getProp('layout').match(/vertical|default/), // s
+ layout === 'default', // nw
+ layout.match(/horizontal|default/), // e
+ layout.match(/vertical|default/), // s
]
handlesVisibility.push(handlesVisibility[1] && handlesVisibility[2]) // se
- for (var i in handlesVisibility) {
- this.handles[i].style.display = handlesVisibility[i] ? '' : 'none'
- }
+ fastdom.measure(()=>{
- var 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)
+ var 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.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.cssTransform = widget.cssTransform || 'none'
- // this.cssTransformOrigin = widget.cssTransformOrigin
+ fastdom.mutate(()=>{
+
+ for (var i in handlesVisibility) {
+ this.handles[i].style.display = handlesVisibility[i] ? '' : 'none'
+ }
+
+ this.updateCss()
+
+ // this.cssTransform = widget.cssTransform || 'none'
+ // this.cssTransformOrigin = widget.cssTransformOrigin
+
+ })
+
+ })
- this.updateCss()
}
@@ -194,4 +238,4 @@ class UiDragResize extends UiWidget {
}
-module.exports = UiDragResize
+export default UiDragResize
diff --git a/src/client/ui/ui-filebrowser.js b/src/client/ui/ui-filebrowser.mjs
similarity index 87%
rename from src/client/ui/ui-filebrowser.js
rename to src/client/ui/ui-filebrowser.mjs
index e448e957..766e3194 100644
--- a/src/client/ui/ui-filebrowser.js
+++ b/src/client/ui/ui-filebrowser.mjs
@@ -1,14 +1,15 @@
-var locales = require('../locales'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- ipc = require('../ipc'),
- doubleClick = require('../events/double-click'),
- {icon} = require('./utils'),
- UiModal = require('./ui-modal'),
- keyboardJS = require('keyboardjs/dist/keyboard.min.js')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import locales from '../locales/index.mjs'
+import ipc from '../ipc/index.mjs'
+import doubleClick from '../events/double-click.mjs'
+import {icon} from './utils.mjs'
+import UiModal from './ui-modal.mjs'
+import {DOM} from '../globals.mjs'
-module.exports = function UiFilebrowser(options, callback) {
+export default function UiFilebrowser(options, callback, closeCallback) {
var save = options.save,
saveInputFocus = undefined,
@@ -40,6 +41,7 @@ module.exports = function UiFilebrowser(options, callback) {
`
var files = [],
+ root = '',
path = ''
var extRe = options.extension ? new RegExp('.*\\.' + options.extension + '$') : /.*/
@@ -75,10 +77,10 @@ module.exports = function UiFilebrowser(options, callback) {
if (files.some(x=>x.name===saveInput.value)) {
if (!confirm(locales('remotesave_overwrite'))) return
}
- callback([path, saveInput.value])
+ callback([path, saveInput.value], root)
popup.close()
} else {
- callback([path, choice ? choice.value : ''])
+ callback([path, choice ? choice.value : ''], root)
popup.close()
}
}
@@ -95,7 +97,7 @@ module.exports = function UiFilebrowser(options, callback) {
function keyDownHandler(e){
- if (e.keyCode === 13) {
+ if (e.key == 'Enter') {
if (save) {
document.addEventListener('keyup', keyUpHandler)
} else {
@@ -103,7 +105,7 @@ module.exports = function UiFilebrowser(options, callback) {
}
} else if (e.target === saveInput) {
return
- } else if (e.keyCode === 8) {
+ } else if (e.key == 'DOM_VK_BACK_SPACE' || e.keyCode === 8) {
list.childNodes[0].firstElementChild.checked = true
submit()
} else if (e.key.length === 1) {
@@ -131,7 +133,7 @@ module.exports = function UiFilebrowser(options, callback) {
}
function keyUpHandler(e){
- if (e.keyCode === 13) {
+ if (e.key == 'Enter') {
setTimeout(submit, 100)
document.removeEventListener('keyup', keyUpHandler)
}
@@ -141,12 +143,12 @@ module.exports = function UiFilebrowser(options, callback) {
document.addEventListener('keydown', keyDownHandler)
ipc.on('listDir', (data)=>{
-
- ariane.textContent = path = data.path
+ path = data.path
+ root = data.root
+ ariane.textContent = root ? path.replace(root, '/') : 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()
@@ -197,6 +199,7 @@ module.exports = function UiFilebrowser(options, callback) {
document.removeEventListener('keydown', keyDownHandler)
document.removeEventListener('keyup', keyUpHandler)
keyboardJS.setContext(previousKbContext)
+ if (closeCallback) closeCallback(path)
})
browser.appendChild(ariane)
diff --git a/src/client/ui/ui-fileupload.js b/src/client/ui/ui-fileupload.mjs
similarity index 54%
rename from src/client/ui/ui-fileupload.js
rename to src/client/ui/ui-fileupload.mjs
index 126dd343..818f5c06 100644
--- a/src/client/ui/ui-fileupload.js
+++ b/src/client/ui/ui-fileupload.mjs
@@ -1,16 +1,20 @@
-var locales = require('../locales'),
- uiLoading = require('./ui-loading'),
- html = require('nanohtml'),
- SINGLETON = null,
+import html from 'nanohtml'
+import locales from '../locales/index.mjs'
+import uiLoading from './ui-loading.mjs'
+import {DOM} from '../globals.mjs'
+
+var SINGLETON = null,
CONTAINER = null
-module.exports = function uiFileUpload(types, ok, error) {
+export default function uiFileUpload(types, ok, error) {
if (!CONTAINER) CONTAINER = DOM.get('osc-modal-container')[0]
if (SINGLETON) CONTAINER.removeChild(SINGLETON)
- SINGLETON = html``
+ SINGLETON = html``
+
+ if (types) SINGLETON.accept = types
CONTAINER.appendChild(SINGLETON)
@@ -22,9 +26,9 @@ module.exports = function uiFileUpload(types, ok, error) {
uiLoading(locales('loading_upload'))
- reader.onerror = reader.onabort = function() {
- loader.close()
- error()
+ reader.onerror = reader.onabort = function(e) {
+ uiLoading(false)
+ error(e)
}
reader.onload = function(e) {
diff --git a/src/client/ui/ui-inspector-field.js b/src/client/ui/ui-inspector-field.mjs
similarity index 69%
rename from src/client/ui/ui-inspector-field.js
rename to src/client/ui/ui-inspector-field.mjs
index e7cd7f40..ceff8e21 100644
--- a/src/client/ui/ui-inspector-field.js
+++ b/src/client/ui/ui-inspector-field.mjs
@@ -1,10 +1,9 @@
-var UiWidget = require('./ui-widget'),
- {categories} = require('../widgets/'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- {icon} = require('../ui/utils'),
- chroma = require('chroma-js')
-
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import chroma from 'chroma-js'
+import UiWidget from './ui-widget.mjs'
+import {categories} from '../widgets/index.mjs'
+import {icon} from '../ui/utils.mjs'
class UiInspectorField extends UiWidget {
@@ -16,9 +15,8 @@ class UiInspectorField extends UiWidget {
this.widget = options.widget
this.value = options.value
this.default = options.default
- this.tabIndex = options.tabIndex
- this.container = html` `
+ this.container = html` `
this.label = this.container.appendChild(html``)
if (this.name === 'type' || this.name === 'widgetType') this.createTypeSelect()
@@ -31,14 +29,14 @@ class UiInspectorField extends UiWidget {
if (this.widget.props.type == 'tab' || this.widget.props.type == 'root') {
this.container.appendChild(html`
-
+
`)
return
}
this.createInput()
- var select = html``
+ var select = html``
for (let cname in categories) {
@@ -65,7 +63,9 @@ class UiInspectorField extends UiWidget {
JSON.stringify(this.value, null, ' ').replace(/\n\s\s\s\s/g, ' ').replace(/\n\s\s(\}|\])/g, ' $1') : this.value
- var input = html``
+ let input = html``
+
+ if (this.name === 'id' && this.widget.props.type === 'root') input.disabled = true
if (this.default.value === 'auto' && stringValue === 'auto') {
input.placeholder = stringValue
@@ -79,14 +79,16 @@ class UiInspectorField extends UiWidget {
if (this.default.choices) {
let wrapper = html` `,
- select = wrapper.appendChild(html``)
+ select = wrapper.appendChild(html``)
for (let choice of this.default.choices) {
select.appendChild(html``)
}
this.container.appendChild(wrapper)
- } else if (this.default.type.includes('boolean')) {
+ }
+
+ if (this.default.type.includes('boolean')) {
let toggle = html`
@@ -96,7 +98,9 @@ class UiInspectorField extends UiWidget {
this.container.appendChild(toggle)
- } else if (this.name.includes('color')) {
+ }
+
+ if (this.name.includes('color')) {
let style = window.getComputedStyle(this.widget.container),
colorData = this.widget.constructor.cssVariables.find(x=>x.js === this.name),
@@ -105,10 +109,10 @@ class UiInspectorField extends UiWidget {
try {
val = chroma(style.getPropertyValue(colorData.css).trim()).hex('rgba')
} catch(e) {}
+ this.container.appendChild(html`
+
+ `)
- let picker = html` `
-
- this.container.appendChild(picker)
} else if (stringValue === 'auto' && this.widget.constructor.cssVariables.some(x=>x.js === this.name)) {
@@ -117,14 +121,17 @@ class UiInspectorField extends UiWidget {
val = style.getPropertyValue(data.css).trim()
if (data.toJs) val = data.toJs(val)
+ this.container.appendChild(html`
+ ${val}
+ `)
+
- this.container.appendChild(html`${val}`)
}
-
}
+
}
-module.exports = UiInspectorField
+export default UiInspectorField
diff --git a/src/client/ui/ui-inspector.js b/src/client/ui/ui-inspector.js
deleted file mode 100644
index 24274723..00000000
--- a/src/client/ui/ui-inspector.js
+++ /dev/null
@@ -1,319 +0,0 @@
-var UiWidget = require('./ui-widget'),
- UiInspectorField = require('./ui-inspector-field'),
- UiColorPicker = require('./ui-colorpicker'),
- UiModal = require('./ui-modal'),
- morph = require('nanomorph'),
- {defaults} = require('../widgets/'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw')
-
-
-
-
-class UiInspector extends UiWidget {
-
- constructor(options) {
-
- super(options)
-
- this.mounted = false
-
- this.expandedCategories = ['widget']
-
- this.widget = null
-
- this.container.addEventListener('fast-click', (e)=>{
-
- if (e.target.classList.contains('category-header')) {
- var name = e.target.getAttribute('data-name'),
- expandedIndex = this.expandedCategories.indexOf(name)
- e.target.parentNode.classList.toggle('expanded', expandedIndex < 0)
- if (expandedIndex > -1) {
- this.expandedCategories.splice(expandedIndex, 1)
- } else {
- this.expandedCategories.push(name)
- }
-
- }
-
- })
-
- this.colorPicker = new UiColorPicker()
- this.colorPicker.on('change', ()=>{
- var textarea = DOM.get(this.container, `textarea[name="${this.colorPicker.name}"]`)
- if (textarea) {
- textarea[0].value = this.colorPicker.value
- DOM.dispatchEvent(textarea[0], 'change')
- }
- })
-
- this.container.addEventListener('click', (e)=>{
-
- var node = e.target
-
- if (node.tagName === 'OSC-INSPECTOR-CHECKBOX') {
-
- var name = node.getAttribute('name')
-
- var textarea = DOM.get(this.container, `textarea[name="${name}"]`)
- if (textarea) {
- textarea[0].value = !node.classList.contains('on')
- DOM.dispatchEvent(textarea[0], 'change')
- }
-
- } else if (node.tagName === 'OSC-INSPECTOR-COLOR') {
-
- this.colorPicker.setName(node.getAttribute('name'))
- this.colorPicker.setValue(node.getAttribute('value'))
- this.colorPicker.open()
-
- } else if (node.tagName === 'LABEL') {
-
- this.help(node.textContent)
-
- }
-
- })
-
-
- this.container.addEventListener('change', this.onChange.bind(this))
- this.container.addEventListener('keydown', this.onKeydown.bind(this))
- this.container.addEventListener('input', this.onInput.bind(this))
-
- this.lock = false
- this.clearTimeout = null
-
- this.helpModalOpened = false
-
- }
-
- clear() {
-
- this.clearTimeout = setTimeout(()=>{
- this.widget = null
- this.container.innerHTML = ''
- this.mounted = false
- this.clearTimeout = null
- this.colorPicker.close()
- })
-
- }
-
- inspect(widgets) {
-
- if (this.clearTimeout) {
- clearTimeout(this.clearTimeout)
- this.clearTimeout = null
- }
-
- var content = html``
-
- var widget = widgets[0],
- props = defaults[widget.props.type],
- tabIndex = 1000
-
- this.widget = widget
-
- for (let categoryName in props) {
-
- if (categoryName === 'children') continue
-
- let category = html` `,
- categoryLabel = categoryName === 'class_specific' ? widget.props.type : categoryName
-
- if (widgets.length > 1 && categoryName === 'class_specific') categoryLabel = 'shared properties'
-
- category.appendChild(html`
- ${categoryLabel}${categoryName === 'widget' && widgets.length > 1 ? `s (${widgets.length})` : ''}
- `)
-
- let notEmpty
-
- for (let propName in props[categoryName]) {
-
- // skip if property is not shared between selected widgets
- if (widgets.some((w)=>{
- let shared = false
- for (let c in defaults[widget.props.type]) {
- if (defaults[w.props.type][c] && defaults[w.props.type][c].hasOwnProperty(propName)) {
- shared = true
- break
- }
- }
- return !shared
- })) continue
-
- let field = propName.includes('_separator') ?
- html`${props[categoryName][propName]}` :
- new UiInspectorField({
- parent: this,
- widget: widget,
- name: propName,
- value: widget.props[propName],
- default: defaults[widget.props.type][categoryName][propName],
- tabIndex: tabIndex++
- }).container
-
- if (field) {
- category.appendChild(field)
- notEmpty = true
- }
-
- }
-
- if (notEmpty) {
- content.appendChild(category)
- }
-
- }
-
- this.lock = true
-
- if (this.mounted) {
- morph(this.container.firstChild, content)
- } else {
- this.container.appendChild(content)
- }
-
- this.mounted = true
- this.lock = false
-
- if (this.colorPicker.opened) {
-
- var picker = DOM.get(this.container, `osc-inspector-color[name="${this.colorPicker.name}"]`)
- if (picker && picker[0]) {
- this.colorPicker.setValue(picker[0].getAttribute('value'))
- } else {
- this.colorPicker.close()
- }
-
- }
-
-
- }
-
- onChange(event) {
-
- if (this.lock) return
-
- this.lock = true
-
- var input = this.focusedInput || event.target
-
- this.focusedInput = null
-
- 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 may not be reached if an error is thrown
- // but the lock will undone at the next inspect() call
- this.lock = false
- }
-
- onKeydown(event) {
-
- if (event.target.tagName === 'TEXTAREA') {
-
- if (event.keyCode === 13 && !event.shiftKey) {
-
- event.preventDefault()
- DOM.dispatchEvent(event.target, 'change')
-
- } else if (event.keyCode === 27) {
-
- event.preventDefault()
- event.target.value = event.target.textContent
- event.target.blur()
-
- }
-
- }
-
- }
-
- onInput(event) {
-
- this.focusedInput = event.target
-
- // text autoheight
-
- this.focusedInput.setAttribute('rows',0)
- this.focusedInput.setAttribute('rows', this.focusedInput.value.split('\n').length)
-
- }
-
- help(name) {
-
- var _defaults = defaults[this.widget.getProp('type')],
- category = Object.keys(_defaults).find(x=>_defaults[x].hasOwnProperty(name)),
- defaultValue = _defaults[category][name],
- dynamic = this.widget.isDynamicProp(name),
- htmlHelp = Array.isArray(defaultValue.help) ? defaultValue.help.join('
').replace(/
-/g, '-') : defaultValue.help
-
- htmlHelp = htmlHelp ? html`${raw(htmlHelp.replace(/`([^`]*)`/g, '$1'))}
` : ''
-
- DOM.each(htmlHelp, 'a', (el)=>{
- el.target = '_blank'
- })
-
- var computedValue = this.widget.getProp(name)
-
- if (typeof computedValue === 'string') {
- try {
- computedValue = JSON.stringify(JSON.parse(computedValue), null, ' ')
- } catch(e) {}
- } else {
- computedValue = JSON.stringify(computedValue, null, ' ')
- }
-
- var modal = new UiModal({closable: true, title: html`${name}`, html: true, content: html`
-
-
-
- Type: ${defaultValue.type}
- Default: ${JSON.stringify(defaultValue.value)}
- ${
- defaultValue.choices ? html`
- Choices: ${raw(defaultValue.choices.map(x=>'' + x + '').join(', '))}
- ` :''
- }
- Dynamic: ${dynamic ? 'true' : 'false'}
-
-
- ${htmlHelp}
-
-
- Computed value: ${computedValue || 'empty'}
-
-
- `})
-
-
- this.helpModalOpened = true
- modal.on('close', ()=>{
- this.helpModalOpened = false
- })
-
- }
-
-}
-
-module.exports = UiInspector
diff --git a/src/client/ui/ui-inspector.mjs b/src/client/ui/ui-inspector.mjs
new file mode 100644
index 00000000..05a71af2
--- /dev/null
+++ b/src/client/ui/ui-inspector.mjs
@@ -0,0 +1,434 @@
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import fastdom from 'fastdom'
+import morph from 'nanomorph'
+import UiWidget from './ui-widget.mjs'
+import UiInspectorField from './ui-inspector-field.mjs'
+import UiColorPicker from './ui-colorpicker.mjs'
+import UiModal from './ui-modal.mjs'
+import {defaults} from '../widgets/index.mjs'
+import {icon} from './utils.mjs'
+import zoom from './zoom.mjs'
+import locales from '../locales/index.mjs'
+import getCodeEditor from './ui-code-editor.mjs'
+import {DOM, JSON5} from '../globals.mjs'
+
+var editor
+;(async()=>{
+ editor = (await import('../editor/index.mjs')).default
+})()
+
+
+var codeEditorModKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+class UiInspector extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.mounted = false
+
+ this.expandedCategories = ['widget']
+
+ this.widget = null
+
+ this.toolbar = this.container.appendChild(html`
+
+ `)
+ this.toolbarBtns = {}
+ DOM.each(this.toolbar, '.btn', (item)=>{
+ var action = item.getAttribute('data-action')
+ if (action) {
+ if (action !== 'selected-id') item.setAttribute('title', locales('inspector_' + action.replace('-', '_')))
+ this.toolbarBtns[action] = item
+ }
+ })
+ zoom.on('local-zoom-changed',()=>{
+ this.toolbarBtns['zoom-out'].classList.toggle('active', zoom.localZoom < 1)
+ this.toolbarBtns['zoom-in'].classList.toggle('active', zoom.localZoom > 1)
+ })
+
+
+ this.content = this.container.appendChild(html``)
+
+ this.container.addEventListener('fast-click', (e)=>{
+
+ if (e.target.classList.contains('category-header')) {
+ var name = e.target.getAttribute('data-name')
+
+ if (e.detail.altKey) {
+ DOM.each(this.container, 'osc-inspector-category.expanded', (item)=>{
+ let iname = item.firstChild.getAttribute('data-name'),
+ index = this.expandedCategories.indexOf(iname)
+ if (iname !== name) {
+ if (index > -1) this.expandedCategories.splice(index, 1)
+ item.classList.remove('expanded')
+ }
+ })
+ }
+ var expandedIndex = this.expandedCategories.indexOf(name)
+ e.target.parentNode.classList.toggle('expanded', expandedIndex < 0)
+ if (expandedIndex > -1) {
+ this.expandedCategories.splice(expandedIndex, 1)
+ } else {
+ this.expandedCategories.push(name)
+ }
+
+ } else if (e.target.classList.contains('toolbar-btn')) {
+
+ switch (e.target.getAttribute('data-action')) {
+ case 'zoom-out':
+ zoom.setLocalZoom(zoom.localZoom - 0.1)
+ break
+ case 'zoom-reset':
+ zoom.setLocalZoom(1)
+ break
+ case 'zoom-in':
+ zoom.setLocalZoom(zoom.localZoom + 0.1)
+ break
+ case 'reset-selection':
+ editor.unselect()
+ break
+ case 'toggle-grid':
+ editor.toggleGrid()
+ break
+ }
+
+ }
+
+ })
+ this.parentContainer = DOM.get('osc-panel-container.right')[0]
+
+ this.colorPicker = new UiColorPicker()
+ this.colorPicker.on('change', (event)=>{
+ var textarea = DOM.get(this.container, `textarea[name="${this.colorPicker.name}"]`)
+ if (textarea) {
+ textarea[0].value = this.colorPicker.value
+ DOM.dispatchEvent(textarea[0], 'change', event)
+ }
+ })
+
+ this.container.addEventListener('click', (e)=>{
+
+ var node = e.target
+
+ if (node.tagName === 'OSC-INSPECTOR-CHECKBOX') {
+
+ let name = node.getAttribute('name'),
+ textarea = DOM.get(this.container, `textarea[name="${name}"]`)
+
+ if (textarea) {
+ fastdom.mutate(()=>{
+ textarea[0].value = !node.classList.contains('on')
+ DOM.dispatchEvent(textarea[0], 'change')
+ })
+ }
+
+ } else if (node.tagName === 'OSC-INSPECTOR-COLOR') {
+
+ let name = node.getAttribute('name')
+
+ if (this.colorPicker.name === name) {
+ this.colorPicker.close()
+ } else {
+ this.colorPicker.setParent(node.parentNode)
+ this.colorPicker.setName(name)
+ this.colorPicker.setValue(node.getAttribute('value'))
+ this.colorPicker.open()
+ }
+
+ } else if (node.tagName === 'LABEL') {
+
+ this.help(node.textContent)
+
+ }
+
+ })
+
+
+ this.container.addEventListener('change', this.onChange.bind(this))
+ this.container.addEventListener('keydown', this.onKeydown.bind(this))
+ this.container.addEventListener('input', this.onInput.bind(this))
+
+ this.lock = false
+ this.clearTimeout = null
+
+ this.helpModalOpened = false
+
+ }
+
+ clear() {
+
+ this.clearTimeout = setTimeout(()=>{
+ this.widget = null
+ this.content.innerHTML = ''
+ this.toolbarBtns['selected-id'].firstChild.innerHTML = ''
+ this.mounted = false
+ this.clearTimeout = null
+ this.colorPicker.close()
+ this.parentContainer.classList.remove('editor-breakout')
+ })
+
+ }
+
+ inspect(widgets) {
+
+ if (this.clearTimeout) {
+ clearTimeout(this.clearTimeout)
+ this.clearTimeout = null
+ }
+
+
+ var widget = widgets[0],
+ lock = widgets.some(w=>w.getProp('lock')),
+ props = defaults[widget.props.type],
+ codeEditorFields = []
+
+ this.widget = widget
+
+ var content = html``
+
+ for (let categoryName in props) {
+
+ if (categoryName === 'children') continue
+
+ let category = html` `,
+ categoryLabel = categoryName === 'class_specific' ? widget.props.type : categoryName
+
+ if (widgets.length > 1 && categoryName === 'class_specific') categoryLabel = 'shared properties'
+
+ category.appendChild(html`
+ ${categoryLabel}${categoryName === 'widget' && widgets.length > 1 ? `s (${widgets.length})` : ''}
+ `)
+
+ let notEmpty
+ let field
+
+ for (let propName in props[categoryName]) {
+
+ // skip if property is not shared between selected widgets
+ if (widgets.some((w)=>{
+ let shared = false
+ for (let c in defaults[widget.props.type]) {
+ if (defaults[w.props.type][c] && defaults[w.props.type][c].hasOwnProperty(propName)) {
+ shared = true
+ break
+ }
+ }
+ return !shared
+ })) continue
+
+ if (propName.includes('_separator')) {
+ if (field) field.classList.add('last-child')
+ field = html`${props[categoryName][propName]}`
+ } else {
+ var def = defaults[widget.props.type][categoryName][propName]
+ if (field && def.editor) field.classList.add('last-child')
+ var first = !field || field.classList.contains('separator')
+ field = new UiInspectorField({
+ parent: this,
+ widget: widget,
+ name: propName,
+ value: widget.props[propName],
+ default: def,
+ }).container
+ if (first) field.classList.add('first-child')
+
+ if (def.editor) {
+ codeEditorFields.push([propName, def.editor, def.syntaxChecker, widget])
+ field.classList.add('has-editor')
+ }
+ }
+
+ if (field) {
+ category.appendChild(field)
+ notEmpty = true
+ }
+
+ }
+
+ if (notEmpty) {
+ content.appendChild(category)
+ }
+
+ }
+
+ this.lock = true
+
+ morph(this.content, content)
+
+ this.toolbarBtns['selected-id'].firstChild.innerHTML = widgets.map(x=>x.getProp('id')).join(', ')
+
+ if (codeEditorFields.length) {
+ let fields = DOM.get(this.container, '.has-editor')
+ for (var i in codeEditorFields) {
+ let [propName, language, syntax, widget] = codeEditorFields[i]
+ let codeEditor = getCodeEditor(this, propName, language, syntax)
+ codeEditor.bind(widget, fields[i])
+ }
+ }
+
+ this.mounted = true
+ this.lock = false
+
+ if (this.colorPicker.opened) {
+
+ var picker = DOM.get(this.container, `osc-inspector-color[name="${this.colorPicker.name}"]`)
+ if (picker && picker[0]) {
+ this.colorPicker.setValue(picker[0].getAttribute('value'))
+ this.colorPicker.open()
+ } else {
+ this.colorPicker.close()
+ }
+
+ }
+
+
+ }
+
+ onChange(event) {
+
+ if (this.lock) return
+
+ this.lock = true
+
+ var input = this.focusedInput || event.target
+
+ this.focusedInput = null
+
+ input.blur()
+
+ if (document.activeElement === input._ace_input) input._ace_input.blur()
+
+ var value = input.value,
+ str = value.replace(/[‟“”]/g, '"').replace(/[‘’]/g, '\''), // convert invalid quote characters
+ v
+
+ try {
+ v = JSON5.parse(str)
+ } catch(err) {
+ v = str
+ }
+
+ this.trigger('update', {
+ propName: input.name,
+ value: v,
+ preventHistory: event && event.detail && event.detail.preventHistory
+ })
+
+ // this may not be reached if an error is thrown
+ // but the lock will undone at the next inspect() call
+ this.lock = false
+ }
+
+ onKeydown(event) {
+
+ if (event.target.tagName === 'TEXTAREA') {
+
+ if (event.key == 'Enter' &&
+ ((!event.shiftKey && !event.target._ace) ||
+ (event[codeEditorModKey] && event.target._ace))
+ ) {
+
+ event.preventDefault()
+ DOM.dispatchEvent(event.target, 'change')
+
+ } else if (event.key == 'Escape') {
+
+ event.preventDefault()
+ event.target.value = event.target.textContent
+ event.target.blur()
+
+ }
+
+ } else if ((event.key == 'Enter' || event.key == ' ') && event.target.classList.contains('category-header')) {
+
+ event.preventDefault()
+ DOM.dispatchEvent(event.target, 'fast-click', {})
+
+ }
+
+ }
+
+ onInput(event) {
+
+ if (event.target._ace) return
+
+ this.focusedInput = event.target
+
+ // text autoheight
+ this.focusedInput.setAttribute('rows',0)
+ this.focusedInput.setAttribute('rows', this.focusedInput.value.split('\n').length)
+
+ }
+
+ help(name) {
+
+ var _defaults = defaults[this.widget.getProp('type')],
+ category = Object.keys(_defaults).find(x=>_defaults[x].hasOwnProperty(name)),
+ defaultValue = _defaults[category][name],
+ dynamic = this.widget.isDynamicProp(name),
+ htmlHelp = Array.isArray(defaultValue.help) ? defaultValue.help.join('
').replace(/
-/g, '-') : defaultValue.help
+
+ htmlHelp = htmlHelp ? html`${raw(htmlHelp.replace(/`([^`]*)`/g, '$1'))}
` : ''
+
+ DOM.each(htmlHelp, 'a', (el)=>{
+ el.target = '_blank'
+ })
+
+ var computedValue = this.widget.getProp(name)
+
+ if (typeof computedValue === 'string') {
+ try {
+ computedValue = JSON.stringify(JSON.parse(computedValue), null, ' ')
+ } catch(e) {}
+ } else {
+ computedValue = JSON.stringify(computedValue, null, ' ')
+ }
+
+ var modal = new UiModal({closable: true, title: html`${name}`, html: true, content: html`
+
+
+
+ Type: ${defaultValue.type}
+ Default: ${JSON.stringify(defaultValue.value)}
+ ${
+ defaultValue.choices ? html`
+ Choices: ${raw(defaultValue.choices.map(x=>'' + x + '').join(', '))}
+ ` :''
+ }
+ Dynamic: ${dynamic ? 'true' : 'false'}
+
+
+ ${htmlHelp}
+
+
+ Computed property: ${computedValue || 'empty'}
+
+ ${name === 'value' ? raw(`
+
+ Current value: ${JSON.stringify(this.widget.getValue())}
+
+ `): ''}
+
+ `})
+
+
+ this.helpModalOpened = true
+ modal.on('close', ()=>{
+ this.helpModalOpened = false
+ })
+
+ }
+
+}
+
+export default UiInspector
diff --git a/src/client/ui/ui-keyboard.mjs b/src/client/ui/ui-keyboard.mjs
new file mode 100644
index 00000000..ad4767d3
--- /dev/null
+++ b/src/client/ui/ui-keyboard.mjs
@@ -0,0 +1,481 @@
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import morph from 'nanomorph'
+import UiWidget from './ui-widget.mjs'
+import {icon} from './utils.mjs'
+import locales from '../locales/index.mjs'
+import doubleClick from '../events/double-click.mjs'
+import {DOM, VIRTUAL_KEYBOARD} from '../globals.mjs'
+
+var layout = locales('keyboard_layout')
+
+const numericLayout = [
+ '{sep} + 7 8 9',
+ '{sep} - 4 5 6',
+ '{sep} * 1 2 3',
+ '{sep} / {up} 0 .',
+ '{sep} {left} {down} {right} {enter}'
+]
+const keysDisplay = {
+ '{esc}': locales('keyboard_escape'),
+ '{bksp}': icon('delete-left'),
+ '{enter}': icon('arrow-turn-down.rotate-90'),
+ '{lock}': icon('arrow-up-from-bracket'),
+ '{shift}': icon('arrow-up'),
+ '{tab}': icon('arrow-right-arrow-left'),
+ '{space}': ' ',
+ '{left}': icon('arrow-left'),
+ '{right}': icon('arrow-right'),
+ '{up}': icon('arrow-up'),
+ '{down}': icon('arrow-down'),
+
+}
+
+class OscKeybard extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.keys = {}
+ this.pressedKeys = {}
+ this.repeatKeys = {}
+ this.lock = false
+ this.shift = false
+ this.input = null
+ this.value = null
+ this.visible = false
+ this.selectionInit = 0
+
+ this.display = html``
+ this.container.appendChild(html`${this.display}`)
+
+ for (var k in layout) {
+ layout[k] = layout[k].map((r, i)=>(r + ' ' + (numericLayout[i]||'')).trim().split(' '))
+ }
+
+ var keyId = 0
+
+ for (var i = 0; i < layout.default.length; i++) {
+ var rowData = layout.default[i],
+ row = html``
+
+ for (var j = 0; j < rowData.length; j++) {
+ var keyData = rowData[j],
+ shiftData = layout.shift[i][j],
+ key = html`
+
+ ${raw(keysDisplay[keyData] || keyData)}
+ ${raw(keysDisplay[shiftData] || shiftData)}
+ `
+
+ keyId++
+ this.keys[keyId] = key
+ key.appendChild = keysDisplay[keyData] || keyData
+
+ key.classList.add(keyData.replace('{', '').replace('}', ''))
+
+ key.setAttribute('data-id', keyId)
+ key.setAttribute('data-key', keyData)
+ key.setAttribute('data-shift', shiftData)
+
+ row.appendChild(key)
+ }
+ this.container.appendChild(row)
+ }
+
+ this.container.addEventListener('mousedown', (e)=>{
+ // prevent keyboard from stealing focus from input
+ e.preventDefault()
+
+ }, {capture: true})
+
+
+ this.on('draginit', (e)=>{
+
+ if (this.pressedKeys[e.pointerId]) return
+
+ if (e.target.tagName === 'KEY') {
+
+ var keyId = e.target.getAttribute('data-id')
+
+ if (keyId === null) return
+
+ var key = this.keys[keyId]
+
+ if (key.getAttribute('data-key') === '{lock}') {
+ this.lock = !this.lock
+ key.classList.toggle('active', this.lock)
+ } else {
+ key.classList.add('active')
+ this.pressedKeys[e.pointerId] = key
+ }
+
+ this.checkShift()
+
+ this.repeatKeys[e.pointerId] = [
+ setTimeout(()=>{
+ this.repeatKeys[e.pointerId][1] = setInterval(()=>{
+ this.keyDown(key.getAttribute(this.shift !== this.lock ? 'data-shift' : 'data-key'))
+ }, 50)
+ },800)
+ ]
+
+ this.keyDown(key.getAttribute(this.shift !== this.lock ? 'data-shift' : 'data-key'))
+
+ } else if (e.target.tagName === 'CHAR') {
+
+ // move cursor
+ if (this.display.contains(e.target) && e.target !== this.display) {
+ var pos = DOM.index(e.target)
+ // adjust cursor depening on where we clicked on the letter
+ if (e.offsetX - DOM.offset(e.target).left >= e.target.offsetWidth / 2)
+ pos += 1
+
+ this.input.selectionStart = pos
+ this.selectionInit = pos
+ if (!e.shiftKey) {
+ this.input.selectionEnd = pos
+ }
+ this.clickHandler()
+ }
+
+ }
+
+
+ }, {element: this.container, multitouch: true})
+
+ doubleClick(this.display, ()=>{
+ this.input.selectionStart = 0
+ this.input.selectionEnd = this.input.value.length
+ this.clickHandler()
+ })
+
+ this.on('drag', (e)=>{
+
+ if (e.target.tagName === 'CHAR') {
+
+ // move cursor
+ if (this.display.contains(e.target) && e.target !== this.display) {
+ var pos = DOM.index(e.target)
+ // adjust cursor depening on where we clicked on the letter
+ if (e.offsetX - DOM.offset(e.target).left >= e.target.offsetWidth / 2)
+ pos += 1
+
+ if (pos < this.selectionInit) {
+ this.input.selectionStart = pos
+ } else {
+ this.input.selectionEnd = pos
+ }
+
+ this.clickHandler()
+ }
+
+ }
+
+ }, {element: this.container, multitouch: true})
+
+ this.on('dragend', (e)=>{
+
+ if (!this.pressedKeys[e.pointerId]) return
+
+ var key = this.pressedKeys[e.pointerId],
+ keyData = key.getAttribute('data-key')
+
+ key.classList.remove('active')
+
+ if (keyData === '{lock}') return
+
+ delete this.pressedKeys[e.pointerId]
+
+ clearTimeout(this.repeatKeys[e.pointerId][0])
+ clearInterval(this.repeatKeys[e.pointerId][1])
+
+ this.checkShift()
+
+ }, {element: this.container, multitouch: true})
+
+
+ document.addEventListener('focus', (e)=>{
+ if (!VIRTUAL_KEYBOARD) return
+ // show keyboard when entering input focus
+ if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
+ setTimeout(()=>{
+ this.show(e.target)
+ })
+ }
+ }, {capture: true})
+
+
+ this.boundSelectHandler = this.selectHandler.bind(this)
+ this.boundBlurHandler = this.blurHandler.bind(this)
+ this.boundKeydownHandler = this.keydownHandler.bind(this)
+ this.boundChangeHandler = this.changeHandler.bind(this)
+ this.boundInputHandler = this.inputHandler.bind(this)
+ this.boundClickHandler = this.clickHandler.bind(this)
+
+ }
+
+ keyDown(key) {
+
+ if (!this.input) return
+
+ var startPos = this.input.selectionStart,
+ endPos = this.input.selectionEnd,
+ editLength, str
+
+ switch (key) {
+ case '{lock}':
+ case '{shift}':
+ return
+ case '{esc}':
+ this.input.value = this.value
+ this.input.blur()
+ return
+ case '{enter}':
+ if (this.shift) {
+ str = '\n'
+ editLength = 1
+ break
+ } else {
+ DOM.dispatchEvent(this.input, 'change')
+ return
+ }
+ case '{bksp}':
+ if (startPos === endPos && startPos === 0) break
+ this.input.value = this.input.value.substring(0, startPos - 1)
+ + this.input.value.substring(endPos, this.input.value.length)
+ editLength = -1
+ break
+ case '{tab}':
+ str = ' '
+ break
+ case '{space}':
+ str = ' '
+ break
+ case '{left}':
+ this.input.selectionStart = this.input.selectionEnd = Math.max(this.input.selectionStart - 1, 0)
+ this.keydownHandler()
+ return
+ case '{right}':
+ this.input.selectionStart = this.input.selectionEnd = this.input.selectionStart + 1
+ this.keydownHandler()
+ return
+ case '{up}':
+ case '{down}':
+ if (this.input.value.includes('\n')) {
+ var chars = this.input.value.split('\n').map(x=>x.length + 1),
+ line = 0,
+ charCount = 0,
+ newPos = 0,
+ posAtLine
+
+ for (let i = 0; i < chars.length; i++) {
+ charCount += chars[i]
+ if (charCount > this.input.selectionStart) {
+ posAtLine = chars[i] - (charCount - this.input.selectionStart)
+ break
+ }
+ line++
+ }
+ line = key === '{up}' ? line - 1 : line + 1
+ for (let i = 0; i < line; i++) {
+ newPos += chars[i]
+ }
+ if (posAtLine > chars[line] - 1) posAtLine = chars[line] - 1
+
+ this.input.selectionStart =
+ this.input.selectionEnd = newPos + posAtLine
+ } else {
+ this.input.selectionStart =
+ this.input.selectionEnd = key === '{up}' ? 0 : this.input.value.length
+ }
+ this.keydownHandler()
+ return
+ default:
+ str = key
+ break
+ }
+
+ if (str !== undefined) {
+
+ this.input.value = this.input.value.substring(0, startPos)
+ + str
+ + this.input.value.substring(endPos, this.input.value.length)
+
+ if (editLength === undefined) editLength = str.length
+
+ }
+
+ this.input.selectionStart = startPos + editLength
+ this.input.selectionEnd = startPos + editLength
+
+ this.inputHandler()
+
+ }
+
+ checkShift() {
+
+ var shift = false
+ for (var k in this.pressedKeys) {
+ var dataKey = this.pressedKeys[k].getAttribute('data-key')
+ if (dataKey === '{shift}') {
+ shift = true
+ }
+ }
+ this.shift = shift
+ this.container.classList.toggle('shift', this.lock !== this.shift)
+
+ }
+
+ updateDisplay() {
+
+ var value = ''
+
+ if (this.input) value = this.input.value
+
+ var content = html``
+ for (var i in value) {
+ let c, nl
+ switch (value[i]) {
+ case '\n':
+ c = raw('')
+ nl = true
+ break
+ case ' ':
+ c = raw(' ')
+ break
+ default:
+ c = value[i]
+ break
+ }
+ content.appendChild(html`
+ ${c}
+ `)
+ }
+
+ morph(this.display, content)
+
+ setTimeout(()=>{
+ this.updateCursor()
+ })
+ }
+
+ updateCursor() {
+
+ if (!this.input) return
+
+ var start = this.input.selectionStart,
+ end = this.input.selectionEnd
+
+
+ this.display.classList.remove('first-char-caret')
+ DOM.each(this.display, 'char', (el)=>{
+ el.classList.remove('caret')
+ el.classList.remove('select')
+ })
+
+ if (start === null || end === null) return
+
+ var caretChar = DOM.get(this.display, 'char:nth-child(' + start + ')')[0]
+
+ if (caretChar) {
+ caretChar.classList.add('caret')
+ caretChar.scrollIntoView()
+ }
+ else this.display.classList.add('first-char-caret')
+ if (start !== end) {
+ DOM.each(this.display, 'char:nth-child(n+' + (start + 1) + '):nth-child(-n+' + (end ) +')', (el)=>{
+ el.classList.add('select')
+ })
+ }
+
+ }
+
+ show(input){
+
+ if (input.osc_input) return // not compatible with code editor
+ if (this.visible) return
+
+ this.input = input
+ this.value = this.input.value
+
+ this.input.addEventListener('blur', this.boundBlurHandler)
+ this.input.addEventListener('input', this.boundInputHandler)
+ this.input.addEventListener('change', this.boundChangeHandler)
+ this.input.addEventListener('keydown', this.boundKeydownHandler)
+ this.input.addEventListener('select', this.boundSelectHandler)
+ this.input.addEventListener('click', this.boundClickHandler)
+
+ this.updateDisplay()
+
+ this.container.style.display = 'flex'
+
+ this.visible = true
+
+ }
+
+ hide(){
+
+ if (!this.visible) return
+
+ this.input.removeEventListener('blur', this.boundBlurHandler)
+ this.input.removeEventListener('input', this.boundInputHandler)
+ this.input.removeEventListener('change', this.boundChangeHandler)
+ this.input.removeEventListener('keydown', this.boundKeydownHandler)
+ this.input.removeEventListener('select', this.boundSelectHandler)
+ this.input.removeEventListener('click', this.boundClickHandler)
+
+ this.input = null
+ this.value = null
+
+
+ this.container.style.display = 'none'
+
+ this.visible = false
+
+ for (let k in this.repeatKeys) {
+ clearTimeout(this.repeatKeys[k][0])
+ clearInterval(this.repeatKeys[k][1])
+ }
+
+ for (let k in this.pressedKeys) {
+ this.pressedKeys[k].classList.remove('active')
+ delete this.pressedKeys[k]
+ }
+ }
+
+
+ blurHandler(e) {
+ setTimeout(()=>{
+ this.hide()
+ })
+ }
+ inputHandler(e) {
+ setTimeout(()=>{
+ this.updateDisplay()
+ })
+ }
+ changeHandler(e) {
+ setTimeout(()=>{
+ this.hide()
+ })
+ }
+ keydownHandler(e) {
+ setTimeout(()=>{
+ this.updateCursor()
+ })
+ }
+ selectHandler(e) {
+ setTimeout(()=>{
+ this.updateCursor()
+ })
+ }
+ clickHandler(e) {
+ setTimeout(()=>{
+ this.updateCursor()
+ })
+ }
+}
+
+export default new OscKeybard({element: DOM.get('osc-keyboard')[0]})
diff --git a/src/client/ui/ui-loading.js b/src/client/ui/ui-loading.mjs
similarity index 77%
rename from src/client/ui/ui-loading.js
rename to src/client/ui/ui-loading.mjs
index a9093b7a..24bcdc2b 100644
--- a/src/client/ui/ui-loading.js
+++ b/src/client/ui/ui-loading.mjs
@@ -1,7 +1,8 @@
-var notifications = require('./notifications'),
- loading = null, timeout = null
+import notifications from './notifications.mjs'
-module.exports = function uiLoading(title) {
+var loading = null, timeout = null
+
+export default function(title) {
if (title === false && loading) {
clearTimeout(timeout)
diff --git a/src/client/ui/ui-modal.js b/src/client/ui/ui-modal.mjs
similarity index 88%
rename from src/client/ui/ui-modal.js
rename to src/client/ui/ui-modal.mjs
index 45a44e56..0c8f7e49 100644
--- a/src/client/ui/ui-modal.js
+++ b/src/client/ui/ui-modal.mjs
@@ -1,8 +1,10 @@
-var UiWidget = require('./ui-widget'),
- {icon} = require('./utils'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- MODAL_SINGLETON = null,
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import UiWidget from './ui-widget.mjs'
+import {icon} from './utils.mjs'
+import {DOM} from '../globals.mjs'
+
+var MODAL_SINGLETON = null,
MODAL_CONTAINER = null
class UiModal extends UiWidget {
@@ -56,13 +58,13 @@ class UiModal extends UiWidget {
if (this.escKey) {
this.escKeyHandler = ((e)=>{
- if (e.keyCode==27) this.close()
+ if (e.key == 'Escape') this.close()
}).bind(this)
}
if (this.enterKey) {
this.enterKeyHandler = ((e)=>{
- if (e.keyCode == 13) this.enterKey.call(this, e)
+ if (e.key == 'Enter') this.enterKey.call(this, e)
}).bind(this)
}
@@ -102,4 +104,4 @@ class UiModal extends UiWidget {
}
-module.exports = UiModal
+export default UiModal
diff --git a/src/client/ui/ui-selectarea.js b/src/client/ui/ui-selectarea.mjs
similarity index 75%
rename from src/client/ui/ui-selectarea.js
rename to src/client/ui/ui-selectarea.mjs
index a27a58df..1ef816a7 100644
--- a/src/client/ui/ui-selectarea.js
+++ b/src/client/ui/ui-selectarea.mjs
@@ -1,4 +1,5 @@
-var html = require('nanohtml')
+import html from 'nanohtml'
+import {DOM} from '../globals.mjs'
class UiSelectArea {
@@ -18,14 +19,14 @@ class UiSelectArea {
this.selector = selector
this.callback = callback
- this.bindedMousedown = this.mousedown.bind(this)
- this.bindedMousemove = this.mousemove.bind(this)
- this.bindedMouseup = this.mouseup.bind(this)
+ this.boundMousedown = this.mousedown.bind(this)
+ this.boundMousemove = this.mousemove.bind(this)
+ this.boundMouseup = this.mouseup.bind(this)
}
mousedown(e) {
- if (!e.shiftKey || event.button === 2) return
+ if (!e.shiftKey || event.altKey || event.button === 2 || (event.shiftKey && event.metaKey)) return
this.startX = this.curX = e.clientX
this.startY = this.curY = e.clientY
this.down = true
@@ -46,7 +47,7 @@ class UiSelectArea {
this.down = false
if (this.rectSize[0] > 0 && this.rectSize[1] > 0) {
- this.callback(this.getElements())
+ this.callback(this.getElements(), e)
this.rect.classList.add('hidden')
}
@@ -109,20 +110,20 @@ class UiSelectArea {
enable() {
- document.addEventListener('pointerdown', this.bindedMousedown)
- document.addEventListener('pointermove', this.bindedMousemove, true)
- document.addEventListener('pointerup', this.bindedMouseup)
+ document.addEventListener('pointerdown', this.boundMousedown)
+ document.addEventListener('pointermove', this.boundMousemove, true)
+ document.addEventListener('pointerup', this.boundMouseup)
}
disable() {
- document.removeEventListener('pointerdown', this.bindedMousedown)
- document.removeEventListener('pointermove', this.bindedMousemove, true)
- document.removeEventListener('pointerup', this.bindedMouseup)
+ document.removeEventListener('pointerdown', this.boundMousedown)
+ document.removeEventListener('pointermove', this.boundMousemove, true)
+ document.removeEventListener('pointerup', this.boundMouseup)
}
}
-module.exports = UiSelectArea
+export default UiSelectArea
diff --git a/src/client/ui/ui-sidepanel.js b/src/client/ui/ui-sidepanel.mjs
similarity index 92%
rename from src/client/ui/ui-sidepanel.js
rename to src/client/ui/ui-sidepanel.mjs
index d588566c..b571374f 100644
--- a/src/client/ui/ui-sidepanel.js
+++ b/src/client/ui/ui-sidepanel.mjs
@@ -1,5 +1,6 @@
-var UiWidget = require('./ui-widget'),
- cache = require('../managers/cache')
+import UiWidget from './ui-widget.mjs'
+import cache from '../managers/cache.mjs'
+import {DOM, PXSCALE} from '../globals.mjs'
class UiSidePanel extends UiWidget {
@@ -19,7 +20,7 @@ class UiSidePanel extends UiWidget {
var size = cache.get(this.cacheKey + '.width') || 250
this.minWidth = options.minSize !== undefined ? options.minSize : (options.size !== undefined ? options.size : 250)
- this.width = size !== undefined ? size : (options.size !== undefined ? options.size : 250)
+ this.width = size !== undefined ? size : (options.size !== undefined ? options.size : 350)
this.disabled = false
var minimized = cache.get(this.cacheKey + '.minimized')
@@ -107,6 +108,7 @@ class UiSidePanel extends UiWidget {
updateWidth() {
this.container.style[this.vertical ? 'height' : 'width'] = this.width + 'rem'
+ this.container.style.setProperty('--sidepanel-size', this.width + 'rem')
}
@@ -134,4 +136,4 @@ class UiSidePanel extends UiWidget {
-module.exports = UiSidePanel
+export default UiSidePanel
diff --git a/src/client/ui/ui-toolbar.js b/src/client/ui/ui-toolbar.mjs
similarity index 90%
rename from src/client/ui/ui-toolbar.js
rename to src/client/ui/ui-toolbar.mjs
index 91bc4d7a..1daa090c 100644
--- a/src/client/ui/ui-toolbar.js
+++ b/src/client/ui/ui-toolbar.mjs
@@ -1,5 +1,5 @@
-var UiWidget = require('./ui-widget'),
- ContextMenu = require('./context-menu')
+import UiWidget from './ui-widget.mjs'
+import ContextMenu from './context-menu.mjs'
class UiToolbar extends UiWidget {
@@ -12,6 +12,7 @@ class UiToolbar extends UiWidget {
})
this.opened = false
this.entries = options.entries
+
this.menu.bindShortcuts(this.entries)
this.container.addEventListener('fast-click', (e)=>{
@@ -59,4 +60,4 @@ class UiToolbar extends UiWidget {
}
-module.exports = UiToolbar
+export default UiToolbar
diff --git a/src/client/ui/ui-tree.js b/src/client/ui/ui-tree.js
deleted file mode 100644
index 9377eb2f..00000000
--- a/src/client/ui/ui-tree.js
+++ /dev/null
@@ -1,197 +0,0 @@
-var UiWidget = require('./ui-widget'),
- html = require('nanohtml'),
- doubleClick = require('../events/double-click'),
- Sortable = require('sortablejs'),
- morph = require('nanomorph'),
- Root, Panel, Matrix, Keyboard, widgetManager,
- init = false
-
-class UiTree extends UiWidget {
-
- constructor(options) {
-
- Root = require('../widgets/containers/root')
- Panel = require('../widgets/containers/panel')
- Matrix = require('../widgets/containers/matrix')
- Keyboard = require('../widgets/containers/keyboard')
- widgetManager = require('../managers/widgets')
-
- super(options)
-
- this.mounted = false
- this.list = this.container.appendChild(html`
`
-
-
- this.expanded = {}
-
- 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-widget')] = true
- } else {
- delete this.expanded[node.parentNode.getAttribute('data-widget')]
- }
- }
-
-
- })
-
- 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-widget')] = true
- } else {
- delete this.expanded[node.getAttribute('data-widget')]
- }
- }
-
- }, {ignoreEditorCapture: true})
-
-
- this.sortables = []
- this.sortCallback = (event)=>{
- var widget = widgetManager.widgets[event.to.parentNode.getAttribute('data-widget')]
- if (!widget || event.oldIndex === event.newIndex) return
- this.trigger('sorted', {
- widget: widget,
- oldIndex: event.oldIndex,
- newIndex: event.newIndex
- })
- }
-
- widgetManager.on('prop-changed', (e)=>{
- console.log(e)
- })
-
- }
-
- 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)
-
- if (!content) return
-
- // 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
-
-
- }
-
- showWidget(widget) {
-
- var node = DOM.get(this.list, `[data-widget="${widget.hash}"]`)
- if (node) {
- var parent = node[0].parentNode
- while (parent !== this.list) {
- if (parent.classList.contains('container')) {
- parent.classList.add('expanded')
- this.expanded[parent.getAttribute('data-widget')] = true
- }
- parent = parent.parentNode
- }
- node[0].scrollIntoView({block: 'center'})
- }
-
- }
-
- 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) {
-
- if (!widget) return
-
- var selected = selectedWidgets.includes(widget),
- id = widget.getProp('id'),
- node = html`
- ${id} `
-
- if (widget instanceof Panel && !(widget instanceof Matrix || widget instanceof Keyboard)) {
- node.insertBefore(html``, node.childNodes[0])
- node.classList.add('container')
- if (this.expanded[widget.hash]) node.classList.add('expanded')
- if (!init && widget instanceof Root) {
- node.classList.add('expanded')
- this.expanded[widget.hash] = true
- init = true
- }
- var sublist = node.appendChild(html`
`)
- for (let child of widget.children) {
- if (child) sublist.appendChild(this.parseWidgets(child, selectedWidgets, depth))
- }
-
- }
-
- for (var h in this.expanded) {
- if (!widgetManager.widgets[h]) delete this.expanded[h]
- }
-
- return node
-
- }
-
-}
-
-module.exports = UiTree
diff --git a/src/client/ui/ui-tree.mjs b/src/client/ui/ui-tree.mjs
new file mode 100644
index 00000000..42afb6c4
--- /dev/null
+++ b/src/client/ui/ui-tree.mjs
@@ -0,0 +1,369 @@
+import UiWidget from './ui-widget'
+import html from 'nanohtml'
+import doubleClick from '../events/double-click'
+import Sortable from 'sortablejs'
+import morph from 'nanomorph'
+import locales from '../locales'
+import raw from 'nanohtml/raw'
+import {icon} from './utils.mjs'
+import {widgets, categories} from '../widgets/index.mjs'
+import {DOM} from '../globals.mjs'
+
+var Root, Panel, Matrix, Keyboard, widgetManager
+;(async()=>{
+ Root = (await import('../widgets/containers/root.mjs')).default
+ Panel = (await import('../widgets/containers/panel.mjs')).default
+ Matrix = (await import('../widgets/containers/matrix.mjs')).default
+ Keyboard = (await import('../widgets/containers/keyboard.mjs')).default
+ widgetManager = (await import('../managers/widgets.mjs')).default
+})()
+
+
+var widgetIcons = {
+ root: 'bookmark',
+ tab: 'window-maximize',
+ folder: 'folder',
+ menu: 'list',
+ dropdown: 'list',
+ switch: 'list',
+ input: 'i-cursor',
+ file: 'file-import',
+ modal: 'window-restore',
+ clone: 'cube',
+ fragment: 'cube',
+ patchbay: 'project-diagram',
+ frame: 'globe'
+
+}
+
+var categoryIcons = {
+ 'Basics': 'toggle-on',
+ 'Containers': 'table-list',
+ 'Frames': 'images',
+ 'Graphs': 'chart-area',
+ 'Indicators': 'info-circle',
+ 'Pads': 'crosshairs',
+ 'Sliders': 'sliders-h.rotate-90',
+ 'Scripts': 'code',
+}
+
+for (var type in widgets) {
+ if (widgetIcons[type]) continue
+ for (var cat in categoryIcons) {
+ if (categories[cat].includes(type)) {
+ widgetIcons[type] = categoryIcons[cat]
+ }
+ }
+}
+
+
+class UiTree extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.mounted = false
+ this.fragment = this.container.appendChild(html`${locales('fragment_mode_warning')}`)
+ this.filter = this.container.appendChild(html``)
+ this.wrapper = this.container.appendChild(html``)
+ this.list = this.wrapper.appendChild(html`
`
+ this.deferredUpdateTimeout = null
+
+
+ this.expanded = {}
+ this.init = false
+
+ 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-widget')] = true
+ } else {
+ delete this.expanded[node.parentNode.getAttribute('data-widget')]
+ }
+ }
+
+
+ })
+
+ 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-widget')] = true
+ } else {
+ delete this.expanded[node.getAttribute('data-widget')]
+ }
+ }
+
+ }, {ignoreEditorCapture: true})
+
+
+ this.sortables = []
+ this.sortCallback = (event)=>{
+
+ var from = widgetManager.widgets[event.from.getAttribute('data-hash')],
+ to = widgetManager.widgets[event.to.getAttribute('data-hash')]
+
+ if (!to || (from === to && event.oldIndex === event.newIndex)) return
+
+ this.trigger('sorted', {
+ oldIndex: event.oldIndex,
+ newIndex: event.newIndex,
+ from: from,
+ to: to
+ })
+
+ }
+
+ this.filter.addEventListener('change', ()=>{
+ this.applyFilter()
+ })
+ var filterTypeTimeout = null
+ this.filter.addEventListener('keydown', ()=>{
+ clearTimeout(filterTypeTimeout)
+ filterTypeTimeout = setTimeout(()=>{
+ this.applyFilter()
+ }, 100)
+ })
+
+ }
+
+ clear() {
+
+ this.list.innerHTML = ''
+ this.init = false
+ this.mounted = false
+ for (var s of this.sortables) {
+ s.destroy()
+ }
+ this.sortables = []
+
+ }
+
+ updateTree(selectedWidgets) {
+
+ if (this.parent.minimized || this.parent.disabled) {
+ clearTimeout(this.deferredUpdateTimeout)
+ this.deferredUpdateTimeout = setTimeout(()=>{
+ this.deferredUpdateTree(selectedWidgets)
+ })
+ } else {
+ this.deferredUpdateTree(selectedWidgets)
+ }
+
+ }
+
+ deferredUpdateTree(selectedWidgets) {
+
+ this.deferredUpdateTimeout = null
+
+ for (var s of this.sortables) {
+ s.destroy()
+ }
+ this.sortables = []
+
+ var content = this.parseWidgets(widgetManager.getWidgetById('root')[0], selectedWidgets)
+
+ if (!content) return
+
+ // morph DOM
+ if (this.mounted) {
+ morph(this.list.firstChild, content)
+ } else {
+ this.list.appendChild(content)
+ }
+
+
+ // sortable lists
+ DOM.each(this.list, 'ol', (el)=>{
+ let placeholder = null
+ this.sortables.push(new Sortable(el, {
+ group: {
+ name: 'group',
+ pull: (to, from)=>from.el.dataset.childrenType === to.el.dataset.childrenType || to.el.dataset.childrenType === '',
+ put: (to, from)=>from.el.dataset.childrenType === to.el.dataset.childrenType || to.el.dataset.childrenType === '',
+ },
+ onEnd: (e)=>{
+ e.from.removeChild(placeholder)
+ placeholder = null
+ if (e.from === e.to && e.newIndex > e.oldIndex) e.newIndex--
+ this.sortCallback(e)
+ },
+ setData: (dataTransfer)=>{
+ dataTransfer.setDragImage(this.dragDummy, 0, 0)
+ },
+ onStart: (event)=>{
+ placeholder = event.from.insertBefore(event.clone.cloneNode(true), event.from.childNodes[event.oldIndex])
+ placeholder.style.display = 'block'
+ },
+ }))
+ })
+
+ this.mounted = true
+ this.applyFilter()
+
+ }
+
+ showWidget(widget) {
+
+ var node = DOM.get(this.list, `[data-widget="${widget.hash}"]`)
+ if (node.length) {
+ node = node[0]
+ var parent = node.parentNode
+ while (parent !== this.list) {
+ if (parent.classList.contains('container')) {
+ parent.classList.add('expanded')
+ this.expanded[parent.getAttribute('data-widget')] = true
+ }
+ parent = parent.parentNode
+ }
+ var nodeRect = node.classList.contains('container') ? node.firstChild.getBoundingClientRect() : node.getBoundingClientRect(),
+ treeRect = this.wrapper.getBoundingClientRect()
+
+ if (nodeRect.top < treeRect.top) {
+ node.scrollIntoView({block: 'start'})
+ } else if (nodeRect.bottom > treeRect.bottom) {
+ node.scrollIntoView({block: 'nearest'})
+ }
+ this.wrapper.scrollLeft = (node.depth - 1) * 20
+ }
+
+ if (this.parent.minimized) this.parent.restore()
+
+ }
+
+ blinkSelected() {
+
+ DOM.each(this.list, '.editing', (el)=>{
+ el.classList.add('editor-blink')
+ this.wrapper.scrollLeft = (el.depth - 1) * 20
+ setTimeout(()=>{
+ el.classList.remove('editor-blink')
+ }, 800)
+ })
+
+ }
+
+ showWidgetInSession(widget) {
+
+ var parent = widget
+ while (parent !== widgetManager) {
+ if (parent.getProp('type') === 'tab') parent.parent.setValue(parent.parent.children.indexOf(parent), {sync: true, send: true})
+ else if (parent.getProp('type') === 'modal') parent.setValue(1, {sync: true, send: true})
+ parent = parent.parent
+ }
+ widget.container.classList.add('editor-blink')
+ widget.container.scrollIntoView({block: 'center'})
+ setTimeout(()=>{
+ widget.container.classList.remove('editor-blink')
+ }, 800)
+
+ }
+
+ 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) {
+
+ if (!widget) return
+
+ var selected = selectedWidgets.includes(widget),
+ id = widget.getProp('id'),
+ node = html`
+ ${raw(icon(widgetIcons[widget.getProp('type')] || 'root'))}${id}${widget.getProp('lock')? raw(icon('lock')) :''} `
+
+
+ node.depth = depth
+
+ if (widget instanceof Panel && !(widget instanceof Matrix || widget instanceof Keyboard)) {
+ node.insertBefore(html``, node.childNodes[0])
+ node.classList.add('container')
+ if (this.expanded[widget.hash]) node.classList.add('expanded')
+ if (!this.init && widget instanceof Root) {
+ node.classList.add('expanded')
+ this.expanded[widget.hash] = true
+ this.init = true
+ }
+ var sublist = node.appendChild(html`
`)
+ for (let child of widget.children) {
+ if (child) sublist.appendChild(this.parseWidgets(child, selectedWidgets, depth))
+ }
+
+ }
+
+ for (var h in this.expanded) {
+ if (!widgetManager.widgets[h]) delete this.expanded[h]
+ }
+
+ return node
+
+ }
+
+ applyFilter() {
+
+ var filter = this.filter.value.replace(/type\:[^\s]+/g, '').trim(),
+ types = this.filter.value.match(/type\:([^\s]+)/g)
+
+ if (types) types = types.map(x=>x.split(':')[1])
+
+ if (!filter && !types) {
+ this.list.classList.remove('filter-active')
+ } else {
+ this.list.classList.add('filter-active')
+
+ var show = []
+ DOM.each(this.list, 'li', (element)=>{
+ var match = element.innerText.includes(filter)
+ if (types && !types.includes(element.dataset.type)) match = false
+ element.classList.toggle('filter-hide', !match)
+ if (match) show.push(element)
+ })
+
+ DOM.each(this.list, '.container.filter-hide', (element)=>{
+ if (show.some(el=>element.contains(el))) element.classList.remove('filter-hide')
+ })
+
+ }
+
+ }
+
+ updateVisibility(widget) {
+
+ if (!this.parent.disabled) {
+
+ var w = DOM.get(this.list, '[data-widget="' + widget.hash + '"]')[0]
+
+ if (w) {
+ w.classList.toggle('invisible', !widget.getProp('visible'))
+ }
+
+ }
+
+ }
+
+}
+
+export default UiTree
diff --git a/src/client/ui/ui-widget.js b/src/client/ui/ui-widget.mjs
similarity index 66%
rename from src/client/ui/ui-widget.js
rename to src/client/ui/ui-widget.mjs
index fa16cdbe..9d8db2b6 100644
--- a/src/client/ui/ui-widget.js
+++ b/src/client/ui/ui-widget.mjs
@@ -1,4 +1,5 @@
-var EventEmitter = require('../events/event-emitter')
+import EventEmitter from '../events/event-emitter.mjs'
+import {DOM} from '../globals.mjs'
class UiWidget extends EventEmitter {
@@ -13,4 +14,4 @@ class UiWidget extends EventEmitter {
}
-module.exports = UiWidget
+export default UiWidget
diff --git a/src/client/ui/ui-workspace.js b/src/client/ui/ui-workspace.js
deleted file mode 100644
index 95c3d189..00000000
--- a/src/client/ui/ui-workspace.js
+++ /dev/null
@@ -1,16 +0,0 @@
-var UiWidget = require('./ui-widget'),
- setScrollbarColor = require('./scrollbar-color')
-
-class UiWorkspace extends UiWidget {
-
- constructor(options) {
-
- super(options)
-
- setScrollbarColor(this.container)
-
- }
-
-}
-
-module.exports = new UiWorkspace({selector: 'osc-workspace'})
diff --git a/src/client/ui/ui-workspace.mjs b/src/client/ui/ui-workspace.mjs
new file mode 100644
index 00000000..41205230
--- /dev/null
+++ b/src/client/ui/ui-workspace.mjs
@@ -0,0 +1,16 @@
+import UiWidget from './ui-widget.mjs'
+import {setScrollbarColor} from './utils.mjs'
+
+class UiWorkspace extends UiWidget {
+
+ constructor(options) {
+
+ super(options)
+
+ setScrollbarColor(this.container)
+
+ }
+
+}
+
+export default new UiWorkspace({selector: 'osc-workspace'})
diff --git a/src/client/ui/utils.js b/src/client/ui/utils.js
deleted file mode 100644
index 86c41985..00000000
--- a/src/client/ui/utils.js
+++ /dev/null
@@ -1,15 +0,0 @@
-
-module.exports = {
-
-
- icon: function(i) {
- var iclass = i.split('.').join(' fa-')
- return ``
- },
- iconify:function(string){
- return String(string).replace(/\^[^\s]{2,}/g,(x)=>{return module.exports.icon(x.substring(1))})
- },
-
-
-
-}
diff --git a/src/client/ui/utils.mjs b/src/client/ui/utils.mjs
new file mode 100644
index 00000000..c23afcc7
--- /dev/null
+++ b/src/client/ui/utils.mjs
@@ -0,0 +1,66 @@
+import chroma from 'chroma-js'
+import fastdom from 'fastdom'
+import {UAParser} from 'ua-parser-js'
+import {DOM} from '../globals.mjs'
+
+var {device, os} = UAParser().withFeatureCheck()
+
+export {device, os}
+
+export function icon(i) {
+ var iclass = i.split('.').join(' fa-')
+ return ``
+}
+
+export function iconify(string){
+ return String(string).replace(/\^[^\s]{2,}/g,(x)=>{return icon(x.substring(1))})
+}
+
+export function setScrollbarColor(container) {
+
+ fastdom.measure(()=>{
+
+ var computedStyle = window.getComputedStyle(container),
+ alpha = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar')),
+ alphaOn = parseFloat(computedStyle.getPropertyValue('--alpha-scrollbar-on')),
+ color = computedStyle.getPropertyValue('--color-fill').trim()
+
+ if (color === 'transparent') {
+ // prevent chroma-js error
+ // irrelevant case, but still...
+ color = 'rgb(0, 0, 0)'
+ alpha = 0
+ alphaOn = 0
+ }
+
+ if (color) {
+ fastdom.mutate(()=>{
+ try {
+ container.style.setProperty('--color-scrollbar', chroma(color).alpha(alpha).css())
+ container.style.setProperty('--color-scrollbar-on', chroma(color).alpha(alphaOn).css())
+ } catch(e) {}
+ })
+ }
+
+ })
+
+}
+
+export function updateMobileThemeColor(root) {
+
+ fastdom.measure(()=>{
+
+ var style = window.getComputedStyle(root ? root.widget : document.documentElement),
+ color = style.getPropertyValue('--color-background').trim()
+
+ fastdom.mutate(()=>{
+
+ for (var el of DOM.get('meta[name="theme-color"], meta[name="apple-mobile-web-app-status-bar-style"]')) {
+ el.setAttribute('content', color)
+ }
+
+ })
+
+ })
+
+}
diff --git a/src/client/ui/zoom.js b/src/client/ui/zoom.js
deleted file mode 100644
index 8ed8e9f0..00000000
--- a/src/client/ui/zoom.js
+++ /dev/null
@@ -1,29 +0,0 @@
-// mousewheel zoom
-
-var mod = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
-
-document.addEventListener('wheel', 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})
diff --git a/src/client/ui/zoom.mjs b/src/client/ui/zoom.mjs
new file mode 100644
index 00000000..a39b0837
--- /dev/null
+++ b/src/client/ui/zoom.mjs
@@ -0,0 +1,94 @@
+import EventEmitter from '../events/event-emitter.mjs'
+import {DOM, PXSCALE, INITIALZOOM, setPXSCALE} from '../globals.mjs'
+
+var mod = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
+
+class Zoom extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.localZoom = 1
+ this.lastWheelZoom = 0
+ this.editor = null
+
+ document.addEventListener('wheel', (event)=>{
+ if (event.ctrlKey) event.preventDefault()
+
+ var now = Date.now()
+ if (now - this.lastWheelZoom > 50) {
+
+ if (event[mod]) {
+
+ event.preventDefault()
+
+ if (event.deltaY === 0) return
+
+ let d = - event.deltaY / (10 * Math.abs(event.deltaY))
+ if (!isNaN(d)) this.setGlobalZoom(d + PXSCALE)
+ }
+ if (event.altKey) {
+ event.preventDefault()
+ let d = - event.deltaY / (10 * Math.abs(event.deltaY)) * 2
+ if (!isNaN(d)) this.setLocalZoom(d + this.localZoom)
+ }
+
+ this.lastWheelZoom = now
+ }
+
+ }, {passive: false})
+
+ document.addEventListener('keydown', (event)=>{
+ if (event[mod]) {
+
+ if (event.key == 'DOM_VK_0' || event.key == 'Numpad0'|| event.code == 'Digit0') {
+ event.preventDefault()
+ this.setGlobalZoom(INITIALZOOM)
+ this.setLocalZoom(1)
+ }
+ else if (event.key == '+' || event.key == '=' || event.keyCode === 107) {
+ event.preventDefault()
+ this.setGlobalZoom(PXSCALE + 0.1)
+ }
+ else if (event.key == '-' || event.keyCode === 109) {
+ event.preventDefault()
+ this.setGlobalZoom(PXSCALE - 0.1)
+ }
+
+ }
+ }, {passive: false})
+
+ }
+
+ setLocalZoom(zoom) {
+
+ if (this.editor && !this.editor.enabled) return
+
+ zoom = Math.max(Math.min(zoom, 4), 0.25)
+ if (zoom !== this.localZoom) {
+ requestAnimationFrame(()=>{
+ this.localZoom = zoom
+ document.documentElement.style.setProperty('--local-zoom', this.localZoom)
+ document.body.classList.toggle('local-zoom-in', this.localZoom > 1)
+ document.body.classList.toggle('local-zoom-out', this.localZoom < 1)
+ this.trigger('local-zoom-changed')
+ })
+ }
+
+ }
+
+ setGlobalZoom(zoom) {
+
+ if (zoom !== PXSCALE) {
+ setPXSCALE(zoom)
+ document.documentElement.style.setProperty('font-size', PXSCALE + 'px')
+ DOM.dispatchEvent(window, 'resize')
+ this.trigger('global-zoom-changed')
+ }
+
+ }
+
+}
+
+export default new Zoom()
diff --git a/src/client/utils.js b/src/client/utils.js
deleted file mode 100644
index e4e06d67..00000000
--- a/src/client/utils.js
+++ /dev/null
@@ -1,48 +0,0 @@
-module.exports = {
-
- deepCopy: function(obj, decimals) {
-
- 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], decimals)
- }
- } else if (typeof obj == 'number') {
- return decimals === undefined ? copy : parseFloat(copy.toFixed(decimals))
- }
-
- return copy
-
- },
-
- deepEqual: function(a, 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
- }
-
- },
-
- isJSON: function(str) {
- // heuristic to avoid using JSON when unnecessary
- // if the string doesn't start with one of these chars
- // it's going to fail
- // ref in source: https://github.com/douglascrockford/JSON-js
- return ' \n+-eE{([0123456789tfn"'.indexOf(str[0]) !== -1
-
- }
-
-}
diff --git a/src/client/utils.mjs b/src/client/utils.mjs
new file mode 100644
index 00000000..e7c07471
--- /dev/null
+++ b/src/client/utils.mjs
@@ -0,0 +1,49 @@
+export function deepCopy(obj, decimals) {
+
+ var copy = obj
+
+ if (obj === null) {
+ return obj
+ }
+
+ if (typeof obj === 'object') {
+ copy = Array.isArray(obj) ? [] : {}
+ for (let key in obj) {
+ copy[key] = deepCopy(obj[key], decimals)
+ }
+ } else if (typeof obj == 'number') {
+ return decimals === undefined ? copy : parseFloat(copy.toFixed(decimals))
+ }
+
+ return copy
+
+}
+
+export function deepEqual(a, 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
+ }
+
+}
+
+export function isJSON(str) {
+ // heuristic to avoid using JSON when unnecessary
+ // if the string doesn't start with one of these chars
+ // it's going to fail
+ // ref in source: https://github.com/douglascrockford/JSON-js
+ return ' \n+-eE{([0123456789tfn"'.indexOf(str[0]) !== -1
+
+}
+
+export function isJSONObject(str) {
+ // same, but only for object/array/bool/null
+ return '{[tfn'.indexOf(str[0]) !== -1
+}
diff --git a/src/client/widgets/basics/button.js b/src/client/widgets/basics/button.js
deleted file mode 100644
index 31791031..00000000
--- a/src/client/widgets/basics/button.js
+++ /dev/null
@@ -1,255 +0,0 @@
-var Widget = require('../common/widget'),
- doubletab = require('../mixins/double_tap'),
- html = require('nanohtml'),
- {deepEqual, isJSON} = require('../../utils'),
- {iconify} = require('../../ui/utils')
-
-class Button extends Widget {
-
- static description() {
-
- return 'On / off button.'
-
- }
-
- static defaults() {
-
- return super.defaults(Button).extend({
- style: {
- _separator_button_style: 'Button style',
- colorTextOn: {type: 'string', value: 'auto', help: 'Defines the widget\'s text color when active.'},
- label: {type: 'string|boolean', value: 'auto', help: [
- 'Set to `false` to hide completely',
- '- Insert icons using the prefix ^ followed by the icon\'s name : `^play`, `^pause`, etc (see https://fontawesome.com/icons?d=gallery&s=solid&m=free)',
- '- Icons can be transformed with the following suffixes: `.flip-[horizontal|vertical|both]`, `.rotate-[90|180|270]`, `.spin`, `.pulse`. Example: `^play.flip-horizontal`',
- ]},
- 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.',
- ]},
- },
- class_specific: {
- on: {type: '*', value: 1, help: [
- 'Set to `null` to send send no argument in the osc message',
- ]},
- off: {type: '*', value: 0, help: [
- 'Set to `null` to send send no argument in the osc message. Must be different from `on`.',
- ]},
- mode: {type: 'string', value: 'toggle', choices: ['toggle', 'push', 'tap'], help: [
- 'Interraction mode:',
- '- `toggle` (classic on/off switch)',
- '- `push` (press & release)',
- '- `tap` (no release)'
- ]},
- doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the button require a double tap to be pushed instead of a single tap'},
-
- }
- })
-
- }
-
- constructor(options) {
-
- super({...options, html: html` `})
-
- this.state = 0
- this.active = false
- this.pulse = null
-
- var tap = this.getProp('mode') === 'tap',
- push = this.getProp('mode') === 'push' || tap
-
- if (push) {
-
- if (this.getProp('doubleTap')) {
-
- doubletab(this.container, (e)=>{
-
- this.active = true
- this.setValue(this.getProp('on'), {sync: true, send: true, y: e.offsetY})
-
- if (tap) this.container.classList.add('active')
-
- })
-
- } else {
-
- this.on('draginit',(e)=>{
-
- if (this.active) return
-
- this.active = true
- this.setValue(this.getProp('on'), {sync: true, send: true, y: e.offsetY})
-
- if (tap) this.container.classList.add('active')
-
-
- }, {element: this.container})
-
- }
-
- this.on('dragend',()=>{
-
- if (!this.active) return
-
- this.active = false
-
- if (!tap) this.setValue(this.getProp('off'), {sync: true, send: true})
- if (tap) this.container.classList.remove('active')
-
- }, {element: this.container})
-
- } else {
-
- if (this.getProp('doubleTap')) {
-
- doubletab(this.container, (e)=>{
-
-
- this.active = true
- this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true, y: e.offsetY})
-
- })
-
- } else {
-
- this.on('draginit',(e)=>{
-
- if (this.active) return
-
- this.active = true
- this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true, y: e.offsetY})
-
- }, {element: this.container})
-
- this.on('dragend',()=>{
-
- this.active = false
-
- }, {element: this.container})
-
- }
-
- }
-
- if (tap) this.noValueState = true
-
- this.value = this.getProp('off')
-
- this.label = html``
-
- if (this.getProp('wrap')) this.label.classList.add('wrap')
- if (this.getProp('vertical')) this.label.classList.add('vertical')
-
- this.updateLabel()
-
- }
-
-
-
- setValue(v, options={}) {
-
- if (typeof v === 'string' && isJSON(v)) {
- try {
- v = JSON.parse(v )
- } catch (err) {}
- }
-
- var newstate
-
- if (deepEqual(v, this.getProp('on'))) {
-
- newstate = 1
-
- } else if (deepEqual(v, this.getProp('off'))) {
-
- newstate = 0
-
- }
-
- if (newstate !== undefined) {
-
- this.state = newstate
- this.container.classList.toggle('on', this.state)
- this.value = this.getProp(this.state ? 'on' : 'off')
-
- if (options.send) this.sendValue()
- if (options.sync) this.changed(options)
-
- // tap mode
- if (newstate && this.getProp('mode') === 'tap' && !options.tapRelease) {
-
- // reset value
- this.setValue(this.getProp('off'), {sync: false, send: false, tapRelease: true})
-
- // pulse
- clearTimeout(this.pulse)
- this.container.classList.remove('pulse')
- setTimeout(()=>{
- this.container.classList.add('pulse')
- this.pulse = setTimeout(()=>{
- this.container.classList.remove('pulse')
- }, 150)
- }, 16)
-
- }
-
- }
-
-
-
- }
-
- updateLabel() {
-
- if (!this.label) return
-
- if (this.getProp('label') === false) {
-
- if (this.widget.contains(this.label)) this.widget.removeChild(this.label)
-
- } else {
- this.label.innerHTML = this.getProp('label') == 'auto'?
- this.getProp('id'):
- iconify(String(this.getProp('label')).replace(/documentation.',]},
+ }
+ })
+
+ defaults.scripting.onValue.help.push(
+ 'Additional variables:',
+ '- `locals.touchCoords`: `[x, y]` array representing the touch coordinates, normalized between 0 and 1.',
+ '- `locals.external`: `true` if value was received from an osc/midi message, `false otherwise`.'
+ )
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html` `})
+
+ this.state = 0
+ this.touchActive = false
+ this.localSet = false
+ this.pulseIn = null
+ this.pulseOut = null
+
+ this.buttonSize = [100, 100]
+ this.exposeTouchCoords = String(this.getProp('onValue')).includes('touchCoords')
+ this.parsersLocalScope.external = false
+ this.parsersLocalScope.touchCoords = [0.5, 0.5]
+ if (this.exposeTouchCoords) {
+ this.on('resize', (e)=>{
+ this.buttonSize = [e.width, e.height]
+ }, {element: this.widget})
+ }
+
+ if (this.getProp('onTouch')) {
+ this.on('draginit',(e)=>this.onTouch(e, 'start'), {element: this.container})
+ }
+
+ var mode = this.getProp('mode'),
+ tap = mode === 'momentary' || mode === 'tap',
+ push = mode === 'push' || tap,
+ click = this.getProp('click') && mode !== 'push'
+
+ if (push) {
+
+ if (this.getProp('doubleTap')) {
+
+ doubleTap(this, (e)=>{
+
+ this.touchActive = true
+
+ if (this.exposeTouchCoords) {
+ this.parsersLocalScope.touchCoords = [e.offsetX / this.buttonSize[0], 1 - e.offsetY / this.buttonSize[1]]
+ }
+
+ this.setValue(this.getProp('on'), {sync: true, send: true, local:true, y: e.offsetY})
+
+ if (tap) this.container.classList.add('active')
+
+ }, {element: this.container, click: click})
+
+ } else {
+
+ this.on(click ? 'click': 'draginit',(e)=>{
+
+ if (this.touchActive) return
+
+ this.touchActive = true
+
+ if (this.exposeTouchCoords) {
+ this.parsersLocalScope.touchCoords = [e.offsetX / this.buttonSize[0], 1 - e.offsetY / this.buttonSize[1]]
+ }
+
+ this.setValue(this.getProp('on'), {sync: true, send: true, local:true, y: e.offsetY})
+
+ if (tap) this.container.classList.add('active')
+
+
+ }, {element: this.container})
+
+ }
+
+ if (this.exposeTouchCoords) {
+ this.on('drag',(e)=>{
+
+ if (!this.touchActive) return
+
+ this.parsersLocalScope.touchCoords[0] += e.movementX / this.buttonSize[0]
+ this.parsersLocalScope.touchCoords[1] += e.movementY / this.buttonSize[1]
+
+ }, {element: this.container})
+ }
+
+ this.on('dragend',()=>{
+
+ if (!this.touchActive) return
+
+ this.touchActive = false
+
+ if (!tap) this.setValue(this.getProp('off'), {sync: true, send: true, local:true})
+ if (tap) this.container.classList.remove('active')
+
+
+ }, {element: this.container})
+
+ } else {
+
+ if (this.getProp('doubleTap')) {
+
+ doubleTap(this, (e)=>{
+
+
+ this.touchActive = true
+ this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true, y: e.offsetY, x: e.offsetX, local:true})
+
+ }, {element: this.container, click: click})
+
+ } else {
+
+ this.on(click ? 'click': 'draginit',(e)=>{
+
+ if (this.touchActive) return
+
+ if (e.traversingStack && TOGGLE_ALT_TRAVERSING) {
+ if (e.traversingStack.firstButtonValue === undefined) {
+ e.traversingStack.firstButtonValue = this.state
+ } else if (e.traversingStack.firstButtonValue !== this.state) {
+ return
+ }
+ }
+
+ this.touchActive = true
+ this.setValue(this.state ? this.getProp('off') : this.getProp('on'), {sync: true, send: true, y: e.offsetY, x: e.offsetX, local:true})
+
+ }, {element: this.container})
+
+ this.on('dragend',()=>{
+
+ this.touchActive = false
+
+ }, {element: this.container})
+
+ }
+
+ }
+
+ if (tap) this.noValueState = true
+
+ this.label = html``
+
+ if (this.getProp('wrap')) this.label.classList.add('wrap')
+ if (this.getProp('wrap') === 'soft') this.label.classList.add('wrap-soft')
+ if (this.getProp('vertical')) this.label.classList.add('vertical')
+
+ this.updateLabel()
+
+ if (this.getProp('decoupled')) {
+
+ this.decoupledValue = parser.parse({
+ data: {
+ type: 'variable',
+ id: this.getProp('id') + '/decoupledValue',
+ ignoreDefaults: true,
+ },
+ parentNode: this.widget,
+ parent: this,
+ meta: {...this.meta}
+ })
+ this.decoupledValue.on('value-changed', (e)=>{
+ this.container.classList.toggle('on', this.decoupledValue.value)
+ if (e.options.send) this.decoupledValue.sendValue()
+ })
+
+ }
+
+ if (this.getProp('onTouch')) {
+ this.on('drag',(e)=>this.onTouch(e, 'move'), {element: this.container})
+ this.on('dragend',(e)=>this.onTouch(e, 'stop'), {element: this.container})
+ }
+
+ }
+
+ onTouch(e, name) {
+
+ var event = {...e}
+
+ event.type = name
+
+ this.scripts.onTouch.run({
+ value: this.value,
+ event: event
+ }, {sync: true, send: true})
+
+ }
+
+ get value() {
+
+ switch (this.getProp('mode')) {
+ case 'toggle':
+ if (this.getProp('decoupled')) {
+ if (this.localSet) {
+ // return requested value
+ return this.getProp(this.decoupledValue.value ? 'off' : 'on')
+ } else {
+ // return feedback value
+ return this.getProp(this.decoupledValue.value ? 'on' : 'off')
+ }
+ } else {
+ return this.getProp(this.state ? 'on' : 'off')
+ }
+ case 'push':
+ if (this.getProp('decoupled')) {
+ if (this.localSet) {
+ // return requested value
+ return this.getProp(this.touchActive ? 'on' : 'off')
+ } else {
+ // return feedback value
+ return this.getProp(this.decoupledValue.value ? 'on' : 'off')
+ }
+ } else {
+ return this.getProp(this.state ? 'on' : 'off')
+ }
+ case 'tap':
+ if (this.localSet || !this.getProp('decoupled')) {
+ return this.getProp('on')
+ } else {
+ return this.getProp(this.decoupledValue.value ? 'on' : 'off')
+ }
+ case 'momentary':
+ if (this.localSet || !this.getProp('decoupled')) {
+ return null
+ } else {
+ return this.getProp(this.decoupledValue.value ? 'on' : 'off')
+ }
+ default:
+ return null
+ }
+
+ }
+
+ setValue(v, options={}) {
+
+ if (typeof v === 'string' && isJSON(v)) {
+ try {
+ v = JSON.parse(v)
+ } catch (err) {}
+ }
+
+ var newstate,
+ mode = this.getProp('mode')
+
+ if (deepEqual(v, this.getProp('on'))) {
+
+ newstate = 1
+
+ } else if (deepEqual(v, this.getProp('off'))) {
+
+ newstate = 0
+
+ } else if (mode === 'momentary' && (v === null || v === undefined)) {
+ newstate = 1
+
+ }
+
+ if (newstate !== undefined) {
+
+ this.parsersLocalScope.external = !!options.fromExternal
+
+ if (this.getProp('decoupled')) {
+
+ if (options.fromExternal) {
+ this.state = newstate
+ this.decoupledValue.setValue(newstate, {sync: true})
+ } else if (!options.local && this.getProp('mode') === 'push') {
+ if (newstate === 1 && !this.touchActive) {
+ this.touchActive = 1
+ setTimeout(()=>{this.touchActive = 0})
+ } else {
+ this.touchActive = 0
+ }
+ }
+
+ } else {
+
+ this.state = newstate
+
+ if (mode === 'toggle' || mode === 'push') {
+ this.container.classList.toggle('on', this.state)
+ }
+
+ }
+
+
+ if (options.local || !options.fromExternal) this.localSet = true
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ if (options.local || !options.fromExternal) this.localSet = false
+
+ // tap mode
+ if (newstate && (mode === 'momentary' || mode === 'tap') && !options.tapRelease) {
+
+ // reset value
+ if (mode === 'tap') this.setValue(this.getProp('off'), {sync: false, send: false, tapRelease: true})
+
+ // pulse
+ clearTimeout(this.pulseIn)
+ clearTimeout(this.pulseOut)
+
+ this.container.classList.remove('pulse')
+
+ if (this.getProp('decoupled') && options.fromExternal) return
+
+ this.pulseIn = setTimeout(()=>{
+ this.container.classList.add('pulse')
+ this.pulseOut = setTimeout(()=>{
+ this.container.classList.remove('pulse')
+ }, 150)
+ }, 16)
+
+ }
+
+ }
+
+
+
+ }
+
+ updateLabel() {
+
+ if (!this.label) return
+
+ if (this.getProp('label') === false) {
+
+ if (this.widget.contains(this.label)) this.widget.removeChild(this.label)
+
+ } else {
+ this.label.innerHTML = this.getProp('label') == 'auto'?
+ this.getProp('id'):
+ iconify(String(this.getProp('label')).replace(/{
+ this.on('change', (e)=>{
this.setValue(this.values[this.select.selectedIndex], {sync:true, send:true, fromLocal:true})
- })
+ }, {element: this.select})
+
+ this.on('fast-click', (e)=>{
+ // allow resubmitting same value
+ this.select.selectedIndex = -1
+ }, {element: this.select})
+
this.select.selectedIndex = -1
this.selected = -1
@@ -84,7 +92,7 @@ class Dropdown extends MenuBase {
this.value = this.values[i]
- if (!options.fromLocal) this.select.selectedIndex = i
+ this.select.selectedIndex = i
this.selected = i
this.setLabel()
@@ -94,6 +102,10 @@ class Dropdown extends MenuBase {
this.select.blur()
}
+ for (var j = 0; j < this.select.options.length; j++) {
+ this.select.options[j].classList.toggle('on', i === j)
+ }
+
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
@@ -107,9 +119,10 @@ class Dropdown extends MenuBase {
case 'values':
this.parseValues()
- this.setValue(this.value)
return
-
+ case 'label':
+ this.setLabel()
+ return
}
return ret
@@ -119,8 +132,9 @@ class Dropdown extends MenuBase {
}
Dropdown.dynamicProps = Dropdown.prototype.constructor.dynamicProps.concat(
- 'values'
+ 'values',
+ 'label'
)
-module.exports = Dropdown
+export default Dropdown
diff --git a/src/client/widgets/basics/file.js b/src/client/widgets/basics/file.mjs
similarity index 54%
rename from src/client/widgets/basics/file.js
rename to src/client/widgets/basics/file.mjs
index d05f369d..61bb427c 100644
--- a/src/client/widgets/basics/file.js
+++ b/src/client/widgets/basics/file.mjs
@@ -1,8 +1,9 @@
-var Widget = require('../common/widget'),
- html = require('nanohtml'),
- uiFilebrowser = require('../../ui/ui-filebrowser')
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import uiFilebrowser from '../../ui/ui-filebrowser.mjs'
+import {DOM} from '../../globals.mjs'
-module.exports = class File extends Widget {
+export default class File extends Widget {
static description() {
@@ -17,10 +18,12 @@ module.exports = class File extends Widget {
_separator_file_style: 'File style',
align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
hidePath: {type: 'boolean', value: false, help: 'Set to `true` to only display the filename (the whole path will still be used as value)'},
+ mode: {type: 'string', value: 'open', choices: ['open', 'save'], help: 'File browser mode'},
+ click: {type: 'boolean', value: false, help: 'Set to `true` to activate upon click event instead of tap'},
},
class_specific: {
directory: {type: 'string', value: 'auto', help: 'Default browsing directory'},
- extension: {type: 'string', value: '*', help: 'Only display files with this extension'},
+ extension: {type: 'string|array', value: '*', help: 'Only display files with this extension. Multiple extensions can be specified with an array of strings (`["jpg", "jpeg"]`)'},
allowDir: {type: 'boolean', value: false, help: 'Allow selecting a folder (by pressing "open" when no file is selected)'}
}
})
@@ -38,25 +41,41 @@ module.exports = class File extends Widget {
if (this.getProp('align') === 'left') this.widget.classList.add('left')
if (this.getProp('align') === 'right') this.widget.classList.add('right')
+ if (this.getProp('mode') === 'save') this.widget.classList.add('save')
+ if (this.getProp('hidePath')) this.widget.classList.add('hide-path')
this.text = DOM.get(this.widget, '.text')[0]
- this.widget.addEventListener('fast-click', (e)=>{
+ this.lastDir = null
+
+ var ext = this.getProp('extension')
+ if (Array.isArray(ext)) {
+ ext = '(' + ext.join('|') + ')'
+ }
+
+ this.on(this.getProp('click') ? 'click' : 'fast-click', (e)=>{
if (e.capturedByEditor === true) return
uiFilebrowser({
- extension: this.getProp('extension').replace(/^\.?(.*)$/, '$1'),
- directory: this.getProp('directory') === 'auto' ? undefined : this.getProp('directory'),
- loadDir: this.getProp('allowDir')
- }, (path)=>{
+ extension: ext.replace(/^\.?(.*)$/, '$1'),
+ directory: this.getProp('directory') === 'auto' ? this.lastDir : this.getProp('directory'),
+ loadDir: this.getProp('allowDir'),
+ save: this.getProp('mode') === 'save'
+ }, (path, root)=>{
- this.setValue(path.join(path[0][0] === '/' ? '/' : '\\'), {
+ var sep = path[0][0] === '/' ? '/' : '\\',
+ val = path.join(sep)
+ if (root) val = val.replace(root, sep).replace(sep + sep, sep)
+
+ this.setValue(val, {
sync: true,
send: true
})
+ }, (path)=>{
+ this.lastDir = path
})
- })
+ }, {element: this.widget})
}
@@ -65,8 +84,8 @@ module.exports = class File extends Widget {
this.value = v
- var sep = v[0] === '/' ? '/' : '\\'
- if (this.getProp('hidePath')) {
+ if (this.getProp('hidePath') && typeof v === 'string') {
+ var sep = v[0] === '/' ? '/' : '\\'
if (v[v.length - 1] === sep) {
this.text.textContent = v.substr(0, v.length - 1).split(sep).pop() + sep
} else {
diff --git a/src/client/widgets/basics/input.js b/src/client/widgets/basics/input.mjs
similarity index 50%
rename from src/client/widgets/basics/input.js
rename to src/client/widgets/basics/input.mjs
index d38532bc..ffc89619 100644
--- a/src/client/widgets/basics/input.js
+++ b/src/client/widgets/basics/input.mjs
@@ -1,6 +1,6 @@
-var Canvas = require('../common/canvas'),
- {deepCopy} = require('../../utils'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import Canvas from '../common/canvas.mjs'
+import {deepCopy} from '../../utils.mjs'
class Input extends Canvas {
@@ -17,17 +17,25 @@ class Input extends Canvas {
_separator_input_style: 'Input style',
align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
unit: {type: 'string', value: '', help: 'Unit will be appended to the displayed widget\'s value (it doesn\'t affect osc messages)'},
+ noCanvas: {type: 'boolean', value: false, help: [
+ 'Set to `true` to not a use a canvas for rendering the value when not focused.',
+ 'Use this if the text renders blurry (less effecient when updating the value frequently).'
+ ]},
},
class_specific: {
asYouType: {type: 'boolean', value: false, help: 'Set to `true` to make the input send its value at each keystroke'},
+ numeric: {type: 'boolean|number', value: false, help: [
+ 'Set to `true` to allow numeric values only and display a numeric keyboard on mobile devices',
+ 'Can be a number to specify the stepping value for mousewheel interaction (only when the input is focused).']},
validation: {type: 'string', value: '', help: [
'Regular expression: if the submitted value doesn\'t match the regular expression, it will be reset to the last valid value.',
'If leading and trailing slashes are omitted, they will be added automatically and the flag will be set to "gm"',
'Examples:',
'- `^[0-9]*$` accepts digits only, any number of them',
'- `/^[a-z\s]{0,10}$/i` accept between 0 and 10 alphabetic characters and spaces (case insensitive)',
- ]}
- }
+ ]},
+ maxLength: {type: 'number', value: '', help: ['Maximum number of characters allowed']}
+ },
})
}
@@ -43,46 +51,64 @@ class Input extends Canvas {
this.value = ''
this.stringValue = ''
this.focused = false
- this.tabKeyBlur = false
this.validation = null
+ this.useCanvas = !this.getProp('noCanvas')
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')
+ this.input = html``
+
+ if (!this.useCanvas) {
+ this.widget.insertBefore(this.input, this.canvas)
+ }
+
+ if (this.getProp('numeric')) {
+ this.input.type = 'number'
+ this.input.pattern = '[0-9\.]*'
+ this.input.inputMode = 'decimal'
+ this.input.step = parseFloat(this.getProp('numeric')) || 1
+ }
+
+ if (this.getProp('maxLength') !== '') {
+ this.maxLength = parseInt(this.getProp('maxLength'))
+ this.input.maxLength = this.maxLength
+ } else {
+ this.maxLength = -1
+ }
+
+ var asYouType = this.getProp('asYouType')
+
+ if (this.getProp('validation') !== '') {
+ var validation = String(this.getProp('validation')),
+ flags = validation.match(/^\/.*\/.*$/) ? validation.split('/').pop() : 'gm',
+ regExpString = validation.match(/^\/.*\/.*$/) ? validation.replace(/^\/(.*)\/.*$/, '$1') : validation
+
+ if (!regExpString.match(/^\^.*\$$/)) regExpString = '^' + regExpString + '$'
+
+ this.validation = new RegExp(regExpString, flags)
+ }
if (this.getProp('interaction')) {
- this.widget.setAttribute('tabindex', 0)
- this.widget.addEventListener('focus', this.focus.bind(this))
- this.input = html``
- this.input.addEventListener('blur', (e)=>{
- this.blur(this.tabKeyBlur)
- this.tabKeyBlur = false
- })
- var asYouType = this.getProp('asYouType')
-
- if (this.getProp('validation') !== '') {
- var validation = String(this.getProp('validation')),
- flags = validation.match(/^\/.*\/.*$/) ? validation.split('/').pop() : 'gm',
- regExpString = validation.match(/^\/.*\/.*$/) ? validation.replace(/^\/(.*)\/.*$/, '$1') : validation
-
- if (!regExpString.match(/^\^.*\$$/)) regExpString = '^' + regExpString + '$'
-
- this.validation = new RegExp(regExpString, flags)
+ if (this.useCanvas) {
+ this.widget.setAttribute('tabindex', 0)
}
+ this.on('focus', this.focus.bind(this), {element: this.widget})
+ this.on('blur', (e)=>{
+ this.blur(true)
+ }, {element: this.input})
this.input.addEventListener('keydown', (e)=>{
- if (e.keyCode === 13) this.blur() // enter
- else if (e.keyCode === 27) this.blur(false) // esc
- else if (e.keyCode === 9) this.tabKeyBlur = true // tab
+ if (e.key == 'Enter') this.blur()
+ else if (e.key == 'Escape') this.blur(false)
else if (asYouType) {
setTimeout(()=>{
this.inputChange()
})
}
})
-
}
}
@@ -92,11 +118,17 @@ class Input extends Canvas {
if (this.focused) return
this.focused = true
- this.widget.setAttribute('tabindex','-1')
- this.input.value = this.stringValue
- this.widget.insertBefore(this.input, this.canvas)
- this.input.focus()
- this.input.setSelectionRange(0, this.input.value.length)
+ if (this.useCanvas) {
+ this.widget.insertBefore(this.input, this.canvas)
+ this.widget.setAttribute('tabindex','-1')
+ this.input.value = this.stringValue
+ this.input.focus()
+ }
+
+
+ setTimeout(()=>{
+ this.input.select()
+ })
}
@@ -107,9 +139,12 @@ class Input extends Canvas {
if (change) this.inputChange()
- this.widget.setAttribute('tabindex','0')
- this.widget.removeChild(this.input)
-
+ if (this.useCanvas) {
+ this.widget.removeChild(this.input)
+ this.widget.setAttribute('tabindex','0')
+ } else {
+ this.input.blur()
+ }
}
inputChange() {
@@ -118,23 +153,22 @@ class Input extends Canvas {
}
+
+ cacheCanvasStyle(style){
+
+ if (!this.useCanvas) return
+
+ super.cacheCanvasStyle(style)
+
+ }
+
+
resizeHandle(event){
+ if (!this.useCanvas) return
+
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={} ) {
@@ -144,6 +178,11 @@ class Input extends Canvas {
return
}
+ if (this.maxLength !== -1 && this.getStringValue(v).length > this.maxLength) {
+ v = this.getStringValue(v).substr(0, this.maxLength)
+ this.input.value = v
+ }
+
try {
this.value = JSON.parse(v)
} catch (err) {
@@ -153,7 +192,12 @@ class Input extends Canvas {
if (this.value === '' || this.value === null) this.value = this.getProp('default')
this.stringValue = this.getStringValue(this.value)
- this.batchDraw()
+
+ if (this.useCanvas) {
+ this.batchDraw()
+ } else {
+ this.input.value = this.stringValue
+ }
if (options.send && !options.fromSync) this.sendValue()
if (options.sync) this.changed(options)
@@ -162,6 +206,8 @@ class Input extends Canvas {
draw() {
+ if (!this.useCanvas) return
+
var v = this.stringValue,
width = this.width,
height = this.height
@@ -172,12 +218,15 @@ class Input extends Canvas {
this.ctx.fillStyle = this.cssVars.colorText
+ // hack ? prevent weird offset added for unknown reason when font size increases
+ var offy = this.fontSize / 10
+
if (this.textAlign == 'center') {
- this.ctx.fillText(v, Math.round(width/2), Math.round(height/2))
+ this.ctx.fillText(v, Math.round(width/2), Math.round(height/2 + offy))
} else if (this.textAlign == 'right') {
- this.ctx.fillText(v, width, Math.round(height/2))
+ this.ctx.fillText(v, width, Math.round(height/2 + offy))
} else {
- this.ctx.fillText(v, 0, Math.round(height/2))
+ this.ctx.fillText(v, 0, Math.round(height/2 + offy))
}
this.clearRect = [0, 0, width, height]
@@ -197,4 +246,4 @@ Input.dynamicProps = Input.prototype.constructor.dynamicProps
.filter(x=>x !== 'interaction')
-module.exports = Input
+export default Input
diff --git a/src/client/widgets/basics/menu-base.js b/src/client/widgets/basics/menu-base.js
deleted file mode 100644
index 1a980668..00000000
--- a/src/client/widgets/basics/menu-base.js
+++ /dev/null
@@ -1,62 +0,0 @@
-var Widget = require('../common/widget'),
- {iconify} = require('../../ui/utils'),
- {deepEqual} = require('../../utils')
-
-class MenuBase extends Widget {
-
- constructor(options) {
-
- super(options)
-
- this.value = undefined
- this.values = []
- this.keys = []
- this.objectInValues = false
-
- }
-
- parseValues() {
-
- this.values = []
- this.keys = []
-
- var values = this.getProp('values') || []
-
- if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
- values = values !== '' ? [values] : []
- }
-
- this.values = !Array.isArray(values) ? Object.values(values) : values
- this.keys = !Array.isArray(values) ? Object.keys(values) : this.values
- this.objectInValues = this.values.some(x=>typeof x === 'object')
-
- }
-
- getIndex(value) {
-
- var index = this.values.indexOf(value)
- if (index === -1 && this.objectInValues) {
- for (var i = 0; i < this.values.length; i++) {
- if (deepEqual(value, this.values[i])) return i
- }
- }
- return index
-
- }
-
- setLabel() {
-
- var string = this.getProp('label') === 'auto' ? '%value' : this.getProp('label'),
- i = this.selected
-
- if (i > -1 && string) {
- this.text.innerHTML = iconify(String(string).replace(/%value/g, JSON.stringify(this.value)).replace(/%key/g, this.keys[i]))
- } else {
- this.text.innerHTML = ''
- }
-
- }
-
-}
-
-module.exports = MenuBase
diff --git a/src/client/widgets/basics/menu-base.mjs b/src/client/widgets/basics/menu-base.mjs
new file mode 100644
index 00000000..c5eadf08
--- /dev/null
+++ b/src/client/widgets/basics/menu-base.mjs
@@ -0,0 +1,76 @@
+import Widget from '../common/widget.mjs'
+import {iconify} from '../../ui/utils.mjs'
+import {deepEqual} from '../../utils.mjs'
+
+class MenuBase extends Widget {
+
+ constructor(options) {
+
+ super(options)
+
+ this.value = undefined
+ this.values = []
+ this.keys = []
+ this.objectInValues = false
+
+ }
+
+ parseValues() {
+
+ this.values = []
+ this.keys = []
+
+ var values = this.getProp('values') || []
+
+ if (
+ typeof values === 'object' && values !== null &&
+ Array.isArray(values.labels) && Array.isArray(values.values) &&
+ Object.keys(values).length === 2 && values.labels.length === values.values.length
+ ) {
+
+ this.values = values.values
+ this.keys = values.labels
+
+ } else {
+
+ if (!Array.isArray(values) && !(typeof values === 'object' && values !== null)) {
+ values = values !== '' ? [values] : []
+ }
+
+ this.values = !Array.isArray(values) ? Object.values(values) : values
+ this.keys = !Array.isArray(values) ? Object.keys(values) : this.values
+ }
+
+ this.objectInValues = this.values.some(x=>typeof x === 'object')
+
+ }
+
+ getIndex(value) {
+
+ var index = this.values.indexOf(value)
+ if (index === -1 && this.objectInValues) {
+ for (var i = 0; i < this.values.length; i++) {
+ if (deepEqual(value, this.values[i])) return i
+ }
+ }
+ return index
+
+ }
+
+ setLabel() {
+
+ var string = this.getProp('label') === 'auto' ? '%value' : this.getProp('label'),
+ i = this.selected
+
+
+ if (i > -1 && string) {
+ this.text.innerHTML = iconify(String(string).replace(/%value/g, typeof this.value === 'string' ? this.value : JSON.stringify(this.value)).replace(/%key/g, this.keys[i]))
+ } else {
+ this.text.innerHTML = iconify(String(string).replace(/%value/g, '').replace(/%key/g, ''))
+ }
+
+ }
+
+}
+
+export default MenuBase
diff --git a/src/client/widgets/basics/menu.js b/src/client/widgets/basics/menu.mjs
similarity index 77%
rename from src/client/widgets/basics/menu.js
rename to src/client/widgets/basics/menu.mjs
index 9aaf17ac..dd9a6e43 100644
--- a/src/client/widgets/basics/menu.js
+++ b/src/client/widgets/basics/menu.mjs
@@ -1,8 +1,10 @@
-var MenuBase = require('./menu-base'),
- {iconify} = require('../../ui/utils'),
- doubletab = require('../mixins/double_tap'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import MenuBase from './menu-base.mjs'
+import {iconify} from '../../ui/utils.mjs'
+import doubleTap from '../mixins/double_tap'
+import iOS from '../../ui/ios.mjs'
+import {DOM} from '../../globals.mjs'
class Menu extends MenuBase {
@@ -21,6 +23,8 @@ class Menu extends MenuBase {
'- If `layout` is `circular`: diameter (in px)',
'- Else: square size or `[width, height]` array',
]},
+ ignoreTabs: {type: 'boolean', value: false, help: 'Set to `true` to allow the menu overflowing its tab ancestors.'},
+
},
style: {
_separator_menu_style: 'Menu style',
@@ -29,17 +33,24 @@ class Menu extends MenuBase {
textAlign: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change text alignment (otherwise center)'},
menuAlignV: {type: 'string', value: 'center', choices: ['center', 'top', 'bottom'], help: 'Set to `top` or `bottom` to change menu alignment (otherwise center)'},
menuAlignH: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Set to `left` or `right` to change menu alignment (otherwise center)'},
- layout: {type: 'string', value: 'circular', choices: ['circular', 'horizontal', 'vertical', 'grid'], help: [
- 'Defines whether the menu\'s layout should be rendered in a circle or in a box'
+ layout: {type: 'string', value: 'vertical', choices: ['circular', 'horizontal', 'vertical', 'grid'], help: [
+ 'Defines how the menu\'s item are laid out'
]},
- gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns or a valid value for the css property "grid-template".'},
},
class_specific: {
- toggle: {type: 'boolean', value: false, help: 'Set to `true` to make the menu stay opened after mouse/touch release'},
- doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the menu require a double tap to be opened instead of a single tap'},
+ mode: {type: 'string', value: 'default', choices: ['default', 'toggle', 'swipe', 'doubleTap', 'doubleTap-toggle'], help: [
+ 'Interaction modes:',
+ '- `default`: opens on touch, closes and changes value on release',
+ '- `toggle`: opens on click, closes and changes value on next click',
+ '- `swipe`: opens on touch, changes value when the pointer moves above items, closes on release',
+ '- `doubleTap`: same as `default` but opens on double tap',
+ '- `doubleTap-toggle`: same as `toggle` but opens on double tap',
+ ]},
values: {type: 'array|object', value: [1, 2, 3], help: [
'`Array` of possible values to switch between : `[1,2,3]`',
'`Object` of label:value pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ '`{"labels": [], "values": []}` `object` where `labels` and `values` arrays must be of the same length. This syntax allows using the same label for different values.',
]},
weights: {type: 'array', value: '', help: [
'`Array` of `number` defining the weights of each value in `values`',
@@ -76,32 +87,35 @@ class Menu extends MenuBase {
this.selected = -1
+ this.mode = String(this.getProp('mode'))
+
this.parseValues()
- if (this.getProp('doubleTap')) {
+ if (this.mode.includes('doubleTap')) {
- doubletab(this.widget, (e)=>{
+ doubleTap(this, (e)=>{
if (this.opened) return
this.open(e)
- })
+ }, {element: this.widget, click: this.mode.includes('toggle')})
this.on('draginit',(e)=>{
- if (this.opened && this.getProp('toggle')) {
+ if (this.opened && this.mode.includes('toggle')) {
this.selectValue(e)
this.submitValue()
}
- }, {element: this.widget})
+ // multitouch is only needed for iOS which fails otherwise
+ }, {element: this.widget, multitouch: iOS})
} else {
- this.on('draginit',(e)=>{
+ this.on(this.mode.includes('toggle') ? 'click' : 'draginit',(e)=>{
- if (this.opened && this.getProp('toggle')) {
+ if (this.opened && this.mode.includes('toggle')) {
this.selectValue(e)
this.submitValue()
@@ -112,22 +126,30 @@ class Menu extends MenuBase {
}
- }, {element: this.widget})
+ }, {element: this.widget, multitouch: iOS})
+
}
- if (!this.getProp('toggle')) {
+ if (!this.mode.includes('toggle')) {
this.on('drag',(e)=>{
this.selectValue(e, true)
+ if (this.mode === 'swipe' && this.values[this.selected] !== this.value) {
+ this.submitValue()
+ }
}, {element: this.widget})
this.on('dragend',()=>{
if (!this.opened) return
- this.submitValue()
+ if (this.mode === 'swipe') {
+ this.close()
+ } else {
+ this.submitValue()
+ }
}, {element: this.widget})
@@ -189,7 +211,7 @@ class Menu extends MenuBase {
submitValue(e) {
- this.close()
+ if (this.mode !== 'swipe') this.close()
if (this.selected > -1) {
this.setValue(this.values[this.selected], {send: true, sync: true})
}
@@ -242,6 +264,7 @@ class Menu extends MenuBase {
this.container.classList.toggle('circular', layout === 'circular')
this.container.classList.toggle('grid', layout === 'grid')
this.container.classList.toggle('vertical', layout === 'vertical')
+ this.container.classList.toggle('horizontal', layout === 'horizontal')
if (layout === 'grid') {
var template = this.getProp('gridTemplate') || Math.round(this.values.length / 2)
@@ -270,9 +293,10 @@ class Menu extends MenuBase {
var parent = this.parent,
scrollX = 0,
- scrollY = 0
+ scrollY = 0,
+ stop = this.getProp('ignoreTabs') ? /root/ : /root|tab/
- while (parent && parent.props && !parent.getProp('type').match(/tab|root/)) {
+ while (parent && parent.props && !String(parent.getProp('type')).match(stop)) {
parent.modalBreakout += (this.opened ? 1 : -1)
if (parent.modalBreakout > 0) parent.container.classList.add('modal-breakout')
@@ -297,17 +321,15 @@ class Menu extends MenuBase {
var i = this.getIndex(v)
+ this.value = this.values[i]
+ this.selected = i
+ DOM.each(this.menu, '.on', (el)=>{el.classList.remove('on')})
+ this.setLabel()
+
if (i !== -1) {
- this.value = this.values[i]
- this.selected = i
- DOM.each(this.menu, '.on', (el)=>{el.classList.remove('on')})
DOM.get(this.menu, '.item')[i].classList.add('on')
-
- this.setLabel()
-
}
-
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
@@ -365,4 +387,4 @@ Menu.dynamicProps = Menu.prototype.constructor.dynamicProps.concat(
)
-module.exports = Menu
+export default Menu
diff --git a/src/client/widgets/basics/switch.js b/src/client/widgets/basics/switch.mjs
similarity index 59%
rename from src/client/widgets/basics/switch.js
rename to src/client/widgets/basics/switch.mjs
index 8a4ea615..88d12f31 100644
--- a/src/client/widgets/basics/switch.js
+++ b/src/client/widgets/basics/switch.mjs
@@ -1,7 +1,8 @@
-var MenuBase = require('./menu-base'),
- {iconify} = require('../../ui/utils'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import MenuBase from './menu-base.mjs'
+import {iconify} from '../../ui/utils'
+import {DOM} from '../../globals.mjs'
class Switch extends MenuBase {
@@ -18,18 +19,23 @@ class Switch extends MenuBase {
_separator_switch_style: 'Switch style',
colorTextOn: {type: 'string', value: 'auto', help: 'Defines the widget\'s text color when active.'},
layout: {type: 'string', value: 'vertical', choices: ['vertical', 'horizontal', 'grid'], help:'Defines how items should be laid out'},
- gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns or a valid value for the css property "grid-template".'},
+ wrap: {type: 'boolean|string', value: false, choices: [false, true, 'soft'], help: [
+ 'Set to `true` to wrap long lines automatically. Set to `soft` to avoid breaking words.',
+ ]},
},
class_specific: {
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',
+ '`{"labels": [], "values": []}` `object` where `labels` and `values` arrays must be of the same length. This syntax allows using the same label for different values.',
]},
- mode: {type: 'string', value: 'tap', choices: ['tap', 'slide', 'click'], help: [
- 'Interraction mode:',
+ mode: {type: 'string', value: 'tap', choices: ['tap', 'slide', 'click', 'flip'], help: [
+ 'Interaction mode:',
'- `tap`: activates when the pointer is down but prevents further scrolling',
'- `slide`: same as `tap` but allows sliding between values',
'- `click`: activates upon click only and allows further scrolling',
+ '- `flip`: selects the next value upon click regardless of where the widget is touched',
]},
}
})
@@ -41,6 +47,8 @@ class Switch extends MenuBase {
super({...options, html: html` `})
this.container.classList.add('layout-' + this.getProp('layout'))
+ if (this.getProp('wrap')) this.container.classList.add('wrap')
+ if (this.getProp('wrap') === 'soft') this.container.classList.add('wrap-soft')
if (this.getProp('layout') === 'grid') {
var template = this.getProp('gridTemplate') || 2
@@ -50,12 +58,16 @@ class Switch extends MenuBase {
this.parseValues()
- var dragCallback = (e, touchFix)=>{
+ var dragCallback = (e, slide)=>{
var index = 0,
node = e.target
- if (touchFix && e.isTouch) {
+ if (e.target === this.widget && e.traversing === true && e.firstTarget) {
+ node = e.firstTarget
+ }
+
+ if (slide && e.isTouch) {
// special traversing touch fix
node = document.elementFromPoint(e.clientX, e.clientY)
}
@@ -70,7 +82,9 @@ class Switch extends MenuBase {
var value = this.values[index]
- if (value !== this.value || this.value === undefined) this.setValue(value, {sync: true, send: true})
+ if (slide && value === this.value) return
+
+ this.setValue(value, {sync: true, send: true})
}
@@ -79,9 +93,13 @@ class Switch extends MenuBase {
this.on('drag', (e)=>{
if (this.getProp('mode') === 'slide' || e.traversing) dragCallback(e, true)
} , {element: this.widget})
- } else {
- this.widget.addEventListener('click', dragCallback)
-
+ } else if (this.getProp('mode') === 'click') {
+ this.on('click', dragCallback, {element: this.widget})
+ } else if (this.getProp('mode') === 'flip') {
+ this.on('click', ()=>{
+ var i = (this.getIndex(this.value) + 1) % this.values.length
+ this.setValue(this.values[i], {sync: true, send: true})
+ }, {element: this.widget})
}
}
@@ -90,6 +108,8 @@ class Switch extends MenuBase {
super.parseValues()
+ this.widget.innerHTML = ''
+
for (var i = 0; i < this.values.length; i++) {
this.widget.appendChild(html`
@@ -98,26 +118,40 @@ class Switch extends MenuBase {
}
+ this.setValue(this.value)
+
}
setValue(v, options={}) {
var i = this.getIndex(v)
+ this.value = this.values[i]
+
+ DOM.each(this.widget, '.on', (el)=>{el.classList.remove('on')})
if (i !== -1) {
-
- this.value = this.values[i]
-
- DOM.each(this.widget, '.on', (el)=>{el.classList.remove('on')})
DOM.get(this.widget, 'value')[i].classList.add('on')
-
- if (options.send) this.sendValue(this.value)
- if (options.sync) this.changed(options)
}
+ if (options.send) this.sendValue(this.value)
+ if (options.sync) this.changed(options)
+
}
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+
+ case 'values':
+ this.parseValues()
+ }
+
+ return ret
+
+ }
setCssVariables() {
super.setCssVariables()
@@ -127,8 +161,12 @@ class Switch extends MenuBase {
}
}
+Switch.dynamicProps = Switch.prototype.constructor.dynamicProps.concat(
+ 'values'
+)
+
Switch.cssVariables = Switch.prototype.constructor.cssVariables.concat(
{js: 'colorTextOn', css: '--color-text-on'}
)
-module.exports = Switch
+export default Switch
diff --git a/src/client/widgets/basics/textarea.mjs b/src/client/widgets/basics/textarea.mjs
new file mode 100644
index 00000000..0e426827
--- /dev/null
+++ b/src/client/widgets/basics/textarea.mjs
@@ -0,0 +1,119 @@
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import {DOM} from '../../globals.mjs'
+
+class TextArea extends Widget {
+
+ static description() {
+
+ return 'Text area (multi line input). Tip: hit shift + enter for new lines.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults().extend({
+ style: {
+ // _separator_input_style: 'Textarea style',
+ },
+ class_specific: {
+
+ },
+ })
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.value = ''
+ this.stringValue = ''
+ this.focused = false
+ this.validation = null
+ this.input = DOM.get(this.widget, 'textarea')[0]
+
+ if (this.getProp('align') === 'left') this.widget.classList.add('left')
+ if (this.getProp('align') === 'right') this.widget.classList.add('right')
+
+
+ if (this.getProp('interaction')) {
+
+ this.input.setAttribute('tabindex', 0)
+ this.on('focus', this.onFocus.bind(this), {element: this.input})
+ this.on('blur', (e)=>{
+ this.blur(true)
+ }, {element: this.input})
+
+ this.input.addEventListener('keydown', (e)=>{
+ if (e.key == 'Enter' && !e.shiftKey) {
+ // enter
+ e.preventDefault()
+ this.blur()
+ }
+ else if (e.key == 'Escape') {
+ // esc
+ this.blur(false)
+ this.input.value = this.value
+ }
+ })
+
+ }
+
+ }
+
+ onFocus() {
+
+ if (this.focused) return
+ this.focused = true
+
+ }
+
+ focus() {
+
+ this.input.focus()
+
+ }
+
+ blur(change=true) {
+
+ if (!this.focused) return
+ this.focused = false
+
+ this.input.blur()
+
+ if (change) this.inputChange()
+
+ }
+
+ inputChange() {
+
+ this.setValue(this.input.value, {sync:true, send:true})
+
+ }
+
+
+ setValue(v, options={} ) {
+
+ this.value = v === '' || v === null ? this.getProp('default') : String(v)
+
+ if (this.value === '') this.value = this.getProp('default')
+
+ if (this.input.value !== this.value) this.input.value = this.value
+
+ if (options.send && !options.fromSync) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ }
+
+}
+
+TextArea.dynamicProps = TextArea.prototype.constructor.dynamicProps
+ .filter(x=>x !== 'interaction')
+
+
+export default TextArea
diff --git a/src/client/widgets/common/canvas.js b/src/client/widgets/common/canvas.js
deleted file mode 100644
index 6c7194f1..00000000
--- a/src/client/widgets/common/canvas.js
+++ /dev/null
@@ -1,181 +0,0 @@
-var Widget = require('./widget'),
- resize = require('../../events/resize'),
- canvasQueue = require('./queue')
-
-
-class Canvas extends Widget {
-
- constructor(options) {
-
- super(options)
-
- this.canvas = DOM.get(this.container, 'canvas')[0]
-
- this.ctx = this.canvas.getContext('2d',{
- desynchronized: !ELECTRON_NOGPU && ENV.desyncCanvas ? true : false,
- alpha: true
- })
-
- this.height = undefined
- this.width = undefined
- this.scaling = 1
-
- this.clearRect = []
-
- this.hasSize = false
-
- this.colors = {}
- this.cssVars = {}
-
- this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
-
- this.ctx.arc = (x, y, r, s, e, c)=>{
-
- this.ctx.__proto__.arc.call(this.ctx, x, y, Math.max(0,r), s, e, c)
-
- }
-
- }
-
- resizeHandleProxy() {
-
- this.resizeHandle(...arguments)
-
- }
-
- resizeHandle(event){
-
- var {width, height, style} = event,
- ratio = CANVAS_SCALING * this.scaling
-
- this.height = height
- this.width = width
-
- this.canvas.setAttribute('width', width * ratio)
- this.canvas.setAttribute('height', height * ratio)
-
- this.clearRect = []
-
- if (ratio != 1) {
- this.ctx.setTransform(1, 0, 0, 1, 0, 0)
- this.ctx.scale(ratio, ratio)
- }
-
- this.cacheCanvasStyle(style)
-
- if (!this.hasSize) {
- this.hasSize = true
- this.setVisibility()
- }
-
- this.batchDraw()
-
- }
-
- cacheCanvasStyle(style){
-
- style = style || window.getComputedStyle(this.canvas)
-
-
- for (var data of this.constructor.cssVariables) {
-
- var val = style.getPropertyValue(data.css).trim()
- this.cssVars[data.js] = data.toJs ? data.toJs(val) : val
-
- }
-
- this.fontFamily = style.getPropertyValue('font-family').trim()
- this.textAlign = style.getPropertyValue('text-align').trim()
- this.fontSize = parseFloat(style.getPropertyValue('font-size').trim())
- this.fontWeight = parseFloat(style.getPropertyValue('font-weight').trim())
-
- this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
- this.ctx.textBaseline = 'middle'
- this.ctx.textAlign = this.textAlign
-
- }
-
- clear() {
-
- if (!this.clearRect.length) {
-
- this.ctx.clearRect(0, 0, this.width, this.height)
-
- } else if (typeof this.clearRect[0] == 'object') {
-
- for (let i in this.clearRect) {
- this.ctx.clearRect(...this.clearRect[i])
- }
-
- } else {
-
- this.ctx.clearRect(...this.clearRect)
-
- }
-
- }
-
- isVisible() {
-
- return this.hasSize && super.isVisible()
-
- }
-
- 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 'colorText':
- case 'colorWidget':
- case 'colorFill':
- case 'colorStroke':
- case 'alphaStroke':
- case 'alphaFillOff':
- case 'alphaFillOn':
- case 'colorBg':
- setTimeout(()=>{
- this.cacheCanvasStyle()
- this.batchDraw()
- },10)
- return
- case 'css':
- case 'lineWidth':
- case 'padding':
- resize.check(this.canvas, true)
- setTimeout(()=>{
- this.cacheCanvasStyle()
- this.batchDraw()
- },10)
- return
- }
-
- return ret
-
-
- }
-
- onRemove() {
- this.off('resize')
- super.onRemove()
- }
-
-}
-
-Canvas.cssVariables = Canvas.prototype.constructor.cssVariables.concat(
- {js: 'alphaPips', css: '--alpha-pips', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
- {js: 'alphaPipsText', css: '--alpha-pips-text', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)}
-)
-
-module.exports = Canvas
diff --git a/src/client/widgets/common/canvas.mjs b/src/client/widgets/common/canvas.mjs
new file mode 100644
index 00000000..6f63d34a
--- /dev/null
+++ b/src/client/widgets/common/canvas.mjs
@@ -0,0 +1,253 @@
+import html from 'nanohtml'
+import fastdom from 'fastdom'
+import Widget from './widget.mjs'
+import * as resize from '../../events/resize.mjs'
+import canvasQueue from './queue.mjs'
+import {ENV, CANVAS_SCALING, ELECTRON_NOGPU, DOM} from '../../globals.mjs'
+
+
+class Canvas extends Widget {
+
+ static defaults() {
+
+ var defaults = super.defaults(Canvas)
+ defaults.style.css.help.push(
+ 'Canvas-based widget have their computed width and height available as css variables (read-only):',
+ '- `--widget-width`',
+ '- `--widget-height`',
+ )
+ defaults.scripting.onValue.help.push(
+ 'Canvas-based widget have their computed width and height available as local variables:',
+ '- `locals.width`',
+ '- `locals.height`',
+ )
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.canvas = DOM.get(this.container, 'canvas')[0]
+
+ this.ctx = this.canvas.getContext(this.getProp('contextType') || '2d',{
+ desynchronized: !ELECTRON_NOGPU && ENV.desynccanvas ? true : false,
+ alpha: true
+ })
+
+ this.height = undefined
+ this.width = undefined
+ this.scaling = 1
+
+ this.clearRect = []
+
+ this.hasSize = false
+
+ this.colors = {}
+ this.cssVars = {}
+
+ this.on('resize', this.resizeHandleProxy.bind(this), {element: this.canvas})
+
+ this.ctx.arc = (x, y, r, s, e, c)=>{
+
+ this.ctx.__proto__.arc.call(this.ctx, x, y, Math.max(0,r), s, e, c)
+
+ }
+
+ }
+
+ resizeHandleProxy() {
+
+ fastdom.measure(()=>{
+ this.resizeHandle(...arguments)
+ })
+
+ }
+
+ resizeHandle(event){
+
+ var {width, height, style} = event,
+ ratio = CANVAS_SCALING * this.scaling
+
+ this.height = height
+ this.width = width
+
+ this.parsersLocalScope.height = this.height
+ this.parsersLocalScope.width = this.width
+
+ this.clearRect = []
+
+ this.cacheCanvasStyle(style)
+
+ fastdom.mutate(()=>{
+
+ this.canvas.setAttribute('width', width * ratio)
+ this.canvas.setAttribute('height', height * ratio)
+ this.container.style.setProperty('--widget-height', this.height + 'rem')
+ this.container.style.setProperty('--widget-width', this.width + 'rem')
+
+ this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily
+ this.ctx.textBaseline = 'middle'
+ this.ctx.textAlign = this.textAlign
+
+ if (ratio != 1) {
+ this.ctx.setTransform(1, 0, 0, 1, 0, 0)
+ this.ctx.scale(ratio, ratio)
+ }
+
+ this.extraResizeHandle(event)
+
+ if (!this.hasSize) {
+ this.hasSize = true
+ this.setVisibility()
+ }
+
+ if (this.width > 0 && this.height > 0 && this.visible) {
+ this.draw()
+ }
+
+ })
+
+ }
+
+ extraResizeHandle(event) {
+
+ // to be overridden if subclass needs additional actions
+ // before redraw
+
+ }
+
+ setVisibility(){
+
+ var visible = this.visible
+ super.setVisibility()
+ if (!visible && this.visible) this.batchDraw()
+
+ }
+
+ cacheCanvasStyle(style){
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ for (var data of this.constructor.cssVariables) {
+
+ var val = style.getPropertyValue(data.css).trim()
+
+ if (typeof val === 'string' && val.match(/(var|calc)\(/)) {
+ // property not computed because of calc() or var() in user style
+ // -> attempt to force calculation
+ var dummy = html``
+ this.container.appendChild(dummy)
+ let s = window.getComputedStyle(dummy)
+ val = parseInt(s.getPropertyValue('width'))
+ this.container.removeChild(dummy)
+ }
+
+ this.cssVars[data.js] = data.toJs ? data.toJs(val) : val
+
+
+ }
+
+ this.fontFamily = style.getPropertyValue('font-family').trim()
+ this.textAlign = style.getPropertyValue('text-align').trim()
+ this.fontSize = parseFloat(style.getPropertyValue('font-size').trim())
+ this.fontWeight = parseFloat(style.getPropertyValue('font-weight').trim())
+
+ }
+
+ clear() {
+
+ if (!this.clearRect.length) {
+
+ this.ctx.clearRect(0, 0, this.width, this.height)
+
+ } else if (typeof this.clearRect[0] == 'object') {
+
+ for (let i in this.clearRect) {
+ this.ctx.clearRect(...this.clearRect[i])
+ }
+
+ } else {
+
+ this.ctx.clearRect(...this.clearRect)
+
+ }
+
+ }
+
+ batchDraw() {
+
+ if (this.hasSize && 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 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'colorKnob':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'colorBg':
+ case 'pointSize':
+ case 'knobSize':
+ fastdom.measure(()=>{
+ this.cacheCanvasStyle()
+ fastdom.mutate(()=>{
+ this.batchDraw()
+ })
+ })
+ return
+ case 'css':
+ if (!/\/\*\s*noresize\s*\*\//.test(this.getProp('css'))) resize.check(this.canvas, true)
+ fastdom.measure(()=>{
+ this.cacheCanvasStyle()
+ fastdom.mutate(()=>{
+ this.batchDraw()
+ })
+ })
+ // falls through
+ case 'lineWidth':
+ case 'padding':
+ resize.check(this.canvas, true)
+ fastdom.measure(()=>{
+ this.cacheCanvasStyle()
+ fastdom.mutate(()=>{
+ this.batchDraw()
+ })
+ })
+ return
+ }
+
+ return ret
+
+
+ }
+
+ onRemove() {
+ this.off('resize')
+ this.canvas.width = 0
+ this.canvas.height = 0
+ super.onRemove()
+ }
+
+}
+
+Canvas.cssVariables = Canvas.prototype.constructor.cssVariables.concat(
+ {js: 'alphaPips', css: '--alpha-pips', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
+ {js: 'alphaPipsText', css: '--alpha-pips-text', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)}
+)
+
+export default Canvas
diff --git a/src/client/widgets/common/container.js b/src/client/widgets/common/container.mjs
similarity index 95%
rename from src/client/widgets/common/container.js
rename to src/client/widgets/common/container.mjs
index 22bc36f3..594c4dd3 100644
--- a/src/client/widgets/common/container.js
+++ b/src/client/widgets/common/container.mjs
@@ -1,4 +1,4 @@
-var Widget = require('./widget')
+import Widget from './widget.mjs'
var Container = (Class=Widget)=> class extends Class {
@@ -6,6 +6,8 @@ var Container = (Class=Widget)=> class extends Class {
super(options)
+ this.isContainer = true
+
this.on('widget-created', (e)=>{
if (e.widget.parent === this) {
@@ -72,4 +74,4 @@ var Container = (Class=Widget)=> class extends Class {
}
-module.exports = Container
+export default Container
diff --git a/src/client/widgets/common/osc-receiver.js b/src/client/widgets/common/osc-receiver.mjs
similarity index 76%
rename from src/client/widgets/common/osc-receiver.js
rename to src/client/widgets/common/osc-receiver.mjs
index e5ed93f1..7809355d 100644
--- a/src/client/widgets/common/osc-receiver.js
+++ b/src/client/widgets/common/osc-receiver.mjs
@@ -1,7 +1,8 @@
-var osc = require('../../osc'),
- {isJSON} = require('../../utils')
+import osc from '../../osc.mjs'
+import {isJSON, isJSONObject} from '../../utils.mjs'
+import {JSON5} from '../../globals.mjs'
-module.exports = class OscReceiver {
+export default class OscReceiver {
constructor(options) {
@@ -9,7 +10,7 @@ module.exports = class OscReceiver {
if (typeof value === 'string' && isJSON(value)) {
try {
- this.value = JSON.parseFlex(value)
+ this.value = JSON5.parse(value)
} catch (err) {
this.value = value
}
@@ -20,7 +21,7 @@ module.exports = class OscReceiver {
this.parent = parent
this.propNames = [propName]
this.usePreArgs = usePreArgs
- this.bindedCallback = this.callback.bind(this)
+ this.boundCallback = this.callback.bind(this)
this.prefix = ''
this.setAddress(address)
@@ -30,7 +31,7 @@ module.exports = class OscReceiver {
if (this.address !== address) {
- if (this.address) osc.off(this.prefix + this.address, this.bindedCallback, this.parent)
+ if (this.address) osc.off(this.prefix + this.address, this.boundCallback, this.parent)
if (address) this.address = address
@@ -44,7 +45,7 @@ module.exports = class OscReceiver {
if (this.prefix[this.prefix.length - 1] !== '/') this.prefix += '/'
}
- osc.on(this.prefix + this.address, this.bindedCallback, {context: this.parent})
+ osc.on(this.prefix + this.address, this.boundCallback, {context: this.parent})
}
@@ -56,7 +57,9 @@ module.exports = class OscReceiver {
}
- callback(args) {
+ callback(data) {
+
+ var {args} = data
if (!Array.isArray(args)) args = [args]
var preArgs = this.usePreArgs ? (this.parent.getProp('preArgs') || []) : []
@@ -65,11 +68,12 @@ module.exports = class OscReceiver {
for (var i in preArgs) {
if (preArgs[i] !== args[i]) return
}
+ if (!osc.match(this.parent, data)) return
var value = args.slice(preArgs.length)
if (value.length < 2) value = value[0]
- if (typeof value === 'string' && isJSON(value)) {
+ if (typeof value === 'string' && isJSONObject(value)) {
try {
- this.value = JSON.parseFlex(value)
+ this.value = JSON5.parse(value)
} catch (err) {
this.value = value
}
diff --git a/src/client/widgets/common/queue.js b/src/client/widgets/common/queue.mjs
similarity index 68%
rename from src/client/widgets/common/queue.js
rename to src/client/widgets/common/queue.mjs
index 9b0ba092..b983e137 100644
--- a/src/client/widgets/common/queue.js
+++ b/src/client/widgets/common/queue.mjs
@@ -1,4 +1,5 @@
-var EventEmitter = require('../../events/event-emitter')
+import EventEmitter from '../../events/event-emitter.mjs'
+import {CANVAS_FRAMERATE} from '../../globals.mjs'
class CanvasQueue extends EventEmitter{
@@ -11,7 +12,7 @@ class CanvasQueue extends EventEmitter{
this.running = false
this.frameLength = 1000 / CANVAS_FRAMERATE
this.lastFrame = 0
- this.bindedLoop = this.loop.bind(this)
+ this.boundLoop = this.loop.bind(this)
}
@@ -27,14 +28,16 @@ class CanvasQueue extends EventEmitter{
this.running = true
this.flushed = 0
- requestAnimationFrame(this.bindedLoop)
+ requestAnimationFrame(this.boundLoop)
}
flush() {
for (var h in this.queue) {
- this.queue[h].draw()
+ if (this.queue[h].width > 0 && this.queue[h].height > 0 && this.queue[h].visible) {
+ this.queue[h].draw()
+ }
}
this.queue = {}
@@ -49,7 +52,7 @@ class CanvasQueue extends EventEmitter{
return
}
- requestAnimationFrame(this.bindedLoop)
+ requestAnimationFrame(this.boundLoop)
var delta = timestamp - this.lastFrame
@@ -63,4 +66,4 @@ class CanvasQueue extends EventEmitter{
}
-module.exports = new CanvasQueue()
+export default new CanvasQueue()
diff --git a/src/client/widgets/common/widget.js b/src/client/widgets/common/widget.mjs
similarity index 59%
rename from src/client/widgets/common/widget.js
rename to src/client/widgets/common/widget.mjs
index f8c045a2..a5626a35 100644
--- a/src/client/widgets/common/widget.js
+++ b/src/client/widgets/common/widget.mjs
@@ -1,20 +1,31 @@
-var EventEmitter = require('../../events/event-emitter'),
- osc = require('../../osc'),
- {nanoid} = require('nanoid'),
- widgetManager = require('../../managers/widgets'),
- {urlParser} = require('../utils'),
- Vm = require('../vm'),
- vm = new Vm(),
- scopeCss = require('scope-css'),
- resize = require('../../events/resize'),
- OscReceiver = require('./osc-receiver'),
- {deepCopy, deepEqual, isJSON} = require('../../utils'),
- html = require('nanohtml'),
- morph = require('nanomorph'),
- sanitizeHtml = require('sanitize-html'),
- updateWidget = ()=>{},
- Script, uiConsole
+import html from 'nanohtml'
+import morph from 'nanomorph'
+import scopeCss from 'scope-css'
+import {nanoid} from 'nanoid'
+import EventEmitter from '../../events/event-emitter.mjs'
+import osc from '../../osc.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+import {urlParser, balancedReplace} from '../utils.mjs'
+import Vm from '../vm.mjs'
+import * as resize from '../../events/resize.mjs'
+import OscReceiver from './osc-receiver.mjs'
+import {deepCopy, deepEqual, isJSON} from '../../utils.mjs'
+import Script from '../scripts/script.mjs'
+import {PXSCALE, JSON5} from '../../globals.mjs'
+var updateWidget = ()=>{},
+ uiConsole, widgetTree, widgetDragResize, sessionManager
+
+setTimeout(async()=>{
+ // use setTimeout to fix init order in safari...
+ updateWidget = (await import('../../editor/data-workers.mjs')).updateWidget
+ uiConsole = (await import('../../ui/ui-console.mjs')).default
+ widgetTree = (await import('../../editor/index.mjs')).default.widgetTree
+ widgetDragResize = (await import('../../editor/index.mjs')).default.widgetDragResize
+ sessionManager = (await import('../../managers/session/index.mjs')).default
+})
+
+var vm = new Vm()
var oscReceiverState = {}
@@ -27,17 +38,6 @@ var OSCProps = [
'bypass'
]
-var dummyDOM
-
-DOM.ready(()=>{
- dummyDOM = html``
-})
-
-setTimeout(()=>{
- updateWidget = require('../../editor/data-workers').updateWidget
- uiConsole = require('../../ui/ui-console')
-})
-
class Widget extends EventEmitter {
static description() {
@@ -50,48 +50,45 @@ class Widget extends EventEmitter {
var defaults = {
widget: {
+ lock: {type: 'boolean', value: false, help: 'Set to `true` to prevent modifying this widget with the editor. This will not prevent deleting the widget or moving it from a container to another.'},
type: {type: 'string', value: 'auto', help: 'Widget type'},
- 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.' },
+ 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 (avoid doing so unless the widgets expect the exact same values).' },
visible: {type: 'boolean', value: true, help: 'Set to `false` to hide the widget.'},
interaction: {type: 'boolean', value: true, help: 'Set to `false` to disable pointer interactions.'},
+ comments: {type: 'string', value: '', help: 'User comments.'},
},
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'
+ 'Otherwise, the widget will be positioned at absolute coordinates'
]},
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'
+ 'Otherwise, the widget will be positioned at absolute coordinates'
]},
width: {type: 'number|percentage', value: 'auto', help: 'Widget width'},
height: {type: 'number|percentage', value: 'auto', help: 'Widget height'},
- expand: {type: 'boolean|number', value: 'false', help: 'If parent\'s layout is `vertical` or `horizontal`, set this to `true` to stretch the widget to use available space automatically.'},
+ expand: {type: 'boolean|number', value: false, help: 'If parent\'s layout is `vertical` or `horizontal`, set this to `true` to stretch the widget to use available space automatically.'},
},
style: {
- colorText: {type: 'string', value: 'auto', help: 'Text color. Set to "auto" to inherit from parent widget.'},
- colorWidget: {type: 'string', value: 'auto', help: 'Widget\'s default accent color. Set to "auto" to inherit from parent widget.'},
- colorStroke: {type: 'string', value: 'auto', help: 'Stroke color. Set to "auto" to use `colorWidget`.'},
- colorFill: {type: 'string', value: 'auto', help: 'Fill color. Set to "auto" to use `colorWidget`.'},
+ colorText: {type: 'string', value: 'auto', help: 'Text color. Set to "auto" to inherit from parent widget. Must be a valid css color.'},
+ colorWidget: {type: 'string', value: 'auto', help: 'Widget\'s default accent color. Set to "auto" to inherit from parent widget. Must be a valid css color.'},
+ colorStroke: {type: 'string', value: 'auto', help: 'Stroke color. Set to "auto" to use `colorWidget`. Must be a valid css color.'},
+ colorFill: {type: 'string', value: 'auto', help: 'Fill color. Set to "auto" to use `colorWidget`. Must be a valid css color.'},
alphaStroke: {type: 'number', value: 'auto', help: 'Stroke color opacity.'},
alphaFillOff: {type: 'number', value: 'auto', help: 'Fill color opacity (off).'},
alphaFillOn: {type: 'number', value: 'auto', help: 'Fill color opacity (on).'},
lineWidth: {type: 'number', value: 'auto', help: 'Stroke width.'},
+ borderRadius: {type: 'number|string', value: 'auto', help: 'Border radius expressed as a number or a css string. This property may not work for all widgets.'},
padding: {type: 'number', value: 'auto', help: 'Inner spacing.'},
- html: {type: 'string', value: '', help: [
- 'Custom html content to be inserted in the widget (before the widget\'s content).',
+ html: {type: 'string', value: '', editor: 'html', syntaxChecker: false, help: [
+ 'Custom html content to be inserted in the widget (before the widget\'s content). Elements are all unstyled by default, `css` should be used to customize their appearance.',
'The code is automatically wrapped in <div class="html"></div>',
- 'Allowed HTML tags:',
- ' h1-6, blockquote, p, a, ul, ol, nl, li,',
- ' b, i, strong, em, strike, code, hr, br, div,',
- ' table, thead, img, caption, tbody, tr, th, td, pre',
- 'Allowed attributes:',
- ' <*>: class, style, title',
- ' <img>: src, width, height',
+ 'Note: inserting scripts may break the application.',
]},
- css: {type: 'string', value: '', help: [
+ css: {type: 'string', value: '', editor: 'css', syntaxChecker: false, help: [
'CSS rules. See documentation.',
- 'Available css variables:',
+ 'Some style-related properties can be set or read from css using css variables:',
...Class.cssVariables.map(x=>'- `' + x.css + '`: `' + x.js + '`')
]},
},
@@ -106,7 +103,6 @@ class Widget extends EventEmitter {
'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)'
]},
- script: {type: 'script', value: '', help: 'Script executed whenever the widget\'s value updates. See documentation.'},
},
osc: {
address: {type: 'string', value: 'auto', help: [
@@ -114,13 +110,14 @@ class Widget extends EventEmitter {
'By default ("auto"), the widget\'s id is used: `/widget_id`',
]},
preArgs: {type: '*|array', value: '', help: [
- 'A value or array of values that will be prepended to the OSC messages.',
+ 'A value or array of values that will be prepended to the widget\'s value in the OSC messages it sends.',
+ 'Incoming messages must match these to affect by the widget.',
]},
typeTags: {type: 'string', value: '', help: [
'Defines the osc argument types, one letter per argument (including preArgs)',
- '- If empty, the types are infered automatically from the values (with numbers casted to floats by default)',
+ '- If empty, the types are inferred automatically from the values (with numbers casted to floats by default)',
'- If there are more arguments than type letters, the last type is used for the extra arguments',
- 'See http://opensoundcontrol.org/spec-1_0 for existing typetags'
+ 'See OSC 1.0 specification for existing typetags'
]},
decimals: {type: 'integer', value: 2, help: [
'Defines the number of decimals to send.',
@@ -133,6 +130,10 @@ class Widget extends EventEmitter {
]},
ignoreDefaults: {type: 'boolean', value: false, help: 'Set to `true` to ignore the server\'s default targets'},
bypass: {type: 'boolean', value: false, help: 'Set to `true` to prevent the widget from sending any osc message'}
+ },
+ scripting: {
+ onCreate: {type: 'script', value: '', editor: 'javascript', help: ['Script executed when the widget (and its children) is created. See documentation.']},
+ onValue: {type: 'script', value: '', editor: 'javascript', help: ['Script executed when the widget\'s value updates. See documentation.']},
}
}
@@ -157,9 +158,14 @@ class Widget extends EventEmitter {
if (obj[i] === null) delete this[i]
else {
if (this[i] === undefined) this[i] = {}
- Object.assign(this[i], obj[i])
for (let j in obj[i]) {
if (obj[i][j] === null) delete this[i][j]
+ else if (j[0] === '_') {
+ this[i][j] = obj[i][j]
+ } else {
+ if (!this[i][j]) this[i][j] = {}
+ Object.assign(this[i][j], obj[i][j])
+ }
}
}
}
@@ -183,12 +189,20 @@ class Widget extends EventEmitter {
this.hash = options.hash || 'W' + nanoid(9)
this.children = []
this.reCreateOptions = options.reCreateOptions
+ this.meta = options.meta || {}
this.removed = false
this.mounted = false
this.visible = true
+ this.scopes = []
+
+ if (options.value !== undefined) this.value = options.value
this.parsers = {}
this.parsersLocalScope = options.locals || {}
+ this.timeouts = {}
+ this.intervals = {}
+ this.variables = options.variables || {}
+ this.fragments = {}
this.createPropsCache()
@@ -209,26 +223,65 @@ class Widget extends EventEmitter {
this.decimals = Math.min(20, Math.max(this.getProp('decimals'), 0))
}
- Script = Script || require('../scripts/script')
- if (this.getProp('script') && !(this instanceof Script)) {
- this.script = new Script({props:{
- id: this.getProp('id') + '/script',
- script: this.getProp('script'),
- event: 'value'
- }, builtIn: true, parent: this})
- this.script._not_editable = true
- this.on('change', (e)=>{
- if (e.widget === this && this.mounted && !e.options.fromEdit) {
- this.script.setValue(e.options.widget ? e.options.widget.value : this.value, {...e.options, id: e.options.id || e.id})
- }
+ // scripting
+ this.scripts = {}
+
+ if (this.getProp('onCreate')) {
+ this.scripts.onCreate = new Script({
+ widget: this,
+ property: 'onCreate',
+ code: this.getProp('onCreate'),
+ context: {value: 0}
})
- if (String(this.getProp('script')).includes('touch')) {
- this.on('touch', (e)=>{
- this.script.setValue(this.value, {id: this.getProp('id'), touch: e.touch, sync: true, send: true})
- })
- }
}
+ if (this.getProp('onValue')) {
+ this.scripts.onValue = new Script({
+ widget: this,
+ property: 'onValue',
+ code: this.getProp('onValue'),
+ context: {value: 0, id: '', touch: undefined}
+ })
+ this.on('value-changed', (e)=>{
+ if (e.widget === this && this.mounted && e.options.script !== false) {
+ this.scripts.onValue.run({
+ value: e.options.widget ? e.options.widget.value : this.value,
+ id: e.options.id || e.id
+ }, e.options)
+ }
+ })
+ }
+
+ if (this.getProp('onTouch') && this.getProp('type') !== 'canvas') {
+ this.scripts.onTouch = new Script({
+ widget: this,
+ property: 'onTouch',
+ code: this.getProp('onTouch'),
+ context: {event: {}, value: 0}
+ })
+ this.on('touch', (e)=>{
+ var multi = Array.isArray(e.touch),
+ state = multi ? e.touch[1] : e.touch
+ this.scripts.onTouch.run({
+ event: {type: state ? 'start' : 'stop', handle: multi ? e.touch[0] : undefined},
+ value: this.value
+ }, {sync: true, send: true})
+ })
+ }
+
+ // legacy touch state in onValue script
+ if (String(this.getProp('onValue')).includes('touch') && !this.getProp('onTouch')) {
+ this.on('touch', (e)=>{
+ this.scripts.onValue.run({
+ value: this.value,
+ id: this.getProp('id'),
+ touch: e.touch
+ }, {sync: true, send: true})
+ })
+ }
+
+
+ this.style = null
this.container = html`
`
@@ -283,11 +336,13 @@ class Widget extends EventEmitter {
index: index
})
+ if (this.scripts.onCreate) this.scripts.onCreate.run({value: this.value}, {sync: true, send: true, onCreate: true})
+
}
changed(options) {
- this.trigger('change', {
+ this.trigger('value-changed', {
widget: this,
options: options,
id: this.getProp('id'),
@@ -309,7 +364,7 @@ class Widget extends EventEmitter {
v: this.getValue(true),
}
- if (this.getProp('ignoreDefaults')) data.i = 1
+ if (this.getProp('ignoreDefaults') && !options.force) data.i = 1
if (overrides) {
for (var k in overrides) {
@@ -337,6 +392,24 @@ class Widget extends EventEmitter {
}
+ areEquivalentValueProps(a, b) {
+ /* See commit c1720b4a and https://openstagecontrol.discourse.group/t/widget-update-when-setting-value-via-edit/4186/7
+ * for the root of this...
+ */
+
+ var currentValue = deepCopy(this.value)
+ var va, vb
+
+ this.setValue(a, {coerceTest: true})
+ va = deepCopy(this.value)
+ this.setValue(b, {coerceTest: true})
+ vb = deepCopy(this.value)
+
+ this.setValue(currentValue)
+
+ return deepEqual(va, vb)
+ }
+
checkLinkedProps(propNames) {
// Dynamic props cache check
@@ -346,31 +419,61 @@ class Widget extends EventEmitter {
Object.values(this.linkedProps).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(this.linkedPropsValue).forEach(l => linkedProps = linkedProps.concat(l))
Object.values(this.oscReceivers).forEach(r => linkedProps = linkedProps.concat(r.propNames))
+ Object.values(this.variables).forEach(r => linkedProps = linkedProps.concat(r.propNames))
+ Object.values(this.fragments).forEach(l => linkedProps = linkedProps.concat(l))
if (
- // if prop/osc listeners have changed (@{} / OSC{})
+ // if prop/osc listeners/custom vars have changed (@{} / OSC{} / VAR{})
// refresh the widget's props cache and update linked props bindings
- propNames.map(x => this.props[x]).some(x => typeof x === 'string' && x.match(/OSC\{|@\{/))
+ propNames.map(x => this.props[x]).some(x => typeof x === 'string' && x.match(/(OSC|@|VAR|IMPORT)\{/))
|| propNames.some(n => linkedProps.includes(n))
) {
this.createPropsCache()
+ return true
}
}
createPropsCache() {
+ /*
+ scopable: cache id prefixes (scopes), from nearest to farthest
+ */
+ this.scopes = []
+ if (this.meta.scopable) {
+ var parent = this.parent
+ do {
+ if (parent.getProp('scoped')) {
+ this.scopes.push(parent.scopeId)
+ }
+ parent = parent.parent
+ } while (parent.meta.scopable || parent.getProp('scoped'))
+ for (var i=0; i < this.scopes.length; i++) {
+ this.scopes[i] = this.scopes.slice(i).reverse().join('/') + '/'
+ }
+ }
+ // include global scope
+ if (this.scopes.length) this.scopes.push('')
+
// @{props} links lists
this.linkedProps = {}
this.nestedLinkedProps = {}
this.linkedPropsValue = {}
+ // reset VAR{} links
+ for (var name in this.variables) {
+ this.variables[name].propNames = []
+ }
+
// OSC{/path} receivers
if (this.oscReceivers) {
this.removeOscReceivers()
}
this.oscReceivers = {}
+ // IMPORT{} fragments
+ this.fragments = {}
+
// Cache resolved props
this.cachedProps = {}
this.cachedProps.uuid = this.hash
@@ -414,18 +517,34 @@ class Widget extends EventEmitter {
if (!this.linkedValueChangedCallback && Object.keys(this.linkedPropsValue).length) {
this.linkedValueChangedCallback = (e)=>{
- this.onLinkedPropsChanged(e, 'change')
+ this.onLinkedPropsChanged(e, 'value-changed')
}
- widgetManager.on('change', this.linkedValueChangedCallback, {context: this})
+ widgetManager.on('value-changed', this.linkedValueChangedCallback, {context: this})
} else if (this.linkedPropsValueCallback && !Object.keys(this.linkedPropsValue).length) {
- widgetManager.off('change', this.linkedValueChangedCallback)
+ widgetManager.off('value-changed', this.linkedValueChangedCallback)
delete this.linkedValueChangedCallback
}
+ if (!this.linkedFragmentCallback && Object.keys(this.fragments).length) {
+
+ this.linkedFragmentCallback = (e)=>{
+ var {path} = e
+ if (this.fragments[path]) this.updateProps(this.fragments[path])
+ }
+
+ sessionManager.on('fragment-updated', this.linkedFragmentCallback, {context: this})
+
+ } else if (this.linkedFragmentCallback && !Object.keys(this.fragments).length) {
+
+ sessionManager.off('fragment-updated', this.linkedFragmentCallback)
+ delete this.linkedFragmentCallback
+
+ }
+
var selfLinkedOSCProps = (this.linkedPropsValue['this'] || []).filter(i=>OSCProps.indexOf(i) > -1)
this.selfLinkedOSCProps = selfLinkedOSCProps.length ? selfLinkedOSCProps : false
@@ -434,16 +553,35 @@ class Widget extends EventEmitter {
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
+ changedProps = type === 'prop-changed' ? e.props : type === 'value-changed' ? ['value'] : undefined,
+ linkedProps = type === 'value-changed' ? this.linkedPropsValue : this.linkedProps
if (widget === this.parent) {
if (type === 'widget-created') return
id = 'parent'
+ } else if (this.parent !== widgetManager && widget === this.parent.parent && this.parent.getProp('type') === 'clone') {
+ // ignore clone wrapper when resolving properties
+ id = 'parent'
}
if (widget === this) id = 'this'
+ /*
+ scopable: attempt to resolve scoped widget updates against ids in advanced syntax blocks
+ */
+ if (this.scopes.length) {
+ var unprefixedId
+ for (var p of this.scopes) {
+ if (id.includes(p)) {
+ unprefixedId = id.replace(p, '')
+ if (this.nestedLinkedProps[unprefixedId] || linkedProps[unprefixedId]) {
+ id = unprefixedId
+ break
+ }
+ }
+ }
+ }
+
if (this.nestedLinkedProps[id]) {
this.updateLinkedPropsWithNesting(id)
}
@@ -487,7 +625,7 @@ class Widget extends EventEmitter {
}
- resolveProp(propName, propValue, storeLinks=true, originalWidget, originalPropName, context) {
+ resolveProp(propName, propValue, storeLinks=true, originalWidget, originalPropName, context, recursive) {
propValue = propValue !== undefined ? propValue : deepCopy(this.props[propName])
originalWidget = originalWidget || this
@@ -500,25 +638,17 @@ class Widget extends EventEmitter {
if (typeof propValue == 'string') {
- propValue = propValue.replace(/@\{[^{}]*((@\{[^{}]*\}|[^{}]*)*)\}/g, (m, nested)=>{
- // pretty regexp:
- // @\{
- // [^{}]*
- // ((
- // @\{
- // [^{}]*
- // \}
- // |
- // [^{}]*
- // )*)
- //
- // \}
+ propValue = balancedReplace('@', '{', '}', propValue, (content)=>{
+
+ if (content.indexOf('@{') >= 0) {
+
+ content = balancedReplace('@', '{', '}', content, (subcontent)=>{
+ return this.resolveProp(propName + '-nested', '@{' + subcontent + '}', storeLinks ? 'nested' : false, this)
+ })
- if (nested) {
- m = m.replace(nested, this.resolveProp(propName, nested, storeLinks ? 'nested' : false, this))
}
- let id = m.substr(2, m.length - 3).split('.'),
+ let id = content.split('.'),
k, subk
if (id.length > 1) {
@@ -542,7 +672,7 @@ class Widget extends EventEmitter {
var widgets = id == 'parent' && this.parent ?
[this.parent] : id == 'this' ? [this] :
- widgetManager.getWidgetById(id)
+ widgetManager.getWidgetById(id, this.scopes)
if (!widgets.length) {
var parent = this.parent
@@ -556,11 +686,13 @@ class Widget extends EventEmitter {
}
- // ignore clone wrapper in @parent stack (https://github.com/jean-emmanuel/open-stage-control/issues/379)
+ // ignore clone wrapper in @parent stack (https://framagit.org/jean-emmanuel/open-stage-control/-/work_items/379)
if (widgets[0] === this.parent && this.parent !== widgetManager && this.parent.getProp('type') === 'clone') widgets = [this.parent.parent]
if (storeLinks) {
+ if (propName.indexOf('-nested') !== -1) propName = propName.replace('-nested', '')
+
if (k == 'value') {
if (!this.linkedPropsValue[id]) this.linkedPropsValue[id] = []
@@ -593,7 +725,7 @@ class Widget extends EventEmitter {
var r
switch (k) {
case 'value':
- r = widgets[i].getValue(true)
+ r = typeof widgets[i].value === 'object' ? widgets[i].value : widgets[i].getValue(true)
break
case 'uuid':
r = widgets[i].hash
@@ -621,9 +753,103 @@ class Widget extends EventEmitter {
}
+ return 'undefined'
+
})
- propValue = propValue.replace(/OSC\{([^}]+)\}/g, (m, args)=>{
+ propValue = balancedReplace('VAR', '{', '}', propValue, (args)=>{
+
+ if (args === '') return 'undefined'
+
+ let [name, value] = args.split(',')
+ .map(x=>x.trim())
+ .map(x=>x.replace(/VAR_[0-9]+/g, (m)=>{
+ return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
+ }))
+
+ if (typeof value === 'string' && isJSON(value)) {
+ try {
+ value = JSON5.parse(value)
+ } catch (err) {}
+ }
+
+ if (
+ // remove quotes
+ (name[0] === '"' && name[name.length - 1] === '"') ||
+ (name[0] === '\'' && name[name.length - 1] === '\'')
+ ) name = name.slice(1, name.length - 1)
+
+ if (!this.variables[name]) {
+
+ this.variables[name] = {default: value, value: value, propNames: [propName]}
+
+
+ } else if (!this.variables[name].propNames.includes(propName)) {
+
+ this.variables[name].propNames.push(propName)
+
+ }
+
+ // update value if default changed
+ if (
+ value !== undefined &&
+ !this.variables[name].updated && // only true on edit
+ value !== this.variables[name].default
+ ) {
+ this.variables[name].default = value
+ this.variables[name].value = value
+ if (this.variables[name].propNames.length > 1) {
+ this.updateProps(this.variables[name].propNames.filter(x=>x!==propName))
+ }
+ }
+
+ var r = this.variables[name].value
+
+ var varname = 'VAR_' + varnumber
+ varnumber--
+
+ variables[varname] = r
+ jsScope[varname] = r
+
+ return varname
+ })
+
+ propValue = balancedReplace('IMPORT', '{', '}', propValue, (file)=>{
+
+ file = file.replace(/VAR_[0-9]+/g, (m)=>{
+ return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
+ })
+
+ if (
+ // remove quotes
+ (file[0] === '"' && file[file.length - 1] === '"') ||
+ (file[0] === '\'' && file[file.length - 1] === '\'')
+ ) file = file.slice(1, file.length - 1)
+
+ if (storeLinks) {
+ if (!this.fragments[file]) this.fragments[file] = []
+ if (!this.fragments[file].includes(propName)) this.fragments[file].push(propName)
+ }
+ var r
+ if (sessionManager.getFragment(file)) {
+ r = sessionManager.getFragment(file)
+ } else {
+ sessionManager.loadFragment(file, true)
+ r = ''
+ }
+
+ var varname = 'VAR_' + varnumber
+ varnumber--
+
+ variables[varname] = r
+ jsScope[varname] = r
+
+ return varname
+ })
+
+ propValue = balancedReplace('OSC', '{', '}', propValue, (args)=>{
+
+ if (args === '') return 'undefined'
let [address, value, usePreArgs] = args.split(',')
.map(x=>x.trim())
@@ -631,6 +857,8 @@ class Widget extends EventEmitter {
return typeof variables[m] === 'string' ? variables[m] : JSON.stringify(variables[m])
}))
+ if (!address) return 'undefined'
+
if (!this.oscReceivers[args]) {
this.oscReceivers[args] = new OscReceiver({
address: address,
@@ -661,11 +889,21 @@ class Widget extends EventEmitter {
})
try {
- propValue = propValue.replace(/JS\{\{([\s\S]*)\}\}/g, (m, code)=>{
+ propValue = balancedReplace('JS', '{', '}', propValue, (code)=>{
+
+ if (code[0] === '{' && code[code.length - 1] === '}') code = code.slice(1, code.length - 1)
if (!this.parsers[code]) this.parsers[code] = vm.compile(code, defaultScope)
- let r = this.parsers[code](jsScope, this.parsersLocalScope)
+ let r
+ vm.setWidget(this)
+ try {
+ r = this.parsers[code](jsScope, this.parsersLocalScope)
+ } catch (err) {
+ vm.setWidget()
+ throw err
+ }
+ vm.setWidget()
if (r === undefined) r = ''
@@ -673,18 +911,23 @@ class Widget extends EventEmitter {
})
} catch (err) {
- this.errorProp(propName, 'JS{{}}', err)
+ this.errorProp(propName, 'JS{}', err)
}
try {
- propValue = propValue.replace(/#\{(?:[^{}]|\{[^{}]*\})*\}/g, (m)=>{
- // one bracket nesting allowed, if we need two: #\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}
+ propValue = balancedReplace('#', '{', '}', propValue, (code)=>{
- var code = m.substr(2, m.length - 3).trim()
+ if (!this.parsers[code]) this.parsers[code] = vm.compile('return ' + code.trim(), defaultScope)
- if (!this.parsers[code]) this.parsers[code] = vm.compile('return ' + code, defaultScope)
-
- let r = this.parsers[code](jsScope, this.parsersLocalScope)
+ let r
+ vm.setWidget(this)
+ try {
+ r = this.parsers[code](jsScope, this.parsersLocalScope)
+ } catch (err) {
+ vm.setWidget()
+ throw err
+ }
+ vm.setWidget()
if (r === undefined) r = ''
@@ -692,6 +935,7 @@ class Widget extends EventEmitter {
})
} catch (err) {
+
this.errorProp(propName, '#{}', err)
}
@@ -700,7 +944,14 @@ class Widget extends EventEmitter {
propValue = propValue.replace(new RegExp(k, 'g'), v)
}
- if (isJSON(propValue)) {
+ if (
+ // json heuristic
+ isJSON(propValue) &&
+ // allow "false" string in label
+ (propName !== 'label' || propValue === 'false') &&
+ // don't coerce booleans and numbers as strings in objects
+ (!recursive || (isNaN(propValue) && propValue != 'true' && propValue != 'false'))
+ ) {
try {
propValue = JSON.parse(propValue)
} catch (err) {}
@@ -708,12 +959,30 @@ class Widget extends EventEmitter {
} else if (propValue != null && typeof propValue == 'object') {
for (let k in propValue) {
- propValue[k] = this.resolveProp(propName, propValue[k], storeLinks, originalWidget, originalPropName, context)
+ propValue[k] = this.resolveProp(propName, propValue[k], storeLinks, originalWidget, originalPropName, context, true)
}
}
- return propValue
+ return this.transformProp(propName, propValue)
+
+
+ }
+
+ transformProp(propName, propValue) {
+
+ switch (propName) {
+ /*
+ scopable: prefix id with the closest (most restrictive) scope
+ */
+ case 'id':
+ if (this.scopes.length) {
+ propValue = this.scopes[0] + propValue
+ }
+ break
+ }
+
+ return propValue
}
@@ -747,13 +1016,32 @@ class Widget extends EventEmitter {
let propValue = this.resolveProp(propName, undefined, false),
oldPropValue = this.getProp(propName)
- if (!deepEqual(oldPropValue, propValue)) {
-
+ if (
+ !deepEqual(oldPropValue, propValue) ||
+ (options && options.fromEditor && propName == 'value' && !this.areEquivalentValueProps(propValue, oldPropValue))
+ ) {
if (!this.isDynamicProp(propName)) {
- if ((!widget || !this.contains(widget)) && !(widget === this && updatedProps.length === 1 && updatedProps[0] === 'value')) {
+ if (this.constructor._defaults[propName] === undefined) {
+
+ // ignore invalid properties
+ continue
+
+ } else if (widget && this.contains(widget)) {
+
+ this.errorProp(propName, '@{}', `a container can't use its child's properties to define non-dynamic properties.`)
+ continue
+
+ } else if (widget === this && updatedProps.length === 1 && updatedProps[0] === 'value') {
+
+ this.errorProp(propName, '@{}', `a widget can't use it's own value to define non-dynamic properties.`)
+ continue
+
+ } else {
+
reCreate = true
break
+
}
} else {
@@ -762,7 +1050,6 @@ class Widget extends EventEmitter {
}
-
}
}
@@ -790,7 +1077,21 @@ class Widget extends EventEmitter {
}
if (options && options.fromEditor) {
- this.checkLinkedProps(propNames)
+
+ // update advanced syntax bindings if its an edition
+ if (this.checkLinkedProps(propNames)) {
+
+ // emit prop-changed event if not already
+ // to make sure an advanced syntax changes don't go unnoticed by clone
+ var unNotified = propNames.filter(n => !changedProps.includes(n))
+ widgetManager.trigger('prop-src-changed', {
+ id: this.getProp('id'),
+ props: unNotified,
+ widget: this,
+ options: options
+ })
+ }
+
}
}
@@ -814,6 +1115,7 @@ class Widget extends EventEmitter {
this.setContainerStyles(['geometry'])
let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
resize.check(container)
+ if (widgetDragResize.mounted && widgetDragResize.widgets.includes(this)) widgetDragResize.updateRectangle()
return
}
@@ -821,6 +1123,7 @@ class Widget extends EventEmitter {
this.setVisibility()
let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
resize.check(container)
+ widgetTree.updateVisibility(this)
return
}
@@ -839,6 +1142,7 @@ class Widget extends EventEmitter {
if (re.test(oldPropValue) || re.test(this.getProp('css'))) {
let container = this.parent !== widgetManager && this.parent.getProp('layout') !== 'default' ? this.parent.container : this.container
resize.check(container)
+ if (widgetDragResize.mounted && widgetDragResize.widgets.includes(this)) widgetDragResize.updateRectangle()
}
return
}
@@ -888,14 +1192,27 @@ class Widget extends EventEmitter {
}
+
+ log(message) {
+
+ if (!uiConsole) return
+
+ var widget = this,
+ id = widget.getProp('id')
+
+ console._log(`${id}${name ? '.' + name : ''}: ${message}`)
+ uiConsole.log('log', `: ${message}`, true)
+
+ }
+
errorProp(name, type, error) {
let stackline = error.stack ? (error.stack.match(/>:([0-9]+):[0-9]+/) || '') : '',
- line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - (type.includes('{}') ? 1 : 0)) : '',
+ line = stackline.length > 1 ? ' at line ' + (parseInt(stackline[1]) - (type.includes('{}') ? 1 : 2)) : '',
id = this.getProp('id') || this.props.id,
widget = this // used for edit link in console
- while (widget._not_editable && widget.parent !== widgetManager) {
+ while (widget.meta.not_editable && widget.parent !== widgetManager) {
// ignore non editable
widget = widget.parent
}
@@ -903,8 +1220,9 @@ class Widget extends EventEmitter {
// ignore clone wrapper
if (widget.parent !== widgetManager && widget.parent.getProp('type') === 'clone') widget = widget.parent
- console._error(`${id}.${name} ${type} error${line}: ${error}`)
- uiConsole.log('error', `.${name} ${type} error${line}: ${error}`, true)
+ console._error(`${id}${name ? '.' + name : ''} ${type} error${line}: ${error}`)
+ console.debug(error)
+ uiConsole.log('error', `${name ? '.' + name : ''} ${type} error${line}: ${error}`, true)
}
setContainerStyles(styles = ['geometry', 'css', 'visibility']) {
@@ -933,6 +1251,7 @@ class Widget extends EventEmitter {
}
this.container.classList.toggle('absolute-position', absolutePos)
this.container.classList.toggle('flex-expand', this.getProp('expand'))
+ this.container.classList.toggle('not-editable', !!this.meta.not_editable)
}
@@ -951,7 +1270,7 @@ class Widget extends EventEmitter {
})
- // escpape windows absolute file paths
+ // escape windows absolute file paths
css = css.replace(/url\(([^)]*)\)/g, (m, url)=>{
var parser = urlParser(url)
if (!parser.protocol.match(/http|data/)) m = m.replace(':', '_:_')
@@ -961,51 +1280,54 @@ class Widget extends EventEmitter {
var prefix = '#' + this.hash,
- scopedCss = scopeCss(css, prefix),
+ scopedCss = '',
unScopedCss = ''
+ if (css.includes('{')) {
- try {
+ scopedCss = scopeCss(css, prefix)
- 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 + ';'
- })
+ .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)
+
+ } else {
+
+ unScopedCss = css
}
- if (scopedCss.indexOf('@keyframes') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s+([0-9]+%|to|from)', 'g'), ' $1')
- if (scopedCss.indexOf('&') > -1) scopedCss = scopedCss.replace(new RegExp(prefix + '\\s&', 'g'), prefix)
- var style = html``,
- oldStyle = DOM.get(this.container, '> style')[0]
+ var style = (unScopedCss ? prefix + '{' + unScopedCss + '}\n' : '') + scopedCss
+ style = style.trim()
- if (oldStyle) {
- this.container.replaceChild(style, oldStyle)
+ if (this.style && this.container.contains(this.style)) {
+ if (style) this.style.innerText = style
+ else this.container.removeChild(this.style)
} else if (scopedCss.length || unScopedCss.length){
- this.container.insertBefore(style, this.container.childNodes[0] || null)
+ this.style = html``
+ this.container.insertBefore(this.style, this.container.childNodes[0] || null)
}
// apply extra css classes
+ if (!deepEqual(extraCssClasses, this.extraCssClasses)) {
+ if (this.extraCssClasses && this.extraCssClasses.length) {
+ this.container.classList.remove(...this.extraCssClasses)
+ this.extraCssClasses = []
+ }
- 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 (extraCssClasses.length) {
+ this.container.classList.add(...extraCssClasses)
+ this.extraCssClasses = extraCssClasses
+ }
}
@@ -1023,9 +1345,6 @@ class Widget extends EventEmitter {
}
- return style
-
-
}
setCssVariables() {
@@ -1042,13 +1361,7 @@ class Widget extends EventEmitter {
updateHtml(){
- var extraHtml = this.getProp('html') !== '' ? sanitizeHtml(this.getProp('html'), {
- allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']).filter(x=>x!=='iframe'),
- allowedAttributes: {
- '*': [ 'title', 'class', 'style', 'type'],
- 'img': [ 'src' , 'title', 'class', 'style', 'width', 'height']
- }
- }) : null
+ var extraHtml = this.getProp('html') || null
if (this.extraHtml) {
if (!extraHtml) {
@@ -1077,11 +1390,11 @@ class Widget extends EventEmitter {
setVisibility() {
-
var visible = this.isVisible()
+
if (visible !== this.visible) {
- this.visible = visible
- this.container.style.display = this.getProp('visible') ? '' : 'none'
+ this.visible = !!visible
+ this.container.style.display = this.visible ? '' : 'none'
for (var c of this.children) {
if (c) c.setVisibility()
@@ -1099,12 +1412,17 @@ class Widget extends EventEmitter {
onRemove(){
- if (this.getProp('script') && !(this instanceof Script)) {
- this.script.onRemove()
+ for (var k in this.scripts) {
+ this.scripts[k].onRemove()
}
this.removed = true
+ for (var name in this._listeners) {
+ if (name !== 'widget-removed') this.off(name)
+ }
+
widgetManager.off(undefined, undefined, this)
+ sessionManager.off(undefined, undefined, this)
this.removeOscReceivers()
}
@@ -1121,6 +1439,7 @@ Widget.cssVariables = [
{js: 'colorText', css: '--color-text'},
{js: 'padding', css: '--widget-padding', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE},
{js: 'lineWidth', css: '--line-width', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE},
+ {js: 'borderRadius', css: '--border-radius', toCss: x=>parseFloat(x) == x ? x + 'rem' : x, toJs: x=>parseFloat(x)},
{js: 'alphaFillOn', css: '--alpha-fill-on', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
{js: 'alphaFillOff', css: '--alpha-fill-off', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
{js: 'alphaStroke', css: '--alpha-stroke', toCss: x=>parseFloat(x), toJs: x=>parseFloat(x)},
@@ -1129,6 +1448,7 @@ Widget.cssVariables = [
Widget.dynamicProps = [
'visible',
'interaction',
+ 'comments',
'top',
'left',
@@ -1159,4 +1479,4 @@ Widget.dynamicProps = [
'bypass'
]
-module.exports = Widget
+export default Widget
diff --git a/src/client/widgets/containers/clone.js b/src/client/widgets/containers/clone.mjs
similarity index 51%
rename from src/client/widgets/containers/clone.js
rename to src/client/widgets/containers/clone.mjs
index 7686bdc9..bf855b51 100644
--- a/src/client/widgets/containers/clone.js
+++ b/src/client/widgets/containers/clone.mjs
@@ -1,10 +1,11 @@
-var Container = require('../common/container'),
- widgetManager = require('../../managers/widgets'),
- resize = require('../../events/resize'),
- parser = require('../../parser'),
- {deepCopy, deepEqual} = require('../../utils'),
- {diff, diffToWidget} = require('../../editor/diff'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import Container from '../common/container.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+import * as resize from '../../events/resize.mjs'
+import parser from '../../parser.mjs'
+import {deepCopy, deepEqual} from '../../utils.mjs'
+import {diff, diffToWidget} from '../../editor/diff'
+import Session from '../../managers/session/session.mjs'
var excludedCloneClasses = ['widget', 'absolute-position', 'not-editable', 'editing', 'flex-expand', 'no-interaction']
@@ -22,10 +23,16 @@ class Clone extends Container() {
class_specific: {
widgetId: {type: 'string', value: '', help: '`id` of the widget to clone'},
- props: {type: 'object', value: {}, help: 'Cloned widget\'s properties to override'},
+ scoped: {type: 'boolean|string', value: false, help: [
+ 'Set to `true` to prefix all cloned `id`s inside the clone with a unique identifier and make the clone independent from its original. All `@{}` blocks and scripts will be prefixed automatically so that they resolve to widgets within the clone if possible, falling back to unprefixed ids otherwise. `linkId` will be prefixed as well but will only resolve within the clone.',
+ '`clone` and `scrollbar` widgets will prioritize targets closer to their scope, falling back to farther target.',
+ 'Set this property to a string to define the `ìd` prefix manually (a trailing slash will be added automatically). This can be useful if one must access a scoped widget via scripting or remote control commands.'
+ ]},
+ props: {type: 'object', value: {}, editor: 'javascript', syntaxChecker: false, help: 'Cloned widget\'s properties to override'},
},
value: null,
- osc: null
+ osc: null,
+ scripting: null
})
defaults.style = {css: defaults.style.css}
@@ -36,7 +43,7 @@ class Clone extends Container() {
constructor(options) {
- options.props.label = ''
+ options.props.address = 'auto'
options.props.variables = '@{parent.variables}'
super({...options, html: html``})
@@ -45,23 +52,94 @@ class Clone extends Container() {
this.cloneLock = false
this.cloneTarget = null
+ this.targetRank = null
this.cloneClass = []
+ this.scopeId = this.getProp('scoped') === true ? this.hash : this.getProp('scoped') === false ? '' : this.getProp('scoped')
+
this.modalBreakout = 0
this.container.classList.add('empty')
- this.bindTarget(this.getCloneTarget())
- if (this.cloneTarget) this.createClone(true)
+ var parent = this.parent
+ while (parent !== widgetManager) {
+ if (parent.getProp('id') === this.getProp('widgetId')) {
+ this.errorProp('widgetId', 'circular reference', 'cannot create clone: target widget is a parent of this clone.')
+ return
+ }
+ parent = parent.parent
+ }
+
+ this.getCloneTarget()
- // global listener to catch cloneTarget's creation if no target is locked
widgetManager.on('widget-created', (e)=>{
- if (this.cloneTarget) return
+ // if in a non-scoped context we don't watch for a closer target once we have one
+ if (!this.scopes.length && this.cloneTarget) return
var {id, widget} = e
- if (id === this.getProp('widgetId') && this.isValidCloneTarget(widget)) {
+ if (String(id).includes(this.getProp('widgetId')) && this.isValidCloneTarget(widget)) {
+
+ this.getCloneTarget()
+
+ }
+
+ }, {context: this})
+
+ var onPropChanged = (e)=>{
+ // watch for prop changes initiated by the editor
+ // Other changes (from advanced syntaxes) are already
+ // handled by standard widget mechanicsé
+
+ if (!this.cloneTarget) return
+ if (!e.options || !e.options.fromEditor) return
+
+ if (e.widget === this.cloneTarget || this.cloneTarget.contains(e.widget)) {
+
+ this.updateClone(e.options)
+
+ }
+
+ }
+
+ widgetManager.on('prop-changed', onPropChanged, {context: this})
+
+ // see common/widget.js @ updateProps()
+ widgetManager.on('prop-src-changed', onPropChanged, {context: this})
+
+ }
+
+ getCloneTarget() {
+
+ // attempt to acquire a cloneTarget if 'widget-created' event has not been caught
+ // (the target might have been created before the clone itself)
+
+ var scopes = this.scopes.length ? this.scopes : [''],
+ target = null,
+ rank = 0
+
+ for (var scope of scopes) {
+ var widgets = widgetManager.getWidgetById(this.getProp('widgetId'), scope)
+ .filter(w=>this.isValidCloneTarget(w))
+ target = widgets[0]
+
+ if (!target) {
+ rank++
+ continue
+ }
+
+ for (var w of widgets) {
+ // 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)
+ if (!(w.parent && w.parent.getProp('type') == 'clone')) {
+ target = w
+ break
+ }
+ }
+
+ if (rank < this.targetRank || this.targetRank == null) {
var clone = this.children[0]
@@ -70,75 +148,21 @@ class Clone extends Container() {
if (!clone) {
this.updateContainer(false)
- this.bindTarget(widget)
+ this.bindTarget(target, rank)
this.createClone()
} else {
- this.bindTarget(widget)
+ this.bindTarget(target, rank)
this.updateClone()
}
-
}
- }, {context: this})
+ return
- widgetManager.on('prop-changed', (e)=>{
-
- if (!this.cloneTarget) return
-
- if (e.widget === this.cloneTarget || this.cloneTarget.contains(e.widget)) {
-
- this.updateClone(e.options)
-
- }
-
- }, {context: this})
-
- this.on('widget-created', (e)=>{
-
- if (e.widget !== this) {
- e.widget.container.classList.add('not-editable')
- e.widget._not_editable = true
- }
-
- })
-
- }
-
- 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) {
@@ -155,10 +179,17 @@ class Clone extends Container() {
var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')}
+ Session.converters['1.13.2'].widget(data)
+
parser.parse({
data: data,
parentNode: this.widget,
- parent: this
+ parent: this,
+ meta: {
+ not_editable: true,
+ clone: true,
+ scopable: true
+ }
})
this.updateContainer(!init)
@@ -174,17 +205,19 @@ class Clone extends Container() {
this.cloneTarget.off(undefined, undefined, this)
this.cloneTarget = null
+ this.targetRank = null
}
- bindTarget(target) {
+ bindTarget(target, rank) {
if (!target) return
this.cloneTarget = target
+ this.targetRank = rank
// listen for cloneTarget's deletion
- // if it is just edited, its recreation will be catched by the global 'widget-created' event handler
+ // if it is just edited, its recreation will be caught by the global 'widget-created' event handler
this.cloneTarget.on('widget-removed', (e)=>{
if (this.cloneTarget === e.widget) {
this.unbindTarget()
@@ -194,18 +227,14 @@ class Clone extends Container() {
// listen for cloneTarget's content updates
this.cloneTarget.on('widget-created', (e)=>{
- var {widget} = e,
- parent = widget.parent
+ var {widget} = e
- 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
+ // if updated widget is in a nested clone, ignore it:
+ // it will be handled by the nested clone that targets it
+ if (!widget.meta.clone) {
+ this.updateClone()
}
- this.updateClone()
-
}, {context: this})
}
@@ -219,6 +248,8 @@ class Clone extends Container() {
var data = {...deepCopy(this.cloneTarget.props), ...this.getProp('props')},
clone = this.children[0]
+ Session.converters['1.13.2'].widget(data)
+
var delta = diff.diff(clone.props, data) || {},
[widget, patch] = diffToWidget(clone, delta),
changedProps = Object.keys(patch)
@@ -263,10 +294,6 @@ class Clone extends Container() {
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) {
@@ -288,24 +315,10 @@ class Clone extends Container() {
switch (propName) {
case 'widgetId':
- this.unbindTarget()
- this.updateContainer(false)
- this.bindTarget(this.getCloneTarget())
- if (this.cloneTarget) this.createClone()
+ this.getCloneTarget()
return
- case 'colorText':
- case 'colorWidget':
- case 'colorFill':
- case 'colorStroke':
- case 'alphaStroke':
- case 'alphaFillOff':
- case 'alphaFillOn':
- case 'colorBg':
- case 'lineWidth':
- case 'padding':
- for (var w of this.children) {
- if (w) w.onPropChanged(propName)
- }
+ case 'props':
+ if (this.children[0]) this.updateClone()
return
}
@@ -322,7 +335,8 @@ class Clone extends Container() {
}
Clone.dynamicProps = Clone.prototype.constructor.dynamicProps.concat(
- 'widgetId'
+ 'widgetId',
+ 'props'
)
-module.exports = Clone
+export default Clone
diff --git a/src/client/widgets/containers/folder.mjs b/src/client/widgets/containers/folder.mjs
new file mode 100644
index 00000000..6f8f3722
--- /dev/null
+++ b/src/client/widgets/containers/folder.mjs
@@ -0,0 +1,60 @@
+import Panel from './panel.mjs'
+
+class Folder extends Panel {
+
+ static description() {
+
+ return 'Flat container that doesn\'t affect layout. Mostly useful for grouping widgets in the tree.'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults().extend({
+ class_specific: {
+ traversing: null
+ },
+ style: {
+
+ },
+ geometry: null,
+ osc: null,
+ scripting: null,
+ value: null,
+ children: {
+ widgets: {type: 'array', value: [], help: 'Each element of the array must be a widget object. A panel cannot contain widgets and tabs simultaneously.'},
+ }
+ })
+
+ defaults.style = {
+ colorText: defaults.style.colorText,
+ colorWidget: defaults.style.colorWidget,
+ css: defaults.style.css,
+ }
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ }
+
+ getProp(propName) {
+
+ if (propName === 'layout') {
+ return this.parent.getProp('layout')
+ } else {
+ return super.getProp(propName)
+ }
+
+ }
+
+
+}
+
+
+
+export default Folder
diff --git a/src/client/widgets/containers/fragment.mjs b/src/client/widgets/containers/fragment.mjs
new file mode 100644
index 00000000..0979425f
--- /dev/null
+++ b/src/client/widgets/containers/fragment.mjs
@@ -0,0 +1,223 @@
+import html from 'nanohtml'
+import Container from '../common/container.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+import * as resize from '../../events/resize.mjs'
+import parser from '../../parser.mjs'
+import {deepCopy, deepEqual} from '../../utils.mjs'
+import {diff, diffToWidget} from '../../editor/diff'
+import Session from '../../managers/session/session.mjs'
+
+var sessionManager
+;(async()=>{
+ sessionManager = (await import('../../managers/session/index.mjs')).default
+})()
+
+var excludedfragmentClasses = ['widget', 'absolute-position', 'not-editable', 'editing', 'flex-expand', 'no-interaction']
+
+class Fragment extends Container() {
+
+ static description() {
+
+ return 'Embedded session or fragment file with overridable properties.'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults().extend({
+
+ class_specific: {
+ file: {type: 'string', value: '', help: 'Fragment file path (relative to the session or theme file location by default, falling back to absolute path)'},
+ fallback: {type: 'string', value: '', help: 'Fallack fragment file path, loaded if `file` can\'t be opened'},
+ scoped: {type: 'boolean|string', value: false, help: [
+ 'Set to `true` to prefix all cloned `id`s inside the clone with a unique identifier and make the clone independent from its original. All `@{}` blocks and scripts will be prefixed automatically so that they resolve to widgets within the clone if possible, falling back to unprefixed ids otherwise. `linkId` will be prefixed as well but will only resolve within the clone.',
+ '`clone` and `scrollbar` widgets will prioritize targets closer to their scope, falling back to farther target.',
+ 'Set this property to a string to define the `ìd` prefix manually (a trailing slash will be added automatically). This can be useful if one must access a scoped widget via scripting or remote control commands.'
+ ]},
+ props: {type: 'object', value: {}, editor: 'javascript', syntaxChecker: false, help: 'Fragment widget\'s properties to override'},
+ },
+ value: null,
+ osc: null,
+ scripting: null
+ })
+
+ defaults.style = {css: defaults.style.css}
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ options.props.address = 'auto'
+ options.props.variables = '@{parent.variables}'
+
+ super({...options, html: html``})
+
+ this.noValueState = true
+
+ this.scopeId = this.getProp('scoped') === true ? this.hash : this.getProp('scoped') === false ? '' : this.getProp('scoped')
+
+ this.modalBreakout = 0
+
+ this.fragmentClass = []
+ this.container.classList.add('empty')
+
+ sessionManager.on('fragment-updated', (e)=>{
+ var {path} = e
+ if (path === this.getProp('file') || path === this.getProp('fallback')) {
+ this.createFragment()
+ }
+ }, {context: this})
+
+ sessionManager.on('fragment-not-found', (e)=>{
+ var {path} = e
+ if (path === this.getProp('file')) {
+ if (this.getProp('fallback')) {
+ if (this.getFragment()) this.createFragment()
+ else sessionManager.loadFragment(this.getProp('fallback'))
+ } else {
+ this.log('fragment file not found')
+ }
+ } else if (path === this.getProp('fallback') && !this.getFragment()) {
+ this.log('fallback fragment file not found')
+ }
+ }, {context: this})
+
+ if (this.getProp('file')) {
+ if (sessionManager.getFragment(this.getProp('file'))) {
+ this.createFragment(true)
+ } else {
+ sessionManager.loadFragment(this.getProp('file'))
+ }
+ }
+
+
+ }
+
+ getFragment() {
+
+ var fragment = sessionManager.getFragment(this.getProp('file'))
+
+ if (!fragment && this.getProp('fallback')) {
+ fragment = sessionManager.getFragment(this.getProp('fallback'))
+ }
+
+ return fragment
+
+ }
+
+ createFragment(init) {
+
+ var fragment = this.getFragment()
+
+ if (!fragment) return
+
+
+ var data = {...deepCopy(fragment.getRoot()), ...this.getProp('props')}
+
+ Session.converters['1.13.2'].widget(data)
+
+ parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this,
+ meta: {
+ not_editable: true,
+ fragment: true,
+ scopable: true
+ }
+ })
+
+ this.updateContainer(!init)
+
+ }
+
+
+ updateContainer(checkResize) {
+
+
+ if (this.children[0]) {
+
+ var classes = [...this.children[0].container.classList].filter(i=>excludedfragmentClasses.indexOf(i) === -1)
+
+ if (!deepEqual(classes, this.fragmentClass)) {
+ this.container.classList.remove(...this.fragmentClass)
+ this.fragmentClass = classes
+ this.container.classList.add(...this.fragmentClass)
+ }
+
+ this.container.classList.remove('empty')
+
+ if (checkResize) resize.check(this.widget)
+
+ } else if (this.fragmentClass.length) {
+
+ this.container.classList.remove(...this.fragmentClass)
+ this.container.classList.add('empty')
+ this.fragmentClass = []
+ this.widget.innerHTML = ''
+ widgetManager.removeWidgets(this.getAllChildren())
+
+ }
+
+ }
+
+ updateFragment() {
+
+
+ var fragment = this.getFragment()
+
+ if (!fragment) return
+
+ var data = {...deepCopy(fragment.getRoot()), ...this.getProp('props')},
+ fragmentWidget = this.children[0]
+
+ Session.converters['1.13.2'].widget(data)
+
+ var delta = diff.diff(fragmentWidget.props, data) || {},
+ [widget, patch] = diffToWidget(fragmentWidget, delta),
+ changedProps = Object.keys(patch)
+
+ if (changedProps.length) {
+
+ diff.patch(widget.props, patch)
+
+
+ if (changedProps.some(x => !widget.isDynamicProp(x))) {
+
+ fragmentWidget.reCreateWidget({reuseChildren: false})
+ this.updateContainer(false)
+
+ } else {
+
+ widget.updateProps(changedProps, this)
+ this.updateContainer(true)
+
+ }
+
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'props':
+ if (this.children[0]) this.updateFragment()
+ return
+
+ }
+
+ }
+
+}
+
+Fragment.dynamicProps = Fragment.prototype.constructor.dynamicProps.concat(
+ 'props'
+)
+
+export default Fragment
diff --git a/src/client/widgets/containers/keyboard.js b/src/client/widgets/containers/keyboard.mjs
similarity index 74%
rename from src/client/widgets/containers/keyboard.js
rename to src/client/widgets/containers/keyboard.mjs
index 73e22603..cdbfd8bc 100644
--- a/src/client/widgets/containers/keyboard.js
+++ b/src/client/widgets/containers/keyboard.mjs
@@ -1,7 +1,7 @@
-var Panel = require('./panel'),
- Widget = require('../common/widget'),
- parser = require('../../parser'),
- {mapToScale} = require('../utils')
+import Panel from './panel.mjs'
+import Widget from '../common/widget.mjs'
+import parser from '../../parser.mjs'
+import {mapToScale} from '../utils.mjs'
class Keyboard extends Panel {
@@ -37,12 +37,19 @@ class Keyboard extends Panel {
'Set to `true` to map the touch coordinates between `off` (top) and `on` (bottom). Requires `on` and `off` to be numbers',
]},
mode: {type: 'string', value: 'push', choices: ['push', 'toggle', 'tap'], help: [
- 'Interraction mode:',
+ 'Interaction mode:',
'- `push` (press & release)',
'- `toggle` (on/off switches)',
'- `tap` (no release)'
]},
- }
+ },
+ value: {
+ value: {type: 'array', value: '', help: [
+ 'The keyboard widget accepts the following values:',
+ '- a `[note, value]` array to set the value of a single key where `note` is the note number and `value` depends on the `on` and `off` properties (any value different from `off` will be interpreted as `on`).',
+ '- an array of values with one item per key in the keyboard'
+ ]}
+ },
})
}
@@ -60,7 +67,7 @@ class Keyboard extends Panel {
}, {element: this.widget})
- this.on('change',(e)=>{
+ this.on('value-changed',(e)=>{
var widget = e.widget
@@ -102,13 +109,13 @@ class Keyboard extends Panel {
var pattern = 'wbwbwwbwbwbw',
whiteKeys = 0, whiteKeys2 = 0, i
- for (i = start; i < keys + start && i < 109; i++) {
+ for (i = start; i < keys + start && i < 128; i++) {
if (pattern[i % 12] == 'w') whiteKeys++
}
this.container.style.setProperty('--nkeys', whiteKeys)
- for (i = start; i < keys + start && i < 109; i++) {
+ for (i = start; i < keys + start && i < 128; i++) {
var data = {
top: 'auto',
@@ -128,12 +135,11 @@ class Keyboard extends Panel {
var key = parser.parse({
data: data,
parentNode: this.widget,
- parent: this
+ parent: this,
+ meta: {not_editable: true}
})
key._index = i - start
- key.container.classList.add('not-editable')
- key._not_editable = true
key.container.classList.add('key')
if (pattern[i % 12] == 'w') {
@@ -153,11 +159,23 @@ class Keyboard extends Panel {
setValue(v, options={}) {
- if (!Array.isArray(v) || v.length !== 2) return
- if (v[1] !== this.getProp('on') && v[1] !== this.getProp('off')) return
+ if (!Array.isArray(v)) return
- var start = parseInt(this.getProp('start'))
- this.children[v[0] - start].setValue(v[1] === this.getProp('on') ? 1 : 0, options)
+ if (v.length === this.children.length) {
+ for (var i = 0; i < this.children.length; i++){
+ this.children[i].setValue(v[i] !== this.getProp('off') ? 1 : 0, options)
+ }
+ }
+
+ else if (
+ v.length === 2 &&
+ v[0] >= parseInt(this.getProp('start')) && v[0] < 128
+ ) {
+ var index = v[0] - parseInt(this.getProp('start'))
+ if (this.children[index]) {
+ this.children[index].setValue(v[1] !== this.getProp('off') ? 1 : 0, options)
+ }
+ }
}
@@ -174,4 +192,4 @@ Keyboard.cssVariables = Keyboard.prototype.constructor.cssVariables.concat(
{js: 'colorBlack', css: '--color-black-key'}
)
-module.exports = Keyboard
+export default Keyboard
diff --git a/src/client/widgets/containers/matrix.js b/src/client/widgets/containers/matrix.js
deleted file mode 100644
index 620d56b4..00000000
--- a/src/client/widgets/containers/matrix.js
+++ /dev/null
@@ -1,184 +0,0 @@
-var Panel = require('./panel'),
- parser = require('../../parser'),
- {deepCopy} = require('../../utils')
-
-
-class Matrix extends Panel {
-
- static description() {
-
- return 'Generic matrix for creating rows/columns of widgets.'
-
- }
-
- static defaults() {
-
- return super.defaults().extend({
- class_specific: {
- widgetType: {type: 'string', value: 'button', help: 'Defines the type of the widgets in the matrix'},
- quantity: {type: 'number', value: 4, help: 'Defines the number of widgets in the matrix'},
- start: {type: 'integer', value: 0, help: 'First widget\'s index'},
- props: {type: 'object', value: {}, help: [
- 'Defines a set of property to override the widgets\' defaults.',
- 'JS{{}} and #{} blocks in this field are resolved with an extra variable representing each widget\'s index: `$` (e.g. `#{$}`)',
- 'Advanced syntax blocks (@{}, OSC{}, JS{{}} and #{}) are resolved at the matrix\' scope (ie @{this.variables} returns the matrix\' variables property, not its parent\'s)',
- 'Note: by default, the widgets inherit from the matrix\' `id` and osc properties (`id` and `address` are appended with `/$`)'
- ]},
- },
- style: {
- layout: {type: 'string', value: 'horizontal', choices: ['horizontal', 'vertical', 'grid'], help: 'Defines how children are laid out.'},
- verticalTabs: null,
- }
- })
-
- }
-
- constructor(options) {
-
- super(options)
-
- this.childrenType = undefined
-
- this.value = []
-
- this.on('change',(e)=>{
-
- if (e.widget === this) return
-
- var widget = this.getProp('widgetType') === 'clone' ? e.widget.parent : e.widget
-
- if (widget.parent !== this) return
-
- this.value[widget._index] = e.widget.getValue()
-
- this.changed({
- ...e.options,
- id: widget.getProp('id')
- })
-
- })
-
-
-
- this.start = parseInt(this.getProp('start'))
-
- if (parser.widgets[this.getProp('widgetType')]) {
-
- for (let i = 0; i < this.getProp('quantity'); i++) {
-
- var props = this.resolveProp('props', undefined, false, false, false, {'$':i + this.start})
- var data = this.defaultProps(i + this.start)
-
- if (typeof props === 'object' && props !== null) {
- Object.assign(data, props)
- }
-
- var widget = parser.parse({
- data: data,
- parentNode: this.widget,
- parent: this
- })
-
- widget._index = i
- widget.container.classList.add('not-editable')
- widget._not_editable = true
-
- this.value[i] = widget.getValue()
-
- }
-
- } else {
-
- this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
-
- }
-
-
-
- }
-
- defaultProps(i) {
-
- return {
- type: this.getProp('widgetType'),
- id: '@{parent.id}/' + i,
- address: '#{@{parent.address} == "auto" ? "/" + @{parent.id} : @{parent.address}}/' + i,
- preArgs: '@{parent.preArgs}',
- target: '@{parent.target}',
- decimals: '@{parent.decimals}',
- bypass: '@{parent.bypass}',
- label: i,
- top: 'auto',
- left: 'auto',
- height: 'auto',
- width: 'auto'
- }
-
- }
-
- onPropChanged(propName, options, oldPropValue) {
-
- if (super.onPropChanged(...arguments)) return true
-
- switch (propName) {
-
- case 'props':
-
- for (let i = this.children.length - 1; i >= 0; i--) {
-
- let data = this.resolveProp('props', undefined, false, false, false, {'$': i + this.start})
-
- if (typeof data !== 'object' || data === null || Array.isArray(data)) {
- data = {}
- }
-
- if (typeof oldPropValue === 'object' && oldPropValue !== null) {
- // if an overridden default props is removed, set it back to default
- let overriddenDefaults,
- widgetDefaults
- for (var k in oldPropValue) {
- if (data[k] === undefined) {
- if (Matrix.overriddenDefaults.indexOf(k) !== -1) {
- overriddenDefaults = overriddenDefaults || this.defaultProps(i + this.start)
- data[k] = overriddenDefaults[k]
- } else {
- widgetDefaults = widgetDefaults || parser.defaults[data.type || this.getProp('widgetType')]
- data[k] = deepCopy(widgetDefaults[k])
- }
- }
- }
- }
-
- Object.assign(this.children[i].props, data)
-
- this.children[i].updateProps(Object.keys(data), this, options)
- // this.children[i] might have been recreated
- this.children[i].container.classList.add('not-editable')
- this.children[i]._not_editable = true
-
- }
-
- return
-
- }
-
- }
-
-}
-
-
-
-Matrix.overriddenDefaults = [
- 'type', 'id', 'address', 'preArgs', 'target', 'decimals', 'bypass',
- 'label', 'top', 'left', 'height', 'width'
-]
-
-Matrix.parsersContexts.props = {
- $: 0
-}
-
-Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
- 'props'
-)
-
-module.exports = Matrix
diff --git a/src/client/widgets/containers/matrix.mjs b/src/client/widgets/containers/matrix.mjs
new file mode 100644
index 00000000..32cb4c24
--- /dev/null
+++ b/src/client/widgets/containers/matrix.mjs
@@ -0,0 +1,276 @@
+import Panel from './panel.mjs'
+import parser from '../../parser.mjs'
+import {deepCopy} from '../../utils.mjs'
+import Session from '../../managers/session/session.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+
+
+class Matrix extends Panel {
+
+ static description() {
+
+ return 'Generic matrix for creating rows/columns of widgets.'
+
+ }
+
+ static defaults() {
+
+ return super.defaults().extend({
+ class_specific: {
+ widgetType: {type: 'string', value: 'button', help: 'Defines the type of the widgets in the matrix'},
+ quantity: {type: 'number', value: 4, help: 'Defines the number of widgets in the matrix'},
+ props: {type: 'object', value: {label: '#{$}'}, editor: 'javascript', syntaxChecker: false, help: [
+ 'Defines a set of property to override the widgets\' defaults.',
+ 'JS{} and #{} blocks in this field are resolved with an extra variable representing each widget\'s index: `$` (e.g. `#{$}`)',
+ 'Advanced syntax blocks (@{}, OSC{}, JS{}, VAR{} and #{}) are resolved at the matrix\' scope (ie @{this.variables} returns the matrix\' variables property)',
+ 'Advanced syntax blocks can be passed to children without being resolved at the matrix\' scope by adding an underscore before the opening bracket.',
+ 'Note: unless overridden, children inherit from the matrix\' `id` and osc properties (`id` and `address` are appended with `/$`)'
+ ]},
+ },
+ style: {
+ layout: {type: 'string', value: 'horizontal', choices: ['horizontal', 'vertical', 'grid'], help: 'Defines how children are laid out.'},
+ tabsPosition: null,
+ }
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.childrenType = undefined
+
+ this.value = []
+
+ this.resolveLock = false
+
+ this.on('value-changed',(e)=>{
+
+ if (e.widget === this) return
+
+ var widget = this.getProp('widgetType') === 'clone' ? e.widget.parent : e.widget
+
+ if (widget.parent !== this) return
+
+ this.value[widget._index] = e.widget.getValue()
+
+ this.changed({
+ ...e.options,
+ id: widget.getProp('id')
+ })
+
+ })
+
+ if (parser.widgets[this.getProp('widgetType')]) {
+
+ var quantity = Math.max(parseInt(this.getProp('quantity')) || 0, 0)
+
+ for (let i = 0; i < quantity; i++) {
+
+ var props = deepCopy(this.getProp('props')[i])
+ var data = this.defaultProps(i)
+
+ if (typeof props === 'object' && props !== null) {
+ Object.assign(data, props)
+ }
+
+ data = JSON.parse(JSON.stringify(data).replace(/(JS|#|OSC|@|VAR)_\{/g, '$1{'))
+
+ Session.converters['1.13.2'].widget(data)
+
+ var widget = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this,
+ meta: {not_editable: true}
+ })
+
+ widget._index = i
+
+ this.value[i] = widget.getValue()
+
+ }
+
+ } else {
+
+ this.errors.widgetType = this.getProp('widgetType') + ' is not a valid widget type'
+
+ }
+
+
+
+ }
+
+ defaultProps(i) {
+
+ return {
+ type: this.getProp('widgetType'),
+ id: '@{parent.id}/' + i,
+ address: '#{@{parent.address} == "auto" ? "/" + @{parent.id} : @{parent.address}}/' + i,
+ preArgs: '@{parent.preArgs}',
+ target: '@{parent.target}',
+ decimals: '@{parent.decimals}',
+ bypass: '@{parent.bypass}',
+ top: 'auto',
+ left: 'auto',
+ height: 'auto',
+ width: 'auto'
+ }
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'quantity':
+
+ var quantity = Math.max(parseInt(this.getProp('quantity')) || 0, 0)
+ oldPropValue = Math.max(parseInt(oldPropValue) || 0, 0)
+
+ if (oldPropValue > quantity) {
+
+ for (let i = oldPropValue - 1; i >= quantity; i--) {
+ if (this.widget.contains(this.children[i].container)) {
+ this.widget.removeChild(this.children[i].container)
+ }
+ widgetManager.removeWidgets(this.children[i].getAllChildren().concat(this.children[i]))
+ }
+
+ } else {
+
+ this.cachedProps.props = this.resolveProp('props', undefined, true)
+
+ for (let i = oldPropValue; i < quantity; i++) {
+
+ var props = deepCopy(this.getProp('props')[i])
+ var data = this.defaultProps(i)
+
+ if (typeof props === 'object' && props !== null) {
+ Object.assign(data, props)
+ }
+
+ data = JSON.parse(JSON.stringify(data).replace(/(JS|#|OSC|@|VAR)_\{/g, '$1{'))
+
+ Session.converters['1.13.2'].widget(data)
+
+ var widget = parser.parse({
+ data: data,
+ parentNode: this.widget,
+ parent: this,
+ meta: {not_editable: true}
+ })
+
+ widget._index = i
+
+ }
+
+ }
+
+
+ return
+
+ case 'props':
+
+ for (let i = this.children.length - 1; i >= 0; i--) {
+
+ let data = deepCopy(this.getProp('props')[i])
+
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
+ data = {}
+ }
+
+ data = JSON.parse(JSON.stringify(data).replace(/(JS|#|OSC|@|VAR)_\{/g, '$1{'))
+
+ Session.converters['1.13.2'].widget(data)
+
+ if (typeof oldPropValue[i] === 'object' && oldPropValue[i] !== null) {
+ // if an overridden default props is removed, set it back to default
+ let overriddenDefaults,
+ widgetDefaults
+ for (var k in oldPropValue[i]) {
+ if (data[k] === undefined) {
+ if (Matrix.overriddenDefaults.indexOf(k) !== -1) {
+ overriddenDefaults = overriddenDefaults || this.defaultProps(i)
+ data[k] = overriddenDefaults[k]
+ } else {
+ widgetDefaults = widgetDefaults || parser.defaults[data.type || this.getProp('widgetType')]
+ data[k] = deepCopy(widgetDefaults[k])
+ }
+ }
+ }
+ }
+
+ Object.assign(this.children[i].props, data)
+
+ this.children[i].updateProps(Object.keys(data), this, options)
+
+ }
+
+ return
+
+ }
+
+ }
+
+ resolveProp(propName, propValue, storeLinks, originalWidget, originalPropName, context) {
+
+ if (propName === 'props' && !this.resolveLock) {
+
+ this.resolveLock = true
+
+ propValue = propValue !== undefined ? propValue : this.props[propName]
+
+ var data = [],
+ quantity = Math.max(parseInt(this.resolveProp('quantity', undefined, false, false, false)) || 0, 0)
+
+ if (typeof propValue === 'object' && propValue !== null && !Array.isArray(propValue)) {
+ for (let i = 0; i < quantity; i++) {
+ data[i] = {}
+ for (var k in propValue) {
+ data[i][k] = super.resolveProp(propName, deepCopy(propValue[k]), i === 0 ? storeLinks : false, originalWidget, originalPropName, {$: i})
+ }
+ }
+
+ } else {
+
+ for (let i = 0; i < quantity; i++) {
+ data[i] = super.resolveProp(propName, deepCopy(propValue), i === 0 ? storeLinks : false, originalWidget, originalPropName, {$: i})
+ }
+
+ }
+
+
+ this.resolveLock = false
+
+ return data
+
+ } else {
+
+ return super.resolveProp(propName, propValue, storeLinks, originalWidget, originalPropName, context)
+
+ }
+
+ }
+}
+
+
+
+Matrix.overriddenDefaults = [
+ 'type', 'id', 'address', 'preArgs', 'target', 'decimals', 'bypass',
+ 'label', 'top', 'left', 'height', 'width'
+]
+
+Matrix.parsersContexts.props = {
+ $: 0
+}
+
+Matrix.dynamicProps = Matrix.prototype.constructor.dynamicProps.concat(
+ 'quantity',
+ 'props'
+)
+
+export default Matrix
diff --git a/src/client/widgets/containers/modal.js b/src/client/widgets/containers/modal.mjs
similarity index 77%
rename from src/client/widgets/containers/modal.js
rename to src/client/widgets/containers/modal.mjs
index 453ef2c2..1b810164 100644
--- a/src/client/widgets/containers/modal.js
+++ b/src/client/widgets/containers/modal.mjs
@@ -1,9 +1,10 @@
-var Panel = require('./panel'),
- {icon, iconify} = require('../../ui/utils'),
- resize = require('../../events/resize'),
- doubletab = require('../mixins/double_tap'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw')
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import Panel from './panel.mjs'
+import {icon, iconify} from '../../ui/utils.mjs'
+import * as resize from '../../events/resize.mjs'
+import doubleTap from '../mixins/double_tap'
+import {DOM, PXSCALE} from '../../globals.mjs'
class Modal extends Panel {
@@ -17,7 +18,8 @@ class Modal extends Panel {
return super.defaults().extend({
class_specific: {
- doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the modal require a double tap to open instead of a single tap'},
+ doubleTap: {type: 'boolean', value: false, help: 'Set to `true` to make the modal require a double tap to open instead of a single tap (allows scrolling when touching the modal button)'},
+ click: {type: 'boolean', value: false, help: 'Set to `true` to make the modal open/close upon click event instead of tap (allows scrolling when touching the modal button)'},
},
geometry: {
_separator_modal_geometry: 'Modal geometry',
@@ -26,6 +28,7 @@ class Modal extends Panel {
popupLeft: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
popupTop: {type: 'number|percentage', value: 'auto', help: 'Modal popup\'s position'},
relative: {type: 'boolean', value: false, help: 'Set to `true` to make the modal\'s position relative to the button\'s position.'},
+ ignoreTabs: {type: 'boolean', value: false, help: 'Set to `true` to allow the modal overflowing its tab ancestors.'},
},
style: {
_separator_modal_style: 'Modal style',
@@ -36,7 +39,8 @@ class Modal extends Panel {
]},
popupLabel: {type: 'string|boolean', value: 'auto', help: 'Alternative label for the modal popup'},
popupPadding: {type: 'number', value: 'auto', help: 'Modal\'s inner spacing.'},
- verticalTabs: null,
+ tabsPosition: null,
+ html: null
},
children: {
tab: null
@@ -66,6 +70,7 @@ class Modal extends Panel {
this.container.appendChild(this.popup)
this.popupContent = DOM.get(this.popup, '.popup-content')[0]
+
// convert dimensions / coordinates to rem
var geometry = {}
for (var g of ['Width', 'Height', 'Left', 'Top']) {
@@ -87,28 +92,25 @@ class Modal extends Panel {
this.toggle = this.container.appendChild(html``)
- if (this.getProp('doubleTap')) {
- doubletab(this.toggle, ()=>{
- this.setValue(1, {sync:true, send:true})
- })
- } else {
- this.toggle.addEventListener('fast-click',(e)=>{
+ var closer = DOM.get(this.popup, '.closer')[0]
+
+ this.on(this.getProp('click') ? 'click' : 'draginit',(e)=>{
+ if ((e.target === this.popup || e.target === closer) && this.value == 1) {
+ this.setValue(0, {sync:true, send:true})
+ } else if (!this.getProp('doubleTap') && e.target === this.toggle) {
if (e.capturedByEditor === true) return
- e.detail.preventOriginalEvent = true
this.setValue(1, {sync:true, send:true})
- })
+ }
+ }, {element: this.container})
+
+ if (this.getProp('doubleTap')) {
+ doubleTap(this, ()=>{
+ this.setValue(1, {sync:true, send:true})
+ }, {element: this.toggle, click: this.getProp('click')})
}
- 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})
+ if (e.key == 'Escape') this.setValue(0, {sync:true, send:true})
}).bind(this)
this.value = 0
@@ -125,18 +127,15 @@ class Modal extends Panel {
}
-
- isVisible() {
-
- return this.init && this.value && super.isVisible()
-
- }
-
setValue(v, options={}) {
if (this.init === undefined) return
- this.value = v ? 1 : 0
+ var val = v ? 1 : 0
+
+ if (val === this.value) return
+
+ this.value = val
if (!this.init && this.value) {
this.popupContent.appendChild(this.widget)
@@ -147,6 +146,8 @@ class Modal extends Panel {
this.updatePopupLabel()
}
+ if (this.getProp('scroll') && this.value) this.scrollLock = true
+
this.popup.classList.toggle('show', this.value)
this.container.classList.toggle('on', this.value)
@@ -157,6 +158,14 @@ class Modal extends Panel {
this.setVisibility()
if (this.value) {
resize.check(this.widget, true)
+
+ if (this.getProp('scroll')) {
+ setTimeout(()=>{
+ this.scrollWidth = this.widget.scrollWidth - this.widget.clientWidth
+ this.scrollHeight = this.widget.scrollHeight - this.widget.clientHeight
+ this.setScroll(this.scroll[0], this.scroll[1], true)
+ })
+ }
}
@@ -168,18 +177,31 @@ class Modal extends Panel {
fixParents() {
- var parent = this.parent
+ var parent = this.parent,
+ scrollX = 0,
+ scrollY = 0,
+ stop = this.getProp('ignoreTabs') ? /root/ : /root|tab/
- while (parent && parent.props && !parent.getProp('type').match(/tab|root/)) {
+ while (parent && parent.props && !String(parent.getProp('type')).match(stop)) {
parent.modalBreakout += (this.value ? 1 : -1)
if (parent.modalBreakout > 0) parent.container.classList.add('modal-breakout')
else if (parent.modalBreakout === 0) parent.container.classList.remove('modal-breakout')
else parent.modalBreakout = 0
+ scrollX += parent.widget.scrollLeft
+ scrollY += parent.widget.scrollTop
+
parent = parent.parent
}
+ scrollX += parent.widget.scrollLeft
+ scrollY += parent.widget.scrollTop
+
+ if (this.getProp('relative')) {
+ this.container.style.setProperty('--parent-scroll-x', scrollX + 'px')
+ this.container.style.setProperty('--parent-scroll-y', scrollY + 'px')
+ }
this.modalBreakout += (this.value ? 1 : -1)
if (this.modalBreakout > 0) this.container.classList.add('modal-breakout')
@@ -244,6 +266,7 @@ class Modal extends Panel {
case 'label':
this.updateLabel()
+ // falls through
case 'popupLabel':
if (this.value) {
this.updatePopupLabel()
@@ -259,8 +282,6 @@ class Modal extends Panel {
}
-
-
}
Modal.cssVariables = Modal.prototype.constructor.cssVariables.concat(
@@ -273,4 +294,4 @@ Modal.dynamicProps = Modal.prototype.constructor.dynamicProps.concat(
'popupPadding'
)
-module.exports = Modal
+export default Modal
diff --git a/src/client/widgets/containers/panel.js b/src/client/widgets/containers/panel.mjs
similarity index 52%
rename from src/client/widgets/containers/panel.js
rename to src/client/widgets/containers/panel.mjs
index 1a0c7c3d..7ab1aa4c 100644
--- a/src/client/widgets/containers/panel.js
+++ b/src/client/widgets/containers/panel.mjs
@@ -1,9 +1,12 @@
-var Container = require('../common/container'),
- widgetManager = require('../../managers/widgets'),
- parser = require('../../parser'),
- html = require('nanohtml'),
- {enableTraversingGestures, disableTraversingGestures} = require('../../events/drag'),
- setScrollbarColor = require('../../ui/scrollbar-color')
+import html from 'nanohtml'
+import fastdom from 'fastdom'
+import Container from '../common/container.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+import parser from '../../parser.mjs'
+import {enableTraversingGestures, disableTraversingGestures} from '../../events/drag.mjs'
+import {setScrollbarColor} from '../../ui/utils.mjs'
+import Script from '../scripts/script.mjs'
+import {DOM} from '../../globals.mjs'
class Panel extends Container() {
@@ -18,28 +21,36 @@ class Panel extends Container() {
return super.defaults().extend({
class_specific: {
variables: {type: '*', value: '@{parent.variables}', help: 'Defines one or more arbitrary variables that can be inherited by children widgets'},
- 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'},
+ traversing: {type: 'boolean', value: false, choices: [false, true, 'smart'], help: 'Set to `true` to enable traversing gestures in this widget. Set to `smart` to limit affected widgets by the type of the first touched widget'},
},
style: {
_separator_panel_style: 'Panel style',
colorBg: {type: 'string', value: 'auto', help: 'Panel background color. Set to "auto" to inherit from parent widget.'},
layout: {type: 'string', value: 'default', choices: ['default', 'vertical', 'horizontal', 'grid'], help:'Defines how children are laid out.'},
justify: {type: 'string', value: 'start', choices: ['start', 'end', 'center', 'space-around', 'space-between'], help:'If `layout` is `vertical` or `horizontal`, defines how widgets should be justified.'},
- gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns of a value css grid-template definition.'},
+ gridTemplate: {type: 'string|number', value: '', help:'If `layout` is `grid`, can be either a number of columns or a valid value for the css property "grid-template".'},
contain: {type: 'boolean', value: true, help:'If `layout` is `vertical` or `horizontal`, prevents children from overflowing the panel.'},
- scroll: {type: 'boolean', value: true, help: 'Set to `false` to disable scrollbars'},
+ scroll: {type: 'boolean|string', value: true, choices: [true, false, 'hidden', 'manual'], help: [
+ '- `true`: scrollbars are show and content is scrollble',
+ '- `false`: scrollbars are hidden and content is not scrollble',
+ '- `"hidden"`: scrollbars are hidden (using css, may not work on old browsers) and content is scrollble',
+ '- `"manual"`: scrollbars are hidden (using css, may not work on old browsers) and content is scrollble only using scripting or scrollbar widgets',
+ ]},
innerPadding: {type : 'boolean', value: true, help: 'Set to `false` to make the `padding` property apply only between children and not at the container\'s inner boundaries.'},
- verticalTabs: {type: 'boolean', value: false, help: 'Set to `true` to display for vertical tab layout'},
+ tabsPosition: {type: 'string', value: 'top', choices: ['top', 'bottom', 'left', 'right', 'hidden'], help: 'Defines the position of the navigation bar if the panel contains tabs'},
},
value: {
- value: {type: 'integer', value: '', help: [
- 'Defines currently selected tab in the widget',
- 'A tab can be opened only by setting its parent\'s value'
+ value: {type: 'integer|array', value: '', help: [
+ 'If the panel contains tabs, its value defines which tab is selected selected (by index, starting with 0).',
+ 'If the panel contains widgets and `scroll` is `true`, its value is an array that contains the scrolling state between 0 and 1 for the x and y axis. '
]}
},
children: {
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'},
+ },
+ scripting: {
+ onTouch: {type: 'script', value: '', editor:'javascript', help: ['Script executed when the panel is touched and released, and when the pointer moves when the widget is touched. See documentation.',]},
}
})
@@ -52,8 +63,19 @@ class Panel extends Container() {
this.childrenType = ''
+ if (options.root && this.getProp('onPreload')) {
+ this.scripts.onPreload = new Script({
+ widget: this,
+ property: 'onPreload',
+ code: this.getProp('onPreload'),
+ context: {}
+ })
+ if (this.scripts.onPreload) this.scripts.onPreload.run({}, {})
+ }
+
this.container.classList.toggle('no-inner-padding', !this.getProp('innerPadding'))
- this.container.classList.toggle('no-scroll', !this.getProp('scroll'))
+ this.container.classList.toggle('no-scroll', !this.getProp('scroll') || this.getProp('scroll') == 'manual')
+ this.container.classList.toggle('hidden-scroll', this.getProp('scroll') == 'hidden')
this.container.classList.add('layout-' + this.getProp('layout'))
this.container.classList.toggle('layout-contain', this.getProp('contain'))
@@ -76,12 +98,34 @@ class Panel extends Container() {
if (this.getProp('tabs') && this.getProp('tabs').length) {
this.container.classList.add('contains-tabs')
- this.container.classList.toggle('vertical-tabs', this.getProp('verticalTabs'))
+ this.container.classList.add('tabs-' + this.getProp('tabsPosition'))
} else {
this.container.classList.add('contains-widgets')
+ if (this.getProp('scroll')) {
+ this.scrollLock = false
+ this.scrollLockTimeout = null
+ this.scroll = [0, 0]
+ this.scrollThumb = [1, 1]
+ this.scrollWidth = 1
+ this.scrollHeight = 1
+ fastdom.measure(()=>{
+ this.scrollWidth = this.widget.scrollWidth - this.widget.clientWidth
+ this.scrollHeight = this.widget.scrollHeight - this.widget.clientHeight
+ this.scrollThumb = [this.widget.clientWidth / this.widget.scrollWidth || 1, this.widget.clientHeight / this.widget.scrollHeight || 1]
+ })
+ this.on('scroll', (e)=>{
+ if (this.scrollLock) e.locked = true
+ this.scrollWidth = this.widget.scrollWidth - this.widget.clientWidth
+ this.scrollHeight = this.widget.scrollHeight - this.widget.clientHeight
+ this.scroll = [this.widget.scrollLeft / this.scrollWidth || 0, this.widget.scrollTop / this.scrollHeight || 0]
+ this.scrollThumb = [this.widget.clientWidth / this.widget.scrollWidth || 1, this.widget.clientHeight / this.widget.scrollHeight || 1]
+ }, {element: this.widget})
+
+ }
+
}
@@ -95,10 +139,12 @@ class Panel extends Container() {
this.value = -1
- this.navigation = this.widget.appendChild(html``)
+ this.navigation = this.widget.appendChild(html``)
this.children = options.children || new Array(this.getProp('tabs').length)
- for (let i = 0; i < this.children.length; i++) {
+ var tlength = this.children.length
+
+ for (let i = 0; i < tlength; i++) {
if (this.children[i]) {
this.widget.appendChild(this.children[i].container)
this.children[i].mounted = true
@@ -110,7 +156,8 @@ class Panel extends Container() {
parentNode: this.widget,
parent: this,
tab: true,
- index: i
+ index: i,
+ meta: {...this.meta}
})
}
}
@@ -119,18 +166,18 @@ class Panel extends Container() {
this.createNavigation()
- this.navigation.addEventListener('fast-click', (e)=>{
- if (!e.target.hasAttribute('data-widget')) return
+ this.on('fast-click', (e)=>{
+ if (!e.target.hasAttribute('data-widget') || e.capturedByEditor) return
var index = DOM.index(e.target)
this.setValue(index, {sync: true, send:this.value != index})
- })
+ }, {element: this.navigation})
this.on('tab-created', (e)=>{
this.createNavigation()
e.stopPropagation = true
})
- this.setValue(this.getProp('value') || 0)
+ this.setValue(Number(this.getProp('value')) || 0)
} else if (this.getProp('widgets') && this.getProp('widgets').length) {
@@ -139,7 +186,9 @@ class Panel extends Container() {
this.childrenType = 'widget'
this.children = options.children || new Array(this.getProp('widgets').length)
- for (let i = 0; i < this.children.length; i++) {
+ var wlength = this.children.length
+
+ for (let i = 0; i < wlength; i++) {
if (this.children[i]) {
this.widget.appendChild(this.children[i].container)
this.children[i].mounted = true
@@ -150,7 +199,8 @@ class Panel extends Container() {
data: this.getProp('widgets')[i],
parentNode: this.widget,
parent: this,
- index: i
+ index: i,
+ meta: {...this.meta}
})
}
}
@@ -162,6 +212,12 @@ class Panel extends Container() {
if (this.getProp('traversing')) this.setTraversing()
+ if (this.getProp('onTouch')) {
+ this.on('draginit',(e)=>this.onTouch(e, 'start'), {element: this.container, multitouch: true})
+ this.on('drag',(e)=>this.onTouch(e, 'move'), {element: this.container, multitouch: true})
+ this.on('dragend',(e)=>this.onTouch(e, 'stop'), {element: this.container, multitouch: true})
+ }
+
}
createNavigation() {
@@ -196,7 +252,8 @@ class Panel extends Container() {
}
setValue(v, options={}) {
- if (this.tabs.length && typeof v == 'number' && v >= 0 && v < this.tabs.length) {
+
+ if (this.childrenType === 'tab' && typeof v == 'number' && v >= 0 && v < this.tabs.length) {
for (let i in this.tabs) {
if (i != v) this.tabs[i].hide()
@@ -211,16 +268,74 @@ class Panel extends Container() {
if (options.sync) this.changed(options)
}
+
}
- scroll(s) {
+ getScroll() {
- if (!s) {
- return [this.widget.scrollLeft, this.widget.scrollTop]
- } else {
- if (s[0] !== undefined) this.widget.scrollLeft = s[0]
- if (s[1] !== undefined) this.widget.scrollTop = s[1]
+ return this.scroll
+
+ }
+
+ setScroll(x, y, updateDom, lock=true) {
+
+ if (x !== undefined) {
+ this.scroll[0] = x
+ if (updateDom) {
+ if (this.widget.scrollLeft != x * this.scrollWidth) {
+ this.scrollLock = !!lock
+ this.widget.scrollLeft = x * this.scrollWidth
+ }
+ }
}
+ if (y !== undefined) {
+ this.scroll[1] = y
+ if (updateDom) {
+ if (this.widget.scrollTop != y * this.scrollHeight) {
+ this.scrollLock = !!lock
+ this.widget.scrollTop = y * this.scrollHeight
+ }
+ }
+ }
+
+ // unlock scroll events only after some time to prevent smooth scrolling
+ // issues in firefox and prevent feedback loops
+ if (this.scrollLock) {
+ clearTimeout(this.scrollLockTimeout)
+ this.scrollLockTimeout = setTimeout(()=>{
+ this.scrollLock = false
+ },100)
+ }
+
+ }
+
+ onTouch(e, name) {
+
+ var event = {...e},
+ w
+
+ event.targetName = event.target ? event.target.getAttribute('name') : ''
+ event.targetTagName = event.target ? event.target.tagName : ''
+
+ w = widgetManager.getWidgetByElement(event.target)
+ if (w) event.target = w === this ? 'this' : w.getProp('id')
+ else event.target = null
+
+ w = widgetManager.getWidgetByElement(event.firstTarget)
+ if (w) event.firstTarget = w === this ? 'this' : w.getProp('id')
+ else event.firstTarget = null
+
+ event.type = name
+
+ this.scripts.onTouch.run({
+ value: this.value,
+ event: event
+ }, {sync: true, send: true})
+
+ e.inertia = parseFloat(event.inertia) || 1
+
+ if (name != 'stop' && event.preventDefault) e.preventDefault = true
+ if (event.allowScroll) e.allowScroll = true
}
@@ -236,8 +351,9 @@ class Panel extends Container() {
case 'colorBg':
this.setCssVariables()
- case 'colorText':
+ // falls through
case 'colorWidget':
+ case 'colorText':
case 'colorFill':
case 'colorStroke':
case 'alphaStroke':
@@ -274,7 +390,6 @@ class Panel extends Container() {
onRemove() {
- this.off('resize')
super.onRemove()
}
@@ -286,4 +401,4 @@ Panel.dynamicProps = Panel.prototype.constructor.dynamicProps.concat(
'traversing'
)
-module.exports = Panel
+export default Panel
diff --git a/src/client/widgets/containers/patchbay.js b/src/client/widgets/containers/patchbay.mjs
similarity index 68%
rename from src/client/widgets/containers/patchbay.js
rename to src/client/widgets/containers/patchbay.mjs
index eb810919..cc10fc29 100644
--- a/src/client/widgets/containers/patchbay.js
+++ b/src/client/widgets/containers/patchbay.mjs
@@ -1,9 +1,10 @@
-var Widget = require('../common/widget'),
- Canvas = require('../common/canvas'),
- Container = require('../common/container'),
- {iconify} = require('../../ui/utils'),
- parser = require('../../parser'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import Canvas from '../common/canvas.mjs'
+import Container from '../common/container.mjs'
+import {iconify} from '../../ui/utils.mjs'
+import parser from '../../parser.mjs'
+import {DOM, PXSCALE} from '../../globals.mjs'
class PatchBayNode extends Widget {
@@ -32,13 +33,35 @@ class PatchBayNode extends Widget {
this.value = Array.isArray(v) ? v : v ? [v] : []
- var allowed = this.parent.getProp('outputs')
+ var allowed = this.parent.outputsValues
for (var i = this.value.length -1; i > -1; i--) {
if (allowed.indexOf(this.value[i]) === -1) {
this.value.splice(i, 1)
}
}
+ if (
+ (this.parent.getProp('exclusive') === true
+ || this.parent.getProp('exclusive') === 'in'
+ || this.parent.getProp('exclusive') === 'both')
+ && this.value.length > 1
+ ) {
+ this.value = [this.value.pop()]
+ }
+
+ if (
+ (this.parent.getProp('exclusive') === 'out' || this.parent.getProp('exclusive') === 'both')
+ && this.value.length > 0
+ ) {
+ for (var input of this.parent.inputsWidgets) {
+ if (input !== this && input.value.some(x=>this.value.includes(x))) {
+ input.setValue(input.value.filter(x=>!this.value.includes(x)), options)
+ }
+ }
+ }
+
+
+
this.parent.batchDraw()
if (options.send) this.sendValue()
@@ -73,27 +96,33 @@ class PatchBay extends Container(Canvas) {
static defaults() {
- return super.defaults().extend({
- style: {
- css: {type: 'string', value: '', help: [
- 'The inputs/ouputs width can be adjusted by using the `.nodes` selector:',
- '`.nodes { width: 25% }`',
- ]}
- },
+ var defaults = super.defaults().extend({
class_specific: {
inputs: {type: 'array|object', value: ['input_1', 'input_2'], help: [
'- `Array` of input names : `[\'input_1\', \'input_2\']`',
- '- `Object` of `"label_1": "input_1"` pairs. Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
+ '- `Object` of `"label_1": "input_1"` pairs (example: `{"label a": "name 1", "label b": "name 2"}`). Numeric labels must be prepended or appended with a white space (or any other non-numeric character) otherwise the order of the values won\'t be kept',
'',
'Patchbay inputs can be connected to one or more outputs and will send messages of the following form when they are connected/disconnected: ',
'`/patchbay_address input_x output_x output_y etc`',
'If no output is connected to the input, the message will be `/patchbay_address input_x`',
- 'The inputs values can be consumed with the property inheritance syntax: `@{patchbay_id/input_1}` returns an array of output names connected to `input_1`'
+ 'The inputs values can be consumed with the property inheritance syntax: `@{patchbay_id/input_1}` returns an array of output names connected to `input_1`.',
+ 'To change connections via scripting, one must target the input nodes as follows: `set(\'patchbay_id/input_name\', [\'output_x\', \'output_y\'])`'
]},
outputs: {type: 'array|object', value: ['output_1', 'output_2'], help: 'List of output values the inputs can connect to (see `inputs`).'},
+ exclusive: {type: 'string', value: false, choices: [false, 'in', 'out', 'both'], help: [
+ '- `in`: allows only one connection per input',
+ '- `out`: allows only one connection per output',
+ '- `both`: allows only one connection per input and output'
+ ]}
}
})
+ defaults.style.css.help.concat(
+ 'The inputs/outputs width can be adjusted by using the `.nodes` selector:',
+ '`.nodes { width: 25% }`',
+ )
+
+ return defaults
}
static normalizeArrayObject(obj) {
@@ -133,26 +162,28 @@ class PatchBay extends Container(Canvas) {
this.inputNodes = []
this.outputNodes = []
+ this.value = {}
for (let k in this.inputs) {
let w = parser.parse({
data: {
type: 'patchbaynode',
+ comments: this.inputs[k], // TODO: using comment prop to smuggle input identifier, ok but could be more elegant
id: this.getProp('id') + '/' + this.inputs[k],
- address: '@{parent.address}',
+ address: '#{@{parent.address} == "auto" ? "/" + @{parent.id} : @{parent.address}}',
target: '@{parent.target}',
- preArgs: this.inputs[k],
+ ignoreDefaults: '@{parent.ignoreDefaults}',
+ preArgs: '#{@{parent.preArgs} == "" ? @{this.comments} : Array.isArray(@{parent.preArgs}) ? @{parent.preArgs}.concat(@{this.comments}) : [@{parent.preArgs}, @{this.comments}]}',
bypass: '@{parent.bypass}',
label: k
-
},
parentNode: DOM.get(this.widget, '.inputs')[0],
- parent: this
+ parent: this,
+ meta: {not_editable: true}
})
- w.container.classList.add('not-editable')
- w._not_editable = true
this.inputsWidgets.push(w)
this.inputNodes.push(w.container)
+ this.value[k] = []
}
var outputs = DOM.get(this.widget, '.outputs')[0]
@@ -168,34 +199,56 @@ class PatchBay extends Container(Canvas) {
this.connecting = []
-
- this.widget.addEventListener('fast-click', (e)=>{
- this.toggleConnection(e.target)
- e.stopPropagation()
- })
-
-
this.mousePosition = []
+ this.dragging = false
+
+ this.on('draginit', (e)=>{
+ this.toggleConnection(e.target)
+ if (e.target === this.canvas) {
+ this.mousePosition = [e.offsetX, e.offsetY]
+ } else {
+ if (this.inputNodes.includes(e.target)) {
+ this.mousePosition = [e.offsetX - e.target.offsetWidth, e.offsetY + e.target.offsetTop]
+ } else {
+ this.mousePosition = [e.offsetX + this.canvas.offsetWidth, e.offsetY + e.target.offsetTop]
+ }
+ }
+ }, {element: this.widget})
+
this.on('drag', (e)=>{
if (!this.connecting.length) {
this.toggleConnection(e.target)
}
- if (e.target === this.canvas) {
- this.mousePosition = [e.offsetX, e.offsetY]
- } else if (this.mousePosition.length) {
- this.mousePosition[0] += e.movementX
- this.mousePosition[1] += e.movementY
- }
+ this.mousePosition[0] += e.movementX
+ this.mousePosition[1] += e.movementY
+ this.dragging = true
this.batchDraw()
}, {element: this.widget})
+
this.on('dragend', (e)=>{
- if (this.mousePosition.length) {
+
+ if (this.dragging) {
+ // touch hover fix
+ var node = e.isTouch ? document.elementFromPoint(e.clientX, e.clientY) : e.target
+
this.mousePosition = []
- this.toggleConnection(e.target)
+ this.toggleConnection(node)
}
+ this.dragging = false
}, {element: this.widget})
+ this.on('value-changed',(e)=>{
+
+ if (e.widget === this || e.widget.parent !== this) return
+
+ var k = e.widget.getProp('label')
+ this.value[k] = e.widget.getValue()
+
+ this.changed(e.options)
+
+ })
+
}
toggleConnection(node) {
@@ -218,14 +271,6 @@ class PatchBay extends Container(Canvas) {
this.batchDraw()
}
- if (this.connecting.length) {
- var cb = (e)=>{
- this.toggleConnection()
- document.removeEventListener('fast-click', cb)
- }
- document.addEventListener('fast-click', cb)
- }
-
}
draw() {
@@ -329,7 +374,7 @@ class PatchBay extends Container(Canvas) {
}
-module.exports = {
+export {
PatchBay,
PatchBayNode
}
diff --git a/src/client/widgets/containers/root.js b/src/client/widgets/containers/root.js
deleted file mode 100644
index 875d54cf..00000000
--- a/src/client/widgets/containers/root.js
+++ /dev/null
@@ -1,69 +0,0 @@
-var Panel = require('./panel'),
- StaticProperties = require('../mixins/static_properties')
-
-class Root extends StaticProperties(Panel, {visible: true, label: false, id: 'root'}) {
-
- static description() {
-
- return 'Main (unique) container'
-
- }
-
- static defaults() {
-
- return super.defaults().extend({
- widgets: {
- visible: null,
- },
- geometry: {
- left: null,
- top: null,
- expand: null,
- },
- style: {
- colorFill: null,
- colorStroke: null,
- alphaStroke: null,
- alphaFillOff: null,
- lineWidth: null
- }
- })
-
- }
-
- constructor(options) {
-
- options.root = true
- options.props.id = 'root'
-
- super(options)
-
- this.widget.classList.add('root')
-
-
- DOM.each(this.widget, '> .navigation', (el)=>{
- el.classList.add('main')
- })
-
- }
-
- isVisible() {
-
- return true
-
- }
-
-
- setContainerStyles(styles) {
-
- super.setContainerStyles(styles)
-
- this.container.classList.toggle('auto-height', this.getProp('height') === 'auto')
-
- }
-
-
-}
-
-
-module.exports = Root
diff --git a/src/client/widgets/containers/root.mjs b/src/client/widgets/containers/root.mjs
new file mode 100644
index 00000000..c61cdea5
--- /dev/null
+++ b/src/client/widgets/containers/root.mjs
@@ -0,0 +1,120 @@
+import Panel from './panel.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {updateMobileThemeColor} from '../../ui/utils.mjs'
+import {DOM} from '../../globals.mjs'
+
+var mainMenu
+;(async()=>{
+ mainMenu = (await import('../../ui/main-menu.mjs')).default
+})()
+
+class Root extends StaticProperties(Panel, {visible: true, label: false, id: 'root'}) {
+
+ static description() {
+
+ return 'Main (unique) container'
+
+ }
+
+ static defaults() {
+
+ return super.defaults().extend({
+ widgets: {
+ visible: null,
+ },
+ geometry: {
+ left: null,
+ top: null,
+ expand: null,
+ },
+ style: {
+ colorFill: null,
+ colorStroke: null,
+ alphaStroke: null,
+ alphaFillOff: null,
+ lineWidth: null,
+ _separator_root_style: 'Root style',
+ hideMenu: {type: 'boolean', value: false, help: 'Set to `true` to hide the main menu button.'},
+
+ },
+ scripting: {
+ onPreload: {type: 'script', value: '', editor: 'javascript', help: ['Script executed before any other widget is created. See documentation.']},
+ }
+ })
+
+ }
+
+ constructor(options) {
+
+ options.root = true
+ options.props.id = 'root'
+
+ super(options)
+
+ this.widget.classList.add('root')
+ this.root = true
+
+ this.checkMenuVisibility()
+
+ DOM.each(this.widget, '> .navigation', (el)=>{
+ el.classList.add('main')
+ })
+
+ }
+
+ checkMenuVisibility() {
+
+ if (this.getProp('hideMenu')) {
+ mainMenu.container.style.display = 'none'
+ } else {
+ mainMenu.container.style.display = ''
+ }
+
+ }
+
+ isVisible() {
+
+ return true
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'hideMenu':
+ this.checkMenuVisibility()
+ return
+ case 'colorBg':
+ updateMobileThemeColor(this)
+
+ }
+
+ }
+
+
+ setContainerStyles(styles) {
+
+ super.setContainerStyles(styles)
+
+ this.container.classList.toggle('auto-height', this.getProp('height') === 'auto')
+
+ }
+
+ setCssVariables() {
+
+ super.setCssVariables()
+ updateMobileThemeColor(this)
+
+ }
+
+}
+
+Root.dynamicProps = Root.prototype.constructor.dynamicProps.concat(
+ 'hideMenu'
+)
+
+
+export default Root
diff --git a/src/client/widgets/containers/tab.js b/src/client/widgets/containers/tab.mjs
similarity index 88%
rename from src/client/widgets/containers/tab.js
rename to src/client/widgets/containers/tab.mjs
index 5bdda4c5..35f113c9 100644
--- a/src/client/widgets/containers/tab.js
+++ b/src/client/widgets/containers/tab.mjs
@@ -1,12 +1,12 @@
-var Panel = require('./panel'),
- resize = require('../../events/resize'),
- {iconify} = require('../../ui/utils')
+import Panel from './panel.mjs'
+import * as resize from '../../events/resize.mjs'
+import {iconify} from '../../ui/utils.mjs'
class Tab extends Panel {
static description() {
- return 'Tabbed panel widget'
+ return 'Tabbed panel widget.mjs'
}
@@ -59,6 +59,7 @@ class Tab extends Panel {
hide() {
if (this.detached) return
this.container.classList.remove('show')
+ this.container.removeChild(this.widget)
this.detached = true
this.setVisibility()
}
@@ -66,6 +67,7 @@ class Tab extends Panel {
show() {
if (!this.detached) return
this.container.classList.add('show')
+ this.container.appendChild(this.widget)
this.detached = false
this.setVisibility()
resize.check(this.widget, true)
@@ -85,8 +87,10 @@ class Tab extends Panel {
case 'label':
this.updateLabel()
+ // falls through
case 'visible':
resize.check(this.widget, true)
+ // falls through
case 'colorText':
case 'colorWidget':
case 'colorFill':
@@ -107,4 +111,4 @@ Tab.dynamicProps = Tab.prototype.constructor.dynamicProps.concat(
'label'
)
-module.exports = Tab
+export default Tab
diff --git a/src/client/widgets/frames/frame.js b/src/client/widgets/frames/frame.mjs
similarity index 61%
rename from src/client/widgets/frames/frame.js
rename to src/client/widgets/frames/frame.mjs
index 87821e1a..4fc9f616 100644
--- a/src/client/widgets/frames/frame.js
+++ b/src/client/widgets/frames/frame.mjs
@@ -1,19 +1,24 @@
-var Widget = require('../common/widget'),
- html = require('nanohtml'),
- locales = require('../../locales'),
- StaticProperties = require('../mixins/static_properties')
+import Widget from '../common/widget'
+import html from 'nanohtml'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {DOM} from '../../globals.mjs'
class Frame extends StaticProperties(Widget, {bypass: true}) {
static description() {
- return 'Embed a page in a frame (local network only).'
+ return 'Embed a web page in a frame. Note: some websites do not allow this.'
}
static defaults() {
return super.defaults().extend({
+ class_specific: {
+ allow: {type: 'string', value: '', help: [
+ 'Content for the iframe element\'s allow attribute',
+ ]},
+ },
value: {
value: {type: 'string', value: '', help: [
'External web page URL.',
@@ -40,9 +45,8 @@ class Frame extends StaticProperties(Widget, {bypass: true}) {
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, '.frame')[0]
- this.errorText = html`${locales('iframe_unauthorized')}`
- this.errorTextMounted = false
+ if (this.getProp('allow')) this.frame.setAttribute('allow', this.getProp('allow'))
}
@@ -52,16 +56,8 @@ class Frame extends StaticProperties(Widget, {bypass: true}) {
if (this.value) {
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)
@@ -71,4 +67,4 @@ class Frame extends StaticProperties(Widget, {bypass: true}) {
}
-module.exports = Frame
+export default Frame
diff --git a/src/client/widgets/frames/html.js b/src/client/widgets/frames/html.mjs
similarity index 63%
rename from src/client/widgets/frames/html.js
rename to src/client/widgets/frames/html.mjs
index c5f9118a..283ec572 100644
--- a/src/client/widgets/frames/html.js
+++ b/src/client/widgets/frames/html.mjs
@@ -1,16 +1,8 @@
-var Widget = require('../common/widget'),
- morph = require('nanomorph'),
- html = require('nanohtml'),
- sanitizeHtml = require('sanitize-html'),
- StaticProperties = require('../mixins/static_properties')
-
-var sanitizeOptions = {
- allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img', 'h1', 'h2']).filter(x=>x!=='iframe'),
- allowedAttributes: {
- '*': [ 'title', 'class', 'style'],
- 'img': [ 'src' , 'title', 'class', 'style', 'width', 'height']
- }
-}
+import morph from 'nanomorph'
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {DOM} from '../../globals.mjs'
class Html extends StaticProperties(Widget, {bypass: true}) {
@@ -38,12 +30,12 @@ class Html extends StaticProperties(Widget, {bypass: true}) {
super({...options, html: html`
-
+
`})
this.noValueState = true
-
+
if (!this.getProp('border')) this.container.classList.add('noborder')
this.frame = DOM.get(this.widget, '.frame')[0]
@@ -57,7 +49,7 @@ class Html extends StaticProperties(Widget, {bypass: true}) {
var newHtml = this.frame.cloneNode(false)
- newHtml.innerHTML = sanitizeHtml(this.getProp('html'), sanitizeOptions)
+ newHtml.innerHTML = this.getProp('html')
morph(this.frame, newHtml)
@@ -80,4 +72,4 @@ class Html extends StaticProperties(Widget, {bypass: true}) {
}
-module.exports = Html
+export default Html
diff --git a/src/client/widgets/frames/image.js b/src/client/widgets/frames/image.mjs
similarity index 69%
rename from src/client/widgets/frames/image.js
rename to src/client/widgets/frames/image.mjs
index 005076d8..9eae72c4 100644
--- a/src/client/widgets/frames/image.js
+++ b/src/client/widgets/frames/image.mjs
@@ -1,9 +1,10 @@
-var Widget = require('../common/widget'),
- html = require('nanohtml'),
- {urlParser} = require('../utils'),
- StaticProperties = require('../mixins/static_properties')
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import {urlParser} from '../utils.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {DOM} from '../../globals.mjs'
-module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
+export default class Image extends StaticProperties(Widget, {bypass: true}) {
static description() {
@@ -16,9 +17,9 @@ module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
return super.defaults().extend({
style: {
_separator_image_style: 'Image style',
- size: {type: 'string', value: 'cover', help: 'CSS background-size'},
- position: {type: 'string', value: 'center', help: 'CSS background-position'},
- repeat: {type: 'string', value: 'no-repeat', help: 'CSS background-repeat'},
+ size: {type: 'string', value: 'cover', choices: ['cover', 'contain', 'auto'], help: 'CSS background-size'},
+ position: {type: 'string', value: 'center', choices: ['center', 'left', 'right', 'top', 'bottom', 'left top', 'left bottom', 'right top', 'right bottom'], help: 'CSS background-position'},
+ repeat: {type: 'string', value: 'no-repeat', choices: ['no-repeat', 'repeat', 'repeat-x', 'repeat-y', 'space', 'round'], help: 'CSS background-repeat'},
},
class_specific: {
cache: {type: 'boolean', value: true, help: [
@@ -28,8 +29,9 @@ module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
},
value: {
value: {type: 'string', value: '', help: [
- '- File `url` or `path` (relative to the session file location by default, falling back to absolute path)',
- '- Base64 encoded image : `data:image/...`'
+ '- File `url` or `path` (relative to the session or theme file location by default, falling back to absolute path)',
+ '- Base64 encoded image : `data:image/...`',
+ '- Enter "qrcode" to display the server\'s address QR code'
]}
},
osc: {
@@ -68,7 +70,7 @@ module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
if (!s.length) {
- this.value = this.getProp('default')
+ this.value = String(this.getProp('default'))
} else if (s != 'reload') {
@@ -87,7 +89,7 @@ module.exports = class Image extends StaticProperties(Widget, {bypass: true}) {
var url = this.value,
parser = urlParser(url)
- // escpape windows absolute file paths
+ // escape windows absolute file paths
if (!parser.protocol.match(/http|data/)) url = url.replace(':', '_:_')
url = url.replace(/\\/g, '\\\\')
diff --git a/src/client/widgets/frames/svg.js b/src/client/widgets/frames/svg.mjs
similarity index 90%
rename from src/client/widgets/frames/svg.js
rename to src/client/widgets/frames/svg.mjs
index 1bca1d9a..443cd3ef 100644
--- a/src/client/widgets/frames/svg.js
+++ b/src/client/widgets/frames/svg.mjs
@@ -1,7 +1,8 @@
-var Widget = require('../common/widget'),
- morph = require('nanomorph'),
- html = require('nanohtml'),
- StaticProperties = require('../mixins/static_properties')
+import morph from 'nanomorph'
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {DOM} from '../../globals.mjs'
class Svg extends StaticProperties(Widget, {bypass: true}) {
@@ -111,4 +112,4 @@ Svg.dynamicProps = Svg.prototype.constructor.dynamicProps.concat(
'svg'
)
-module.exports = Svg
+export default Svg
diff --git a/src/client/widgets/graphs/eq.js b/src/client/widgets/graphs/eq.mjs
similarity index 63%
rename from src/client/widgets/graphs/eq.js
rename to src/client/widgets/graphs/eq.mjs
index 343a667d..b3c0263c 100644
--- a/src/client/widgets/graphs/eq.js
+++ b/src/client/widgets/graphs/eq.mjs
@@ -1,6 +1,6 @@
-var {mapToScale} = require('../utils'),
- Plot = require('./plot'),
- StaticProperties = require('../mixins/static_properties')
+import {mapToScale} from '../utils.mjs'
+import Plot from './plot.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smooth:true}) {
@@ -14,7 +14,7 @@ class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smoo
return super.defaults().extend({
widget: {
- interaction: null
+ interaction: {value: false}
},
class_specific: {
filters: {type: 'array', value: '', help: [
@@ -24,13 +24,20 @@ class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smoo
'- `q`: number (Q factor, default: 1)',
'- `gain`: number (default: 0)',
'- `on`: boolean (default: true)',
+ '- `poles`: if `type` is "highpass" or "lowpass", indicates the number of poles for the filter (if omitted or 0, a biquad filter with Q factor is used). Set to 1 for 6dB/octaves roll-off, 2 for 12dB/octaves, etc.',
'See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode'
]},
pips: {type: 'boolean', value: true, help: 'Set to false to hide the scale'},
- rangeX: {type: 'object', value: {min: 20, max: 22000}, help: 'Defines the min and max values for the x axis (in Hz, logarithmic scale)'},
+ rangeX: {type: 'object', value: {min: 20, max: 22000}, help: [
+ 'Defines the min and max values for the x axis (in Hz, logarithmic scale)',
+ 'The sampling frequency used to compute the response curve will be 2 * rangeX.max',
+
+ ]},
rangeY: {type: 'object', value: {min:-6, max:6}, help: 'Defines the min and max values for the y axis (in dB)'},
origin: {type: 'number|boolean', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
+ logScaleX: null,
+ logScaleY: null
},
osc: {
decimals: null,
@@ -46,54 +53,72 @@ class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smoo
super(options)
- this.calcResponse()
+ this.setupArrays()
+ this.calcPending = true
+ this.batchDraw()
+
+ }
+
+ setupArrays() {
+
+ this.freqs = new Float32Array(this.width)
+ this.value = new Float32Array(this.width).fill(0)
+
+ var i,
+ min = this.getProp('rangeX').min,
+ max = this.getProp('rangeX').max,
+ width = this.width
+
+ for (i = 0; i < width; ++i) {
+ this.freqs[i] = mapToScale(i, [0, width], [min, max], -1, true)
+ }
}
calcResponse() {
- var resolution = this.width,
- frequencyHz = new Float32Array(resolution),
- filterResponse = new Float32Array(resolution).fill(0)
-
- for (let i = 0; i < resolution; ++i) {
- frequencyHz[i] = mapToScale(i, [0, this.width], [this.getProp('rangeX').min, this.getProp('rangeX').max], -1, true)
- }
+ this.value.fill(0)
for (let filter of this.getProp('filters')) {
if (filter.on !== undefined && !filter.on) continue
+ var poles = 1,
+ type = filter.type
+
+ if ((type === 'lowpass' || type === 'highpass') && filter.poles !== undefined && filter.poles !== 0) {
+ poles = Math.max(parseInt(filter.poles), 1)
+ type += '-1p'
+ }
+
biquadResponse({
- type: filter.type || 'peak',
+ type: type || 'peak',
gain: filter.gain || 0,
frequency: filter.freq || 1000,
- q: filter.q || 1
- }, frequencyHz, filterResponse)
-
+ q: filter.q || 1,
+ poles,
+ Fs: this.getProp('rangeX').max * 2
+ }, this.freqs, this.value)
}
- this.setValue(filterResponse, {sync: true})
-
-
-
}
- setValue(v, options={}) {
-
- if (!(v instanceof Float32Array) && !(Array.isArray(v)) || v.length !== this.width) return
-
- this.value = v
- this.batchDraw()
-
- if (options.sync) this.changed(options)
-
+ draw() {
+ if (this.calcPending) {
+ this.calcResponse()
+ this.calcPending = false
+ }
+ super.draw()
}
resizeHandle(event){
super.resizeHandle(event)
- if (this.width !== this.value.length) this.calcResponse()
+ if (this.width !== this.value.length) {
+ this.setupArrays()
+ this.calcPending = true
+ this.batchDraw()
+ }
}
@@ -103,7 +128,8 @@ class Eq extends StaticProperties(Plot, {logScaleX: false, logScaleY:false, smoo
switch (propName) {
case 'filters':
- this.calcResponse()
+ this.calcPending = true
+ this.batchDraw()
return
}
@@ -116,17 +142,17 @@ Eq.dynamicProps = Eq.prototype.constructor.dynamicProps.concat(
'filters'
)
-module.exports = Eq
+export default Eq
// biquadResponse
-// Based on code by Nigel Redmon Dec 14, 2010 njr
+// Based on code by Nigel Redmon @ https://www.earlevel.com
function biquadResponse(options, frequencyHz, filterResponse) {
- var {type, frequency, q, gain} = options,
- Fs = 44100,
+ var {type, frequency, q, gain, Fs, poles} = options,
len = frequencyHz.length,
- a0, a1, a2, b1, b2,norm
+ a0, a1, a2, b1, b2,norm,
+ w, phi, y, i
var V = Math.pow(10, Math.abs(gain) / 20)
var K = Math.tan(Math.PI * frequency / Fs)
@@ -150,6 +176,31 @@ function biquadResponse(options, frequencyHz, filterResponse) {
b2 = (1 - K / q + K * K) * norm
break
+ case 'lowpass-1p':
+ // b1 = Math.exp(-2.0 * Math.PI * (frequency / Fs))
+ // a0 = 1.0 - b1
+ // b1 = -b1
+ // a1 = a2 = b2 = 0
+ // using lowpass 1p1z instead
+ norm = 1 / (1 / K + 1)
+ a0 = a1 = norm
+ b1 = (1 - 1 / K) * norm
+ a2 = b2 = 0
+ break
+
+ case 'highpass-1p':
+ // b1 = -Math.exp(-2.0 * Math.PI * (0.5 - frequency / Fs))
+ // a0 = 1.0 + b1
+ // b1 = -b1
+ // a1 = a2 = b2 = 0
+ // using highpass 1p1z instead
+ norm = 1 / (K + 1)
+ a0 = norm
+ a1 = -norm
+ b1 = (K - 1) * norm
+ a2 = b2 = 0
+ break
+
case 'bandpass':
norm = 1 / (1 + K / q + K * K)
a0 = K / q * norm
@@ -224,18 +275,17 @@ function biquadResponse(options, frequencyHz, filterResponse) {
break
}
- for (var i = 0; i < len; i++) {
- var w = mapToScale(frequencyHz[i], [0, Fs / 2], [0, Math.PI], -1, false),
- 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)
+ for (i = 0; i < len; i++) {
+
+ w = mapToScale(frequencyHz[i], [0, Fs / 2], [0, Math.PI], -1, false),
+ 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
-
- filterResponse[i] += y
+ filterResponse[i] += y * poles
}
diff --git a/src/client/widgets/graphs/plot.js b/src/client/widgets/graphs/plot.mjs
similarity index 74%
rename from src/client/widgets/graphs/plot.js
rename to src/client/widgets/graphs/plot.mjs
index 32f28f20..6259a00e 100644
--- a/src/client/widgets/graphs/plot.js
+++ b/src/client/widgets/graphs/plot.mjs
@@ -1,9 +1,10 @@
-var {mapToScale} = require('../utils'),
- Canvas = require('../common/canvas'),
- html = require('nanohtml'),
- StaticProperties = require('../mixins/static_properties')
+import html from 'nanohtml'
+import {mapToScale} from '../utils.mjs'
+import Canvas from '../common/canvas.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {PXSCALE, JSON5} from '../../globals.mjs'
-module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, interaction: false}) {
+export default class Plot extends StaticProperties(Canvas, {bypass: true}) {
static description() {
@@ -15,7 +16,7 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte
return super.defaults().extend({
widget: {
- interaction: null
+ interaction: {value: false}
},
style: {
_separator_plot_style: 'Plot style',
@@ -24,27 +25,18 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte
pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
},
class_specific: {
- filters: {type: 'array', value: '', help: [
- 'Each item must be an object with the following properties',
- '- `type`: string ("highpass", "highshelf", "lowpass", "lowshelf", "peak", "bandpass" or "notch", default: "peak")',
- '- `freq`: number (filter\'s resonant frequency, default: 1000)',
- '- `q`: number (Q factor, default: 1)',
- '- `gain`: number (default: 0)',
- '- `on`: boolean (default: true)',
- 'See https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode'
-
- ]},
- pips: {type: 'boolean', value: true, help: 'Set to false to hide the scale'},
- rangeX: {type: 'object', value: {min: 20, max: 22000}, help: 'Defines the min and max values for the x axis (in Hz, logarithmic scale)'},
- rangeY: {type: 'object', value: {min:-6, max:6}, help: 'Defines the min and max values for the y axis (in dB)'},
+ rangeX: {type: 'object', value: {min: 0, max: 1}, help: 'Defines the min and max values for the x axis'},
+ rangeY: {type: 'object', value: {min: 0, max:1}, help: 'Defines the min and max values for the y axis'},
+ logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
origin: {type: 'number|boolean', value: 'auto', help: 'Defines the y axis origin. Set to `false` to disable it'},
},
value: {
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',
+ '- `Array` of `y` values: `[y1, y2, ...]`',
+ '- `Array` of `[x, y]` `array` values: `[[x1 , y1], [x2, y2], ...]`',
+ '- `String` `array`: `"[y1, y2, ...]"` or `"[[x1 , y1], [x2, y2], ...]"`',
+ '- `String` `object` to update specific coordinates only: `"{0: y1, 1: y2}"` or `"{0: [x1, y1], 1: [x2, y2]}"`',
]}
},
osc: {
@@ -132,23 +124,21 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte
var points = [],
padding = this.cssVars.padding + this.cssVars.lineWidth,
- decimals = this.getProp('smooth') ? 1 : 0,
length = this.value.length,
x, y, i, previousValue, nx, ny
for (i = 0; i < length; i++) {
if (this.value[i].length) {
- points.push(mapToScale(this.value[i][0], [this.rangeX.min, this.rangeX.max], [padding, this.width - padding], decimals, this.logScaleX, true))
- points.push(mapToScale(this.value[i][1], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], decimals, this.logScaleY, true))
+ points.push(mapToScale(this.value[i][0], [this.rangeX.min, this.rangeX.max], [padding, this.width - padding], -1, this.logScaleX, true))
+ points.push(mapToScale(this.value[i][1], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], -1, this.logScaleY, true, true))
} else {
if (i < length - 2 && this.value[i] === previousValue && this.value[i+1] === previousValue) {
continue
}
-
- nx = mapToScale(i, [0, this.value.length - 1], [padding, this.width - padding], decimals, this.logScaleX, true)
- ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], decimals, this.logScaleY, true)
+ nx = mapToScale(i, [0, this.value.length - 1], [padding, this.width - padding], -1, this.logScaleX, true)
+ ny = mapToScale(this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], -1, this.logScaleY, true, true)
if (x !== nx || y !== ny) {
points.push(nx)
@@ -212,21 +202,23 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte
draw_bars() {
- var barWidth = Math.round(this.width / this.value.length),
+ var padding = this.cssVars.padding,
+ barWidth = Math.round((this.width - padding * 2) / this.value.length),
offset = Math.round((this.width - barWidth * this.value.length) / 2)
- var origin = mapToScale(this.getProp('origin') !== false ? this.getProp('origin') : this.rangeY.min, [this.rangeY.min,this.rangeY.max],[this.height,0],0,this.getProp('logScaleY'),true)
+
+ var origin = mapToScale(this.getProp('origin') !== false ? this.getProp('origin') : this.rangeY.min, [this.rangeY.min, this.rangeY.max],[this.height - padding, padding], 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)
+ var y = mapToScale(this.value[i].length ? this.value[i][1] : this.value[i], [this.rangeY.min, this.rangeY.max], [this.height - 2 * PXSCALE - padding, 2 * PXSCALE + padding], 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.fillStyle = this.cssVars.colorWidget
this.ctx.fill()
}
@@ -235,7 +227,7 @@ module.exports = class Plot extends StaticProperties(Canvas, {bypass: true, inte
if (typeof v == 'string') {
try {
- v = JSON.parseFlex(v)
+ v = JSON5.parse(v)
} catch(err) {}
}
diff --git a/src/client/widgets/graphs/visualizer.js b/src/client/widgets/graphs/visualizer.mjs
similarity index 85%
rename from src/client/widgets/graphs/visualizer.js
rename to src/client/widgets/graphs/visualizer.mjs
index cb1aafa3..7ab31d75 100644
--- a/src/client/widgets/graphs/visualizer.js
+++ b/src/client/widgets/graphs/visualizer.mjs
@@ -1,10 +1,11 @@
-var {clip} = require('../utils'),
- Plot = require('./plot'),
- StaticProperties = require('../mixins/static_properties'),
- canvasQueue = require('../common/queue')
+import {clip} from '../utils.mjs'
+import Plot from './plot.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import canvasQueue from '../common/queue.mjs'
+import {CANVAS_FRAMERATE} from '../../globals.mjs'
-class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dots: false, smooth: false, interaction: false}) {
+class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dots: false, smooth: false}) {
static description() {
@@ -16,11 +17,11 @@ class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dot
return super.defaults().extend({
widget: {
- interaction: null
+ interaction: {value: false}
},
style: {
- _separator_visualizer_style: 'Visualizer style',
- pips:{type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ bars: null,
+ dots: null,
},
class_specific: {
duration: {type: 'number', value: 1, help: 'Defines visualization duration in seconds'},
@@ -54,7 +55,7 @@ class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dot
this.watchDuration = 1000 * this.getProp('duration')
this.ticks = 0
- this.bindedLoop = this.loop.bind(this)
+ this.boundLoop = this.loop.bind(this)
}
@@ -63,7 +64,7 @@ class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dot
this.clock = Date.now()
if (!this.looping && !this.getProp('freeze')) {
this.lastUpdate = Date.now()
- canvasQueue.on('frame', this.bindedLoop)
+ canvasQueue.on('frame', this.boundLoop)
if (!canvasQueue.running) canvasQueue.startLoop()
this.looping = true
this.ticks = 0
@@ -74,7 +75,7 @@ class Visualizer extends StaticProperties(Plot, {rangeX: {min: '', max: ''}, dot
if (this.looping) {
- canvasQueue.off('frame', this.bindedLoop)
+ canvasQueue.off('frame', this.boundLoop)
this.looping = false
}
@@ -168,4 +169,4 @@ Visualizer.dynamicProps = Visualizer.prototype.constructor.dynamicProps.concat(
'freeze'
)
-module.exports = Visualizer
+export default Visualizer
diff --git a/src/client/widgets/index.js b/src/client/widgets/index.js
deleted file mode 100644
index 2a40455a..00000000
--- a/src/client/widgets/index.js
+++ /dev/null
@@ -1,70 +0,0 @@
-module.exports.widgets = {
-
- // basics
- button: require('./basics/button'),
- switch: require('./basics/switch'),
- dropdown: require('./basics/dropdown'),
- menu: require('./basics/menu'),
- input: require('./basics/input'),
- file: require('./basics/file'),
-
- // containers
- panel: require('./containers/panel'),
- root: require('./containers/root'),
- tab: require('./containers/tab'),
- modal: require('./containers/modal'),
- clone: require('./containers/clone'),
- matrix: require('./containers/matrix'),
- keyboard: require('./containers/keyboard'),
- patchbay: require('./containers/patchbay').PatchBay,
- patchbaynode: require('./containers/patchbay').PatchBayNode,
-
- // frames
- image: require('./frames/image'),
- svg: require('./frames/svg'),
- html: require('./frames/html'),
- frame: require('./frames/frame'),
-
- // graphs
- plot: require('./graphs/plot'),
- eq: require('./graphs/eq'),
- visualizer: require('./graphs/visualizer'),
-
- // indicators
- led: require('./indicators/led'),
- text: require('./indicators/text'),
-
- // pads
- xy: require('./pads/xy'),
- rgb: require('./pads/rgb'),
- multixy: require('./pads/multixy'),
- // canvas: require('./pads/canvas'),
-
- // sliders
- fader: require('./sliders/fader'),
- knob: require('./sliders/knob'),
- encoder: require('./sliders/encoder'),
- range: require('./sliders/range'),
-
- // scripts
- script: require('./scripts/script'),
- variable: require('./scripts/variable'),
-
-}
-
-module.exports.categories = {
- 'Basics':['button', 'switch', 'dropdown', 'menu', 'input', 'file'],
- 'Containers':['panel', 'modal', 'clone', 'matrix', 'keyboard', 'patchbay'],
- 'Frames':['frame', 'svg', 'html', 'image'],
- 'Graphs':['plot','eq','visualizer'],
- 'Indicators':['led', 'text'],
- 'Pads':['xy','rgb','multixy'],
- 'Sliders':['fader','knob', 'encoder', 'range'],
- 'Scripts':['script', 'variable'],
-}
-
-var defaults = {}
-for (var k in module.exports.widgets) {
- defaults[k] = module.exports.widgets[k].defaults()
-}
-module.exports.defaults = defaults
diff --git a/src/client/widgets/index.mjs b/src/client/widgets/index.mjs
new file mode 100644
index 00000000..6ea652cf
--- /dev/null
+++ b/src/client/widgets/index.mjs
@@ -0,0 +1,128 @@
+// basics
+import button from './basics/button.mjs'
+import _switch from './basics/switch.mjs'
+import dropdown from './basics/dropdown.mjs'
+import menu from './basics/menu.mjs'
+import input from './basics/input.mjs'
+import textarea from './basics/textarea.mjs'
+import file from './basics/file.mjs'
+
+// containers
+import panel from './containers/panel.mjs'
+import folder from './containers/folder.mjs'
+import root from './containers/root.mjs'
+import tab from './containers/tab.mjs'
+import modal from './containers/modal.mjs'
+import clone from './containers/clone.mjs'
+import fragment from './containers/fragment.mjs'
+import matrix from './containers/matrix.mjs'
+import keyboard from './containers/keyboard.mjs'
+import {PatchBay as patchbay, PatchBayNode as patchbaynode} from './containers/patchbay.mjs'
+
+// frames
+import image from './frames/image.mjs'
+import svg from './frames/svg.mjs'
+import html from './frames/html.mjs'
+import frame from './frames/frame.mjs'
+
+// graphs
+import plot from './graphs/plot.mjs'
+import eq from './graphs/eq.mjs'
+import visualizer from './graphs/visualizer.mjs'
+
+// indicators
+import led from './indicators/led.mjs'
+import text from './indicators/text.mjs'
+
+// pads
+import xy from './pads/xy.mjs'
+import rgb from './pads/rgb.mjs'
+import multixy from './pads/multixy.mjs'
+import canvas from './pads/canvas.mjs'
+
+// sliders
+import fader from './sliders/fader.mjs'
+import knob from './sliders/knob.mjs'
+import encoder from './sliders/encoder.mjs'
+import range from './sliders/range.mjs'
+import scrollbar from './sliders/scrollbar.mjs'
+
+// scripts
+import script from './scripts/script-widget.mjs'
+import variable from './scripts/variable.mjs'
+
+export const widgets = {
+
+ // basics
+ button,
+ switch: _switch,
+ dropdown,
+ menu,
+ input,
+ textarea,
+ file,
+
+ // containers
+ panel,
+ folder,
+ root,
+ tab,
+ modal,
+ clone,
+ fragment,
+ matrix,
+ keyboard,
+ patchbay,
+ patchbaynode,
+
+ // frames
+ image,
+ svg,
+ html,
+ frame,
+
+ // graphs
+ plot,
+ eq,
+ visualizer,
+
+ // indicators
+ led,
+ text,
+
+ // pads
+ xy,
+ rgb,
+ multixy,
+ canvas,
+
+ // sliders
+ fader,
+ knob,
+ encoder,
+ range,
+ scrollbar,
+
+ // scripts
+ script,
+ variable,
+
+}
+
+export const categories = {
+ 'Basics':['button', 'switch', 'dropdown', 'menu', 'input', 'textarea', 'file'],
+ 'Containers':['panel', 'modal', 'clone', 'fragment', 'matrix', 'keyboard', 'patchbay', 'folder'],
+ 'Frames':['frame', 'svg', 'html', 'image'],
+ 'Graphs':['plot','eq','visualizer'],
+ 'Indicators':['led', 'text'],
+ 'Pads':['xy','rgb','multixy', 'canvas'],
+ 'Sliders':['fader','knob', 'encoder', 'range', 'scrollbar'],
+ 'Scripts':['script', 'variable'],
+}
+
+var defaults = {}
+for (var k in widgets) {
+ defaults[k] = widgets[k].defaults()
+ widgets[k]._defaults = defaults[k]._props()
+}
+export {defaults}
diff --git a/src/client/widgets/indicators/led.js b/src/client/widgets/indicators/led.mjs
similarity index 80%
rename from src/client/widgets/indicators/led.js
rename to src/client/widgets/indicators/led.mjs
index 4f8b43f7..b3b87498 100644
--- a/src/client/widgets/indicators/led.js
+++ b/src/client/widgets/indicators/led.mjs
@@ -1,9 +1,8 @@
-var {mapToScale} = require('../utils'),
- Widget = require('../common/widget'),
- html = require('nanohtml'),
- StaticProperties = require('../mixins/static_properties')
+import html from 'nanohtml'
+import {mapToScale} from '../utils.mjs'
+import Widget from '../common/widget.mjs'
-module.exports = class Led extends StaticProperties(Widget, {bypass: true, interaction: false}) {
+export default class Led extends Widget {
static description() {
@@ -15,11 +14,7 @@ module.exports = class Led extends StaticProperties(Widget, {bypass: true, inter
return super.defaults().extend({
widget: {
- interaction: null
- },
- style: {
- _separator_led_style: 'Led style',
- borderRadius: {type: 'string', value: '', help: 'Css border-radius property.'},
+ interaction: {value: false}
},
class_specific: {
mode: {type: 'string', value: 'intensity', choices: ['intensity', 'color'], help: 'Defines how value is interpreted (see `value`)'},
@@ -40,7 +35,6 @@ module.exports = class Led extends StaticProperties(Widget, {bypass: true, inter
osc: {
decimals: null,
typeTags: null,
- bypass: null,
ignoreDefaults: null
}
})
@@ -53,10 +47,6 @@ module.exports = class Led extends StaticProperties(Widget, {bypass: true, inter
this.setValueIntensity(this.getProp('mode') === 'intensity' ? this.getProp('range').min : this.getProp('range').max)
- var bR = this.getProp('borderRadius')
- if (parseInt(bR) == bR) bR += 'rem'
- this.container.style.setProperty('--border-radius', bR)
-
}
setValue(v, options={}) {
@@ -66,6 +56,7 @@ module.exports = class Led extends StaticProperties(Widget, {bypass: true, inter
if (options.sync && ret !== false) this.changed(options)
+ if (options.send) this.sendValue(null, {syncOnly: true})
}
diff --git a/src/client/widgets/indicators/text.js b/src/client/widgets/indicators/text.mjs
similarity index 58%
rename from src/client/widgets/indicators/text.js
rename to src/client/widgets/indicators/text.mjs
index fd88e513..79b154a8 100644
--- a/src/client/widgets/indicators/text.js
+++ b/src/client/widgets/indicators/text.mjs
@@ -1,9 +1,8 @@
-var {iconify} = require('../../ui/utils'),
- Widget = require('../common/widget'),
- html = require('nanohtml'),
- StaticProperties = require('../mixins/static_properties')
+import html from 'nanohtml'
+import {iconify} from '../../ui/utils.mjs'
+import Widget from '../common/widget.mjs'
-module.exports = class Text extends StaticProperties(Widget, {bypass: true, interaction: false}) {
+export default class Text extends Widget {
static description() {
@@ -15,20 +14,18 @@ module.exports = class Text extends StaticProperties(Widget, {bypass: true, inte
return super.defaults().extend({
widget: {
- interaction: null
+ interaction: {value: false}
},
style: {
_separator_text_style: 'Text style',
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.',
+ wrap: {type: 'boolean|string', value: false, choices: [false, true, 'soft'], help: [
+ 'Set to `true` to wrap long lines automatically. Set to `soft` to avoid breaking words.',
]},
- align: {type: 'string', value: 'center', choices: ['center', 'left', 'right'], help: 'Css text-align property.'},
+ align: {type: 'string', value: 'center', choices: ['center', 'left', 'right', 'top', 'bottom', 'left top', 'left bottom', 'right top', 'right bottom'], help: 'Text alignment.'},
},
osc: {
- decimals: null,
typeTags: null,
- bypass: null,
ignoreDefaults: null
}
})
@@ -42,10 +39,12 @@ module.exports = class Text extends StaticProperties(Widget, {bypass: true, inte
this.text = this.widget.appendChild(html``)
if (this.getProp('vertical')) this.text.classList.add('vertical')
- if (this.getProp('align') === 'left') this.text.classList.add('left')
- if (this.getProp('align') === 'right') this.text.classList.add('right')
+ if (this.getProp('align').includes('left')) this.text.classList.add('left')
+ if (this.getProp('align').includes('right')) this.text.classList.add('right')
+ if (this.getProp('align').includes('top')) this.text.classList.add('top')
+ if (this.getProp('align').includes('bottom')) this.text.classList.add('bottom')
if (this.getProp('wrap')) this.text.classList.add('wrap')
-
+ if (this.getProp('wrap') === 'soft') this.text.classList.add('wrap-soft')
this.setValue(this.getProp('default'))
@@ -56,7 +55,7 @@ module.exports = class Text extends StaticProperties(Widget, {bypass: true, inte
this.value = v === '' || v === null ? this.getProp('default') : v
- var s = String(this.value)
+ var s = String(this.getValue(true))
if (s.indexOf('^') > -1) {
this.text.innerHTML = iconify(s.replace(//g, '>').replace(/\n/g,'
'))
} else {
@@ -64,6 +63,7 @@ module.exports = class Text extends StaticProperties(Widget, {bypass: true, inte
}
if (options.sync) this.changed(options)
+ if (options.send) this.sendValue(null, {syncOnly: true})
}
diff --git a/src/client/widgets/mixins/double_tap.js b/src/client/widgets/mixins/double_tap.mjs
similarity index 71%
rename from src/client/widgets/mixins/double_tap.js
rename to src/client/widgets/mixins/double_tap.mjs
index ac4c2287..8564e9c5 100644
--- a/src/client/widgets/mixins/double_tap.js
+++ b/src/client/widgets/mixins/double_tap.mjs
@@ -1,10 +1,13 @@
-module.exports = (element, callback, options={})=>{
+import {normalizeDragEvent} from '../../events/utils.mjs'
+import {DOUBLE_TAP_TIME} from '../../globals.mjs'
+
+export default (self, callback, options={})=>{
var lastTapTime = 0,
lastTapX,
lastTapY
- element.addEventListener(options.click ? 'click' : 'fast-click', (event)=>{
+ self.on(options.click ? 'click' : 'fast-click', (event)=>{
if (event.capturedByEditor) return
@@ -22,8 +25,10 @@ module.exports = (element, callback, options={})=>{
) {
// execute callback at next cycle to ensure draginit events are resolved first
+ // normalize event now or offset gets lost
+ var e = normalizeDragEvent(event.detail)
setTimeout(()=>{
- callback(event.detail)
+ callback(e)
}, 0)
lastTapTime = 0
@@ -38,6 +43,6 @@ module.exports = (element, callback, options={})=>{
}
- })
+ }, {element: options.element})
}
diff --git a/src/client/widgets/mixins/static_properties.js b/src/client/widgets/mixins/static_properties.mjs
similarity index 87%
rename from src/client/widgets/mixins/static_properties.js
rename to src/client/widgets/mixins/static_properties.mjs
index fc415dde..041ffe40 100644
--- a/src/client/widgets/mixins/static_properties.js
+++ b/src/client/widgets/mixins/static_properties.mjs
@@ -13,4 +13,4 @@ let StaticProperties = (superclass, props) => class extends superclass {
}
-module.exports = StaticProperties
+export default StaticProperties
diff --git a/src/client/widgets/mixins/touch_state.js b/src/client/widgets/mixins/touch_state.mjs
similarity index 74%
rename from src/client/widgets/mixins/touch_state.js
rename to src/client/widgets/mixins/touch_state.mjs
index 7a9192b5..941cc18a 100644
--- a/src/client/widgets/mixins/touch_state.js
+++ b/src/client/widgets/mixins/touch_state.mjs
@@ -1,9 +1,17 @@
-module.exports = (self, options)=>{
+export default (self, options)=>{
+
+ if (self.parent.preventChildrenTouchState) return
self.touched = 0
self.setValueTouchedQueue = undefined
self.on('draginit',(e)=>{
+ self.setValueTouchedQueue = undefined
+
+ if (self.shouldDrag && !self.shouldDrag(e)) {
+ e.cancelDragEvent = true
+ return
+ }
self.touched += 1
if (self.touched == 1) {
self.trigger('touch', {stopPropagation: true, touch: 1})
@@ -28,6 +36,7 @@ module.exports = (self, options)=>{
self.onRemove = ()=>{
if (self.touched > 0) {
+ self.setValueTouchedQueue = undefined
self.trigger('touch', {stopPropagation: true, touch: 0})
}
self.__proto__.onRemove.call(self)
diff --git a/src/client/widgets/pads/canvas.js b/src/client/widgets/pads/canvas.js
deleted file mode 100644
index d88b09c9..00000000
--- a/src/client/widgets/pads/canvas.js
+++ /dev/null
@@ -1,100 +0,0 @@
-var Canvas = require('../common/canvas'),
- html = require('nanohtml')
-
-class CanvasWidget extends Canvas {
-
- static description() {
-
- return 'KANVA !'
-
- }
-
- static defaults() {
-
- return super.defaults().extend({
- class_specific: {
- onCreate: {type: 'string', value: '', help: ' '},
- onTouch: {type: 'string', value: '', help: ' '},
- }
- })
-
- }
-
- constructor(options) {
-
- super({...options, html: html`
-
-
-
- `})
-
-
- this.on('draginit',(e)=>{
-
-
- }, {element: this.widget, multitouch: true})
-
- this.on('drag',(e)=>{
-
-
- }, {element: this.widget, multitouch: true})
-
- this.on('dragend',(e)=>{
-
-
- }, {element: this.widget, multitouch: true})
-
-
- }
-
- setValue(v, options={}) {
-
- if (v === null || v === undefined || ((v.length || 1) !== this.getProp('valueLength'))) return
-
- this.value = v
-
- if (!options.dragged) {
- var coords = this.resolveProp('valueToCoords', undefined, false, false, false, {
- coords: this.touchCoords,
- value: this.value,
- width: this.width,
- height: this.height,
- local: this.localContext
- }) || this.touchCoords
-
- this.touchCoords = coords === undefined ? this.touchCoords : coords
- }
-
- this.batchDraw()
-
- if (options.send) this.sendValue()
- if (options.sync) this.changed(options)
-
- }
-
-
- draw() {
-
- if (this.getProp('autoClear')) this.clear()
-
- this.resolveProp('draw', undefined, false, false, false, {
- ctx: this.ctx,
- coords: this.touchCoords,
- value: this.value,
- colors: this.colors,
- width: this.width,
- height: this.height,
- })
-
-
- if (this.getProp('autoClear')) this.clearRect = [0, 0, this.width, this.height]
-
- }
-
-
-}
-
-CanvasWidget.dynamicProps = CanvasWidget.prototype.constructor.dynamicProps.concat([
-])
-
-module.exports = CanvasWidget
diff --git a/src/client/widgets/pads/canvas.mjs b/src/client/widgets/pads/canvas.mjs
new file mode 100644
index 00000000..8b0c62e1
--- /dev/null
+++ b/src/client/widgets/pads/canvas.mjs
@@ -0,0 +1,200 @@
+import html from 'nanohtml'
+import Canvas from '../common/canvas.mjs'
+import Script from '../scripts/script.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+
+class CanvasWidget extends Canvas {
+
+ static description() {
+
+ return 'Multitouch canvas widget with user-defined drawing functions and touch reactions.'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults().extend({
+ class_specific: {
+ contextType: {type: 'string', value: '2d', choices: ['2d', 'webgl2'], help: 'Context type for the canvas'},
+ valueLength: {type: 'number', value: 1, help:[
+ 'Defines the number of values accepted by the widget (minimum 1). Incoming messages that don\'t comply will be ignored',
+ 'When calling `set()` from a script, submitted value should be an array only if `valueLength` is greater than 1.'
+ ]},
+ autoClear: {type: 'boolean', value: true, help: [
+ 'If set to `false`, the canvas context won\'t be cleared automatically and `ctx.clearRect()` will need to be called in `onDraw`. Ignored if `contextType` is different from `2d`.'
+ ]},
+ continuous: {type: 'boolean|number', value: false, help: [
+ 'If set to `true`, `onDraw` will be called at each frame, otherwise it will be called only when the widget is touched and when it receives a value.',
+ 'Can be a number between 1 and 60 to specify the framerate (default: 30 fps).'
+ ]},
+ }
+ })
+ defaults.scripting = {
+ onCreate: {type: 'script', value: '', editor: 'javascript', help: ['Script executed when the widget is created. See documentation.']},
+ onValue: {type: 'script', value: '', editor: 'javascript', help: ['Script executed whenever the widget\'s value updates. See documentation.']},
+ onTouch: {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is touched and released, and when the pointer moves when the widget is touched. See documentation.',]},
+ onDraw: {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is redrawn. See documentation.']},
+ onResize: {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is resized. See documentation.']},
+ }
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: html`
+
+
+
+ `})
+
+ this.valueLength = Math.max(1, parseInt(this.getProp('valueLength')) || 1)
+ this.value = this.valueLength > 1 ? Array(this.valueLength).fill(0) : 0
+
+ if (this.getProp('onResize')) {
+ this.scripts.onResize = new Script({
+ widget: this,
+ property: 'onResize',
+ code: this.getProp('onResize'),
+ context: {
+ value: 0,
+ width: 100,
+ height: 100,
+ cssVars: {}
+ }
+ })
+ }
+
+ if (this.getProp('onDraw')) {
+ this.scripts.onDraw = new Script({
+ widget: this,
+ property: 'onDraw',
+ code: this.getProp('onDraw'),
+ context: {
+ value: 0,
+ width: 100,
+ height: 100,
+ ctx: {},
+ cssVars: {}
+ }
+ })
+ }
+
+ if (this.getProp('onTouch')) {
+
+ this.scripts.onTouch = new Script({
+ widget: this,
+ property: 'onTouch',
+ code: this.getProp('onTouch'),
+ context: {
+ value: 0,
+ width: 100,
+ height: 100,
+ event: {}
+ }
+ })
+
+ this.on('draginit',(e)=>this.onTouch(e, 'start'), {element: this.container, multitouch: true})
+ this.on('drag',(e)=>this.onTouch(e, 'move'), {element: this.container, multitouch: true})
+ this.on('dragend',(e)=>this.onTouch(e, 'stop'), {element: this.container, multitouch: true})
+
+ }
+
+ if (this.getProp('continuous')) {
+ var freq = parseInt(this.getProp('continuous')) || 30
+ freq = Math.max(Math.min(60, freq), 1)
+ this.drawInterval = setInterval(()=>{
+ this.batchDraw()
+ }, 1000/freq)
+ }
+
+ }
+
+ onTouch(e, name) {
+
+ var event = {...e}
+ delete event.firstTarget
+
+ event.targetName = event.target ? event.target.getAttribute('name') : ''
+ event.targetTagName = event.target ? event.target.tagName : ''
+
+ var w = widgetManager.getWidgetByElement(event.target)
+ if (w) event.target = w === this ? 'this' : w.getProp('id')
+ else event.target = null
+
+ event.type = name
+
+ this.scripts.onTouch.run({
+ value: this.value,
+ width: this.width,
+ height: this.height,
+ event: event,
+ }, {sync: true, send: true})
+
+ this.batchDraw()
+
+ }
+
+ setValue(v, options={}) {
+
+ if (Array.isArray(v)) {
+ if (v.length !== this.valueLength) return
+ } else if (this.valueLength > 1) return
+
+ this.value = v
+
+ this.batchDraw()
+
+ if (options.sync) this.changed(options)
+ if (options.send) this.sendValue()
+ if (options.defaultInit && this.script) this.script.setValue(this.value, {id: this.getProp('id')})
+
+ }
+
+
+ draw() {
+
+ if (!this.getProp('onDraw')) return
+
+ if (this.getProp('autoClear') && this.getProp('contextType') === '2d') {
+ this.clear()
+ this.ctx.beginPath()
+ }
+
+ this.scripts.onDraw.run({
+ value: this.value,
+ ctx: this.ctx,
+ width: this.width,
+ height: this.height,
+ cssVars: this.cssVars
+ }, {sync: false, send: false})
+
+ }
+
+ extraResizeHandle(event) {
+
+ if (!this.getProp('onResize')) return
+
+ this.scripts.onResize.run({
+ value: this.value,
+ width: this.width,
+ height: this.height,
+ cssVars: this.cssVars
+ }, {sync: true, send: true})
+
+ }
+
+ onRemove() {
+
+ clearInterval(this.drawInterval)
+
+ super.onRemove()
+
+ }
+
+}
+
+CanvasWidget.dynamicProps = CanvasWidget.prototype.constructor.dynamicProps.concat([
+])
+
+export default CanvasWidget
diff --git a/src/client/widgets/pads/multixy.js b/src/client/widgets/pads/multixy.js
deleted file mode 100644
index bf0bdb64..00000000
--- a/src/client/widgets/pads/multixy.js
+++ /dev/null
@@ -1,301 +0,0 @@
-var Pad = require('./pad'),
- Xy = require('./xy'),
- {clip} = require('../utils'),
- touchstate = require('../mixins/touch_state')
-
-
-var xyDefaults = Xy.defaults()._props()
-
-
-module.exports = class MultiXy extends Pad {
-
- static description() {
-
- return 'Multi-point XY pad.'
-
- }
-
- static defaults() {
-
-
- return super.defaults().extend({
- style: {
- _separator_xy_style: 'Xy style',
- pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
- ephemeral: {type: 'boolean', value: false, help: 'When set to `true`, the points will be drawn only chile touched.'},
- pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
- },
- class_specific: {
- 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\']`)'
- ]},
- 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'},
- rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
- rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
- logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
- logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
- sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
- }
- })
-
- }
-
- constructor(options) {
-
- super(options)
-
- this.npoints = typeof this.getProp('points') == 'object' ? this.getProp('points').length : this.getProp('points')
- this.labels = typeof this.getProp('points') == 'object'
- this.pointSize = parseInt(this.getProp('pointSize'))
-
- this.pads = []
-
- for (let i = 0; i < this.npoints; i++) {
- this.pads[i] = new Xy({props:{
- ...xyDefaults,
- snap:this.getProp('snap'),
- spring:this.getProp('spring'),
- ephemeral:this.getProp('ephemeral'),
- 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'),
- decimals:this.getProp('decimals'),
- logScaleX:this.getProp('logScaleX'),
- logScaleY:this.getProp('logScaleY'),
- pointSize: this.getProp('pointSize'),
- pips: this.getProp('pips') && i == this.npoints-1,
- sensitivity: this.getProp('sensitivity'),
- input:false
- }, parent: this})
- this.pads[i].canvas.classList.add('pad-' + i)
- this.widget.append(this.pads[i].canvas)
-
- }
-
- this.value = []
-
- this.padsCoords = []
- this.touchMap = {}
-
- touchstate(this, {element: this.widget, multitouch: true})
-
- this.on('draginit',(e)=>{
-
- var id
-
- if (!this.touchMap[e.pointerId]) {
-
- var ndiff, diff = -1
-
- for (var i in this.pads) {
-
- if (Object.values(this.touchMap).indexOf(i) != -1) continue
-
- ndiff = Math.abs(e.offsetX - this.padsCoords[i][0]) + Math.abs(e.offsetY - (this.padsCoords[i][1] + this.height))
-
- if (diff == -1 || ndiff < diff) {
- id = i
- diff = ndiff
- }
-
- }
-
- this.touchMap[e.pointerId] = id
-
-
- }
-
- if (!id) return
-
- e.stopPropagation = true
-
- this.trigger('touch', {stopPropagation: true, touch: [parseInt(id), 1]})
-
- this.pads[id].trigger('draginit', e)
-
- if (this.getProp('ephemeral')) this.batchDraw()
-
- }, {element: this.widget, multitouch: true})
-
- this.on('drag',(e)=>{
-
- var i = this.touchMap[e.pointerId]
-
- if (!i) return
-
- this.pads[i].trigger('drag', e)
-
- }, {element: this.widget, multitouch: true})
-
- this.on('dragend',(e)=>{
-
- var i = this.touchMap[e.pointerId]
-
- if (!i) return
-
- e.stopPropagation = true
-
- this.pads[i].trigger('dragend', e)
-
- this.trigger('touch', {stopPropagation: true, touch: [parseInt(this.touchMap[e.pointerId]), 0]})
-
- delete this.touchMap[e.pointerId]
-
- if (this.getProp('ephemeral')) this.batchDraw()
-
- }, {element: this.widget, multitouch: true})
-
- this.on('change',(e)=>{
- if (e.widget == this) return
- e.stopPropagation = true
- this.setValue(this.getValue(), e.options)
- })
-
- var v = []
- for (let i = 0; i < this.npoints * 2; i = i + 2) {
- [v[i],v[i+1]] = this.pads[i/2].getValue()
- }
-
- this.setValue(v)
-
- }
-
- resizeHandle(event){
-
- super.resizeHandle(event)
-
- for (var k in this.pads) {
- this.pads[k].width = this.width
- this.pads[k].height = this.height
- this.pads[k].padPadding = this.padPadding
- }
-
- this.updateHandlesPosition()
-
- }
-
- cacheCanvasStyle(style) {
-
- super.cacheCanvasStyle(style)
- for (var k in this.pads) {
- this.pads[k].cacheCanvasStyle()
- this.pads[k].batchDraw()
- }
-
- }
-
- setVisibility() {
-
- super.setVisibility()
- for (var k in this.pads) {
- this.pads[k].setVisibility()
- }
-
- }
-
- updateHandlesPosition() {
-
- for (var i=0;idocumentation.',]}
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.npoints = Array.isArray(this.getProp('points')) ? this.getProp('points').length : parseInt(this.getProp('points'))
+
+ if (isNaN(this.npoints) || this.npoints < 1) this.npoints = 1
+
+ this.preventChildrenTouchState = true
+ this.pads = []
+
+ for (let i = 0; i < this.npoints; i++) {
+ this.pads[i] = new Xy({props:{
+ ...xyDefaults,
+ snap:this.getProp('snap'),
+ spring:this.getProp('spring'),
+ ephemeral:this.getProp('ephemeral'),
+ default:this.getProp('default').length === this.npoints * 2 ? [this.getProp('default')[i*2], this.getProp('default')[i*2 + 1]] : '',
+ rangeX:this.getProp('rangeX'),
+ rangeY:this.getProp('rangeY'),
+ decimals:this.getProp('decimals'),
+ logScaleX:this.getProp('logScaleX'),
+ logScaleY:this.getProp('logScaleY'),
+ stepsX:this.getProp('stepsX'),
+ stepsY:this.getProp('stepsY'),
+ axisLock:this.getProp('axisLock'),
+ pointSize: 'auto',
+ pips: false,
+ sensitivity: this.getProp('sensitivity'),
+ input:false
+ }, parent: this})
+ this.pads[i].canvas.classList.add('pad-' + i)
+ this.widget.append(this.pads[i].canvas)
+
+ }
+
+ // tiny hack for pips until there's a proper range refactoring
+ this.faders = this.pads[0].faders
+
+ this.pointsAttr = []
+ this.updatePadsAttr()
+
+ this.padsCoords = []
+ this.touchMap = {}
+
+ this.on('dragend',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ this.pads[i].touched = 0
+ this.pads[i].trigger('dragend', e)
+
+ this.trigger('touch', {stopPropagation: true, touch: [parseInt(this.touchMap[e.pointerId]), 0]})
+
+ delete this.touchMap[e.pointerId]
+
+ }, {element: this.widget, multitouch: true})
+
+ touchstate(this, {element: this.widget, multitouch: true})
+
+ this.on('draginit',(e)=>{
+
+ var id
+
+ if (!this.touchMap[e.pointerId]) {
+
+ id = this.getPadIdFromCoords(e.offsetX, e.offsetY)
+
+ this.touchMap[e.pointerId] = id
+
+ }
+
+ if (!id) return
+
+ this.trigger('touch', {stopPropagation: true, touch: [parseInt(id), 1]})
+
+ this.pads[id].trigger('draginit', e)
+ this.pads[id].touched = 1
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('drag',(e)=>{
+
+ var i = this.touchMap[e.pointerId]
+
+ if (!i) return
+
+ e.fingers = 1 // cancel mutlifinger inertia
+
+ this.pads[i].trigger('drag', e)
+
+ }, {element: this.widget, multitouch: true})
+
+ this.on('value-changed',(e)=>{
+ if (e.widget == this) return
+ e.stopPropagation = true
+ if (e.options.spring) e.options.dragged = true
+ this.setValue(this.getValue(), e.options)
+ })
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubleTap(this, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ }, {element: this.widget})
+
+ } else {
+
+ doubleTap(this, (e) => {
+ var id, ndiff, diff = Infinity
+
+ for (var i in this.pads) {
+ ndiff = Math.abs(e.offsetX - this.padsCoords[i][0]) + Math.abs(e.offsetY - (this.padsCoords[i][1] + this.height))
+ if (ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+ }
+
+ var pad = this.pads[id]
+
+ if (this.getProp('doubleTap') == 'script') {
+ this.scripts.onTouch.run({
+ event: {type: 'doubleTap', handle: id},
+ value: this.value
+ }, {sync: true, send: true})
+ } else {
+ pad.setValue([pad.faders.x.getSpringValue(), pad.faders.y.getSpringValue()], { sync: true, send: true, spring: true, doubleTap: true })
+ }
+
+ }, { element: this.widget})
+
+ }
+
+ }
+
+ 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)
+
+ }
+
+ getPadIdFromCoords(x, y) {
+
+ var ndiff, diff = -1,
+ id
+
+ for (var i in this.pads) {
+
+ if (Object.values(this.touchMap).indexOf(i) != -1) continue
+ if (!this.pads[i].getProp('visible')) continue
+
+ ndiff = Math.abs(x - this.padsCoords[i][0]) + Math.abs(y - (this.padsCoords[i][1] + this.height))
+
+ if (diff == -1 || ndiff < diff) {
+ id = i
+ diff = ndiff
+ }
+
+ }
+
+ return id
+
+ }
+
+ extraResizeHandle(event){
+
+ super.extraResizeHandle(event)
+
+ for (var k in this.pads) {
+ this.pads[k].width = this.width
+ this.pads[k].height = this.height
+ this.pads[k].padPadding = this.padPadding
+ }
+
+ this.updateHandlesPosition()
+
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ super.cacheCanvasStyle(style)
+ for (var k in this.pads) {
+ this.pads[k].cacheCanvasStyle()
+ this.pads[k].batchDraw()
+ }
+ this.batchDraw()
+
+ }
+
+ setVisibility() {
+
+ super.setVisibility()
+ for (var k in this.pads) {
+ this.pads[k].setVisibility()
+ }
+ this.batchDraw()
+
+ }
+
+ updateHandlesPosition() {
+
+ for (var i=0;ix.js==n)
+ if (cssVar) {
+ this.pads[i].canvas.style.setProperty(cssVar.css, this.pointsAttr[i][n] == 'auto' ? '' : this.pointsAttr[i][n])
+ }
+
+ if (n == 'visible') {
+ this.pads[i].canvas.style.setProperty('opacity', this.pointsAttr[i][n] ? 1 : 0)
+ }
+
+ }
+ }
+ }
+
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'padding':
+ for (let w of this.pads) {
+ w.onPropChanged(propName)
+ }
+ return
+
+ case 'colorText':
+ case 'colorWidget':
+ case 'colorFill':
+ case 'colorStroke':
+ case 'alphaStroke':
+ case 'alphaFillOff':
+ case 'alphaFillOn':
+ case 'pointsAttr':
+ case 'spring':
+ case 'pointSize':
+ case 'axisLock':
+ this.updatePadsAttr(options)
+ return
+ }
+
+ }
+
+ onRemove() {
+ for (var i in this.pads) {
+ this.pads[i].onRemove()
+ }
+ super.onRemove()
+ }
+
+}
+
+
+MultiXy.dynamicProps = MultiXy.prototype.constructor.dynamicProps.filter(n => n !== 'decimals').concat([
+ 'pointsAttr',
+])
+
+export default MultiXy
diff --git a/src/client/widgets/pads/pad.js b/src/client/widgets/pads/pad.js
deleted file mode 100644
index bf0acd80..00000000
--- a/src/client/widgets/pads/pad.js
+++ /dev/null
@@ -1,33 +0,0 @@
-var Canvas = require('../common/canvas'),
- html = require('nanohtml')
-
-class Pad extends Canvas {
-
- constructor(options) {
-
- super({...options, html: html`
-
-
-
- `})
-
- this.canvas.style.setProperty('--pointSize', parseInt(this.getProp('pointSize')) + 'rem')
-
- }
-
- cacheCanvasStyle(style) {
-
- style = style || window.getComputedStyle(this.canvas)
-
- super.cacheCanvasStyle(style)
-
- this.pointSize = parseFloat(style.getPropertyValue('--pointSize')) * PXSCALE
- this.padPadding = (this.cssVars.padding + this.cssVars.lineWidth) + 2 * PXSCALE
-
- }
-
-}
-
-Pad.dynamicProps = Pad.prototype.constructor.dynamicProps.filter(n => n !== 'decimals')
-
-module.exports = Pad
diff --git a/src/client/widgets/pads/pad.mjs b/src/client/widgets/pads/pad.mjs
new file mode 100644
index 00000000..68660e64
--- /dev/null
+++ b/src/client/widgets/pads/pad.mjs
@@ -0,0 +1,113 @@
+import html from 'nanohtml'
+import Canvas from '../common/canvas.mjs'
+import {PXSCALE} from '../../globals.mjs'
+
+class Pad extends Canvas {
+
+ constructor(options) {
+
+ super({...options, value: [], html: html`
+
+
+
+ `})
+
+ }
+
+ cacheCanvasStyle(style) {
+
+ style = style || window.getComputedStyle(this.canvas)
+
+ super.cacheCanvasStyle(style)
+
+ this.padPadding = (this.cssVars.padding + this.cssVars.lineWidth) + 2 * PXSCALE
+ this.pointSize = parseFloat(this.cssVars.pointSize) * (this.cssVars.pointSize.indexOf('%') > -1 ? this.width / 100 : PXSCALE)
+
+ }
+
+ drawPips() {
+
+ var margin = this.padPadding,
+ pipTexts = margin >= this.fontSize * 1.5
+
+ this.ctx.lineWidth = PXSCALE
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.cssVars.alphaPips
+ this.ctx.beginPath()
+
+ for (let i in this.faders.x.rangeKeys) {
+
+ let pip = this.faders.x.rangeKeys[i],
+ px = Math.round(0.5 * this.faders.x.percentToCoord(pip)) * 2
+
+ if (parseInt(px) === px) px -= 0.5
+
+ if (pipTexts) {
+ this.ctx.textAlign = 'center'
+ let label = this.faders.x.rangeLabels[i]
+ this.ctx.fillText(label, px, this.height - margin / 2)
+ }
+
+ if (pip == 0 || pip == 100) continue
+ this.ctx.moveTo(px, margin - PXSCALE)
+ this.ctx.lineTo(px, this.height - margin + PXSCALE)
+
+
+ }
+ for (let i in this.faders.y.rangeKeys) {
+
+ let pip = this.faders.y.rangeKeys[i],
+ py = Math.round(0.5 * this.faders.y.percentToCoord(pip)) * 2
+
+ if (parseInt(py) === py) py -= 0.5
+
+ if (pipTexts) {
+ this.ctx.textAlign = 'right'
+ let label = this.faders.y.rangeLabels[i]
+ this.ctx.fillText(label, margin / 2 + this.fontSize / 2, py)
+ }
+
+ if (pip == 0 || pip == 100) continue
+ this.ctx.moveTo(margin - PXSCALE, py)
+ this.ctx.lineTo(this.width - margin + PXSCALE, py)
+
+
+ }
+
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.stroke()
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ var ret = super.onPropChanged(...arguments)
+
+ switch (propName) {
+ case 'pointSize':
+ this.setCssVariables()
+ return
+ }
+
+ return ret
+
+
+ }
+
+}
+
+Pad.cssVariables = Pad.prototype.constructor.cssVariables.concat(
+ {js: 'pointSize', css: '--point-size'},
+)
+
+Pad.dynamicProps = Pad.prototype.constructor.dynamicProps.filter(n => n !== 'decimals').concat([
+ 'spring',
+ 'axisLock',
+ 'pointSize',
+ 'label',
+ 'clipX',
+ 'clipY'
+])
+
+export default Pad
diff --git a/src/client/widgets/pads/rgb.js b/src/client/widgets/pads/rgb.mjs
similarity index 85%
rename from src/client/widgets/pads/rgb.js
rename to src/client/widgets/pads/rgb.mjs
index 4ec06440..4db285b4 100644
--- a/src/client/widgets/pads/rgb.js
+++ b/src/client/widgets/pads/rgb.mjs
@@ -1,14 +1,16 @@
-var Widget = require('../common/widget'),
- Xy = require('./xy'),
- Fader = require('../sliders/fader'),
- {clip, mapToScale, hsbToRgb, rgbToHsb} = require('../utils'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import Widget from '../common/widget.mjs'
+import Xy from './xy.mjs'
+import Fader from '../sliders/fader.mjs'
+import {clip, mapToScale, hsbToRgb, rgbToHsb} from '../utils.mjs'
+import touchstate from '../mixins/touch_state.mjs'
+import {PXSCALE} from '../../globals.mjs'
var faderDefaults = Fader.defaults()._props(),
xyDefaults = Xy.defaults()._props()
-module.exports = class Rgb extends Widget {
+export default class Rgb extends Widget {
static description() {
@@ -18,7 +20,7 @@ module.exports = class Rgb extends Widget {
static defaults() {
- return super.defaults().extend({
+ var defaults = super.defaults().extend({
class_specific: {
snap: {type: 'boolean', value: false, help: [
'By default, the points are dragged from their initial position.',
@@ -31,14 +33,20 @@ module.exports = class Rgb extends Widget {
}
})
+ defaults.scripting.onTouch = {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is touched and released. See documentation.',]}
+
+ return defaults
+
}
constructor(options) {
- super({...options, html: html` `})
+ super({...options, value: [], html: html` `})
this.container.classList.toggle('contains-alpha', this.getProp('alpha'))
+ this.preventChildrenTouchState = true
+
this.pad = new Xy({props:{
...xyDefaults,
type: 'xy',
@@ -49,11 +57,11 @@ module.exports = class Rgb extends Widget {
decimals:2,
pointSize: 10,
pips: false,
- }, parent: this})
+ }, parent: this, meta: {not_editable: true}})
this.pad.sendValue = ()=>{}
- this.pad.container.classList.add('not-editable', 'pad')
+ this.pad.container.classList.add('pad')
this.widget.appendChild(this.pad.container)
- this.pad.on('change',(e)=>{
+ this.pad.on('value-changed',(e)=>{
e.stopPropagation = true
this.dragHandle()
})
@@ -68,10 +76,10 @@ module.exports = class Rgb extends Widget {
snap:this.getProp('snap'),
range:{min:0,max:360},
decimals:2
- }, parent: this})
- this.hue.container.classList.add('not-editable', 'hue')
+ }, parent: this, meta: {not_editable: true}})
+ this.hue.container.classList.add('hue')
this.widget.appendChild(this.hue.container)
- this.hue.on('change',(e)=>{
+ this.hue.on('value-changed',(e)=>{
e.stopPropagation = true
this.dragHandle(true)
})
@@ -89,10 +97,10 @@ module.exports = class Rgb extends Widget {
default: 255,
input:false,
decimals:2
- }, parent: this})
- this.alpha.container.classList.add('not-editable', 'alpha')
+ }, parent: this, meta: {not_editable: true}})
+ this.alpha.container.classList.add('alpha')
this.widget.appendChild(this.alpha.container)
- this.alpha.on('change',(e)=>{
+ this.alpha.on('value-changed',(e)=>{
e.stopPropagation = true
this.dragAlphaHandle()
})
@@ -114,8 +122,7 @@ module.exports = class Rgb extends Widget {
}
-
- this.value = []
+ touchstate(this, {element: this.widget, multitouch: true, ignoreCustomBindings: false})
this.hsb = {h:0,s:0,b:0}
@@ -210,7 +217,7 @@ module.exports = class Rgb extends Widget {
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.pad.container.setAttribute('style',`background-color:${hueStr}`)
+ this.pad.container.style.setProperty('background-color', hueStr)
this.hue.setValue(this.hsb.h, {sync: false, send:false, dragged:false})
}
diff --git a/src/client/widgets/pads/xy.js b/src/client/widgets/pads/xy.js
deleted file mode 100644
index 5f6328c1..00000000
--- a/src/client/widgets/pads/xy.js
+++ /dev/null
@@ -1,290 +0,0 @@
-var Pad = require('./pad'),
- Fader = require('../sliders/fader'),
- doubletab = require('../mixins/double_tap'),
- touchstate = require('../mixins/touch_state')
-
-var faderDefaults = Fader.defaults()._props()
-
-module.exports = class Xy extends Pad {
-
- static description() {
-
- return 'Two-dimensional slider.'
-
- }
-
- static defaults() {
-
- return super.defaults().extend({
- style: {
- _separator_xy_style: 'Xy style',
- pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size'},
- ephemeral: {type: 'boolean', value: false, help: 'When set to `true`, the point will be drawn only while touched.'},
- pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
- },
- class_specific: {
- 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'},
- rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis'},
- rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis'},
- logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
- logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
- 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: `/ `'
- ]},
- sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
- }
- })
-
- }
-
- constructor(options) {
-
- super(options)
-
- this.faders = {
- x: new Fader({props:{
- ...faderDefaults,
- id:0,
- visible:false,
- horizontal:true,
- default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
- snap:this.getProp('snap'),
- range:this.getProp('rangeX'),
- decimals:this.getProp('decimals'),
- logScale:this.getProp('logScaleX'),
- sensitivity: this.getProp('sensitivity'),
- }, parent: this}),
- y: new Fader({props:{
- ...faderDefaults,
- id:1,
- visible:false,
- horizontal:false,
- default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
- snap:this.getProp('snap'),
- range:this.getProp('rangeY'),
- decimals:this.getProp('decimals'),
- logScale:this.getProp('logScaleY'),
- sensitivity: this.getProp('sensitivity'),
- }, parent: this}),
- }
-
- this.on('change',(e)=>{
- if (e.widget == this) return
- e.stopPropagation = true
- })
-
- this.value = []
-
- touchstate(this, {element: this.canvas})
-
- this.active = false
-
- this.on('draginit',(e)=>{
- this.active = true
- this.faders.x.trigger('draginit', {...e, stopPropagation: true})
- this.faders.y.trigger('draginit', {...e, stopPropagation: true})
- this.dragHandle()
- }, {element: this.canvas})
-
- this.on('drag',(e)=>{
- this.faders.x.trigger('drag', e)
- this.faders.y.trigger('drag', e)
- this.dragHandle()
- }, {element: this.canvas})
-
- this.on('dragend', (e)=>{
- this.active = false
- this.faders.x.trigger('dragend', {...e, stopPropagation: true})
- this.faders.y.trigger('dragend', {...e, stopPropagation: true})
- if (this.getProp('spring')) {
- this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true,send:true})
- } else {
- this.batchDraw()
- }
- }, {element: this.canvas})
-
- if (this.getProp('doubleTap')) {
-
- if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
-
- doubletab(this.widget, ()=>{
- this.sendValue({v:null, address: this.getProp('doubleTap')})
- })
-
- } else {
-
- doubletab(this.widget, ()=>{
- this.faders.x.setValue(this.faders.x.getSpringValue(), {sync: false, send:false, dragged:true})
- this.faders.y.setValue(this.faders.y.getSpringValue(), {sync: false, send:false, dragged:true})
- this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true, send:true})
- })
-
- }
-
- }
-
- this.setValue([0,0])
-
- }
-
- dragHandle(){
-
- var x = this.faders.x.value,
- y = this.faders.y.value
-
-
- if (x != this.value[0] || y != this.value[1]) {
- this.setValue([x, y],{send:true,sync:true,dragged:true})
- } else {
- this.batchDraw()
- }
-
- }
-
- resizeHandle(event){
-
- super.resizeHandle(event)
-
- for (var k in this.faders) {
- this.faders[k].width = this.width
- this.faders[k].height = this.height
- this.faders[k].gaugePadding = this.padPadding
-
- }
-
- }
-
-
- setValue(v, options={}) {
-
- if (!v || !v.length || v.length!=2) return
- if (this.touched && !options.dragged) return this.setValueTouchedQueue = [v, options]
-
- if (!options.dragged) {
- this.faders.x.setValue(v[0], {sync: false, send:false, dragged:false})
- this.faders.y.setValue(v[1], {sync: false, send:false, dragged:false})
- }
-
- this.value = [
- this.faders.x.value,
- this.faders.y.value
- ]
-
- if (options.send) this.sendValue()
- if (options.sync) this.changed(options)
-
- this.batchDraw()
-
- }
-
- draw() {
-
- var pointSize = this.pointSize,
- margin = this.padPadding,
- x = this.faders.x.percentToCoord(this.faders.x.percent),
- y = this.faders.y.percentToCoord(this.faders.y.percent),
- ephemeral = this.getProp('ephemeral')
-
- this.clear()
-
-
- if (!ephemeral || this.active) {
- this.ctx.fillStyle = this.cssVars.colorFill
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.beginPath()
- this.ctx.arc(x, y, pointSize - 3 * PXSCALE, Math.PI * 2, false)
- this.ctx.fill()
- }
-
-
-
-
- var pipsDrawn = false
- if (this.getProp('pips')) {
-
- var pipTexts = margin >= this.fontSize * 1.5
-
- this.ctx.lineWidth = PXSCALE
- this.ctx.fillStyle = this.cssVars.colorText
- this.ctx.strokeStyle = this.cssVars.colorStroke
- this.ctx.globalAlpha = this.cssVars.alphaPips
- this.ctx.beginPath()
-
- for (let i in this.faders.x.rangeKeys) {
-
- let pip = this.faders.x.rangeKeys[i],
- px = Math.round(0.5 * this.faders.x.percentToCoord(pip)) * 2
-
- if (parseInt(px) === px) px -= 0.5
-
- if (pipTexts) {
- this.ctx.textAlign = 'center'
- let label = this.faders.x.rangeLabels[i]
- this.ctx.fillText(label, px, this.height - margin / 2)
- pipsDrawn = true
- }
-
- if (pip == 0 || pip == 100) continue
- this.ctx.moveTo(px, margin - PXSCALE)
- this.ctx.lineTo(px, this.height - margin + PXSCALE)
- pipsDrawn = true
-
-
- }
- for (let i in this.faders.y.rangeKeys) {
-
- let pip = this.faders.y.rangeKeys[i],
- py = Math.round(0.5 * this.faders.y.percentToCoord(pip)) * 2
-
- if (parseInt(py) === py) py -= 0.5
-
- if (pipTexts) {
- this.ctx.textAlign = 'right'
- let label = this.faders.y.rangeLabels[i]
- this.ctx.fillText(label, margin / 2 + this.fontSize / 2, py)
- pipsDrawn = true
- }
-
- if (pip == 0 || pip == 100) continue
- this.ctx.moveTo(margin - PXSCALE, py)
- this.ctx.lineTo(this.width - margin + PXSCALE, py)
- pipsDrawn = true
-
-
- }
-
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.stroke()
-
- }
-
- if (!pipsDrawn) this.clearRect = [x - this.pointSize - 2 * PXSCALE, y - this.pointSize - 2 * PXSCALE, (this.pointSize + PXSCALE) * 4, (this.pointSize + PXSCALE) * 4]
-
-
- if (!ephemeral || this.active) {
- this.ctx.strokeStyle = this.cssVars.colorStroke
- this.ctx.globalAlpha = this.active ? 1 : 0.75
- this.ctx.lineWidth = 1.5 * PXSCALE
- this.ctx.beginPath()
- this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
- this.ctx.stroke()
- }
-
-
-
- }
-
- onRemove() {
-
- this.faders.x.onRemove()
- this.faders.y.onRemove()
- super.onRemove()
-
- }
-
-}
diff --git a/src/client/widgets/pads/xy.mjs b/src/client/widgets/pads/xy.mjs
new file mode 100644
index 00000000..fdde2ccc
--- /dev/null
+++ b/src/client/widgets/pads/xy.mjs
@@ -0,0 +1,329 @@
+import Pad from './pad.mjs'
+import Fader from '../sliders/fader.mjs'
+import doubleTap from '../mixins/double_tap.mjs'
+import touchstate from '../mixins/touch_state.mjs'
+import {PXSCALE} from '../../globals.mjs'
+
+var faderDefaults = Fader.defaults()._props()
+
+export default class Xy extends Pad {
+
+ static description() {
+
+ return 'Two-dimensional slider.'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults().extend({
+ style: {
+ _separator_xy_style: 'Xy style',
+ pointSize: {type: 'integer', value: 20, help: 'Defines the points\' size (may be in %)'},
+ ephemeral: {type: 'boolean', value: false, help: 'When set to `true`, the point will be drawn only while touched.'},
+ pips: {type: 'boolean', value: true, help: 'Set to `false` to hide the scale'},
+ label: {type: 'string', value: '', help: 'Text displayed in the handle'}
+ },
+ class_specific: {
+ 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'},
+ rangeX: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the x axis (see fader)'},
+ rangeY: {type: 'object', value: {min:0,max:1}, help: 'Defines the min and max values for the y axis (see fader)'},
+ logScaleX: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the x axis. Set to `-1` for exponential scale.'},
+ logScaleY: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale for the y axis. Set to `-1` for exponential scale.'},
+ stepsX: {type: 'number|array|string', value: false, help: 'Defines `steps` for the x axis (see fader)'},
+ stepsY: {type: 'number|array|string', value: false, help: 'Defines `steps` for the x axis (see fader)'},
+ clipX: {type: 'object', value: '', help: 'Min and max boundaries for the x axis'},
+ clipY: {type: 'object', value: '', help: 'Min and max boundaries for the y axis'},
+ axisLock: {type: 'string', value: '', choices: ['', 'x', 'y', 'auto'], help: [
+ 'Restrict movements to one of the axes only unless `Shift` is held.',
+ 'When left empty, holding `Shift` while dragging will lock the pad according the first movement. `auto` will do the opposite.'
+ ]},
+ doubleTap: {type: 'boolean|string', value: false, choices: [false, true, 'script'], help: [
+ 'Set to `true` to make the knob reset to its `default` value when receiving a double tap.',
+ 'Can be an osc address, in which case the widget will just send an osc message with no value (but `preArgs` included).',
+ 'If set to "script", `onTouch` will be called with `event.type` set to `doubleTap`. '
+ ]},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the pad\'s sensitivity when `snap` is `false` '},
+ }
+ })
+
+ defaults.scripting.onTouch = {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is touched and released. See documentation.',]}
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.preventChildrenTouchState = true
+
+ this.faders = {
+ x: new Fader({props:{
+ ...faderDefaults,
+ id:0,
+ visible:false,
+ horizontal:true,
+ default:this.getProp('default').length === 2 ? this.getProp('default')[0] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeX'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScaleX'),
+ sensitivity: this.getProp('sensitivity'),
+ steps: this.getProp('stepsX'),
+ }, parent: this}),
+ y: new Fader({props:{
+ ...faderDefaults,
+ id:1,
+ visible:false,
+ horizontal:false,
+ default:this.getProp('default').length === 2 ? this.getProp('default')[1] : '',
+ snap:this.getProp('snap'),
+ range:this.getProp('rangeY'),
+ decimals:this.getProp('decimals'),
+ logScale:this.getProp('logScaleY'),
+ sensitivity: this.getProp('sensitivity'),
+ steps: this.getProp('stepsY'),
+ }, parent: this}),
+ }
+
+ this.on('value-changed',(e)=>{
+ if (e.widget == this) return
+ e.stopPropagation = true
+ })
+
+ touchstate(this, {element: this.canvas})
+
+ this.active = false
+
+ this.autoAxisLock = ''
+
+ this.on('draginit',(e)=>{
+ this.active = true
+ this.autoAxisLock = ''
+ var axis = this.getProp('axisLock')
+ if (axis !== '' && e.shiftKey) axis = ''
+ if (axis !== 'y') this.faders.x.trigger('draginit', {...e, stopPropagation: true})
+ if (axis !== 'x') this.faders.y.trigger('draginit', {...e, stopPropagation: true})
+ this.dragHandle()
+ }, {element: this.canvas})
+
+ this.on('drag',(e)=>{
+ var axis = this.getProp('axisLock')
+ if (axis !== '' && e.shiftKey) axis = ''
+ else if (e.shiftKey && axis === '' || !e.shiftKey && axis === 'auto') {
+ if (this.autoAxisLock === '') {
+ if (Math.abs(e.movementX) > Math.abs(e.movementY)) {
+ this.autoAxisLock = 'x'
+ } else if (Math.abs(e.movementY) > Math.abs(e.movementX)) {
+ this.autoAxisLock = 'y'
+ }
+ }
+ axis = this.autoAxisLock
+ }
+ if (axis !== 'y') this.faders.x.trigger('drag', e)
+ if (axis !== 'x') this.faders.y.trigger('drag', e)
+ this.dragHandle()
+ }, {element: this.canvas})
+
+ this.on('dragend', (e)=>{
+ this.active = false
+ var axis = this.getProp('axisLock')
+ if (axis !== '' && e.shiftKey) axis = ''
+ if (axis !== 'y') this.faders.x.trigger('dragend', {...e, stopPropagation: true})
+ if (axis !== 'x') this.faders.y.trigger('dragend', {...e, stopPropagation: true})
+ if (this.getProp('spring')) {
+ this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true, send:true, spring:true})
+ } else {
+ if (this.getProp('clipX')) this.faders.x.setValue(this.value[0])
+ if (this.getProp('clipY')) this.faders.y.setValue(this.value[1])
+ this.batchDraw()
+ }
+ }, {element: this.canvas})
+
+ if (this.getProp('doubleTap')) {
+
+ if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
+
+ doubleTap(this, ()=>{
+ this.sendValue({v:null, address: this.getProp('doubleTap')})
+ }, {element: this.widget})
+
+ } else if (this.getProp('doubleTap') == 'script') {
+
+ doubleTap(this, ()=>{
+ this.scripts.onTouch.run({
+ event: {type: 'doubleTap'},
+ value: this.value
+ }, {sync: true, send: true})
+ }, {element: this.widget})
+
+
+ } else {
+
+ doubleTap(this, ()=>{
+ this.setValue([this.faders.x.getSpringValue(),this.faders.y.getSpringValue()],{sync:true, send:true, spring:true, doubleTap:true})
+ }, {element: this.widget})
+
+ }
+
+ }
+
+ this.setValue([0,0])
+
+ }
+
+ dragHandle(){
+
+ var x = this.faders.x.value,
+ y = this.faders.y.value
+
+
+ if (x != this.value[0] || y != this.value[1]) {
+ this.setValue([x, y],{send:true,sync:true,dragged:true})
+ } else {
+ this.batchDraw()
+ }
+
+ }
+
+ extraResizeHandle(event){
+
+ super.extraResizeHandle(event)
+
+ for (var k in this.faders) {
+ this.faders[k].width = this.width
+ this.faders[k].height = this.height
+ this.faders[k].gaugePadding = this.padPadding
+ }
+
+ }
+
+
+ setValue(v, options={}) {
+
+ if (!v || !v.length || v.length!=2) return
+ if (this.touched && !options.dragged && !options.doubleTap) return this.setValueTouchedQueue = [v, options]
+
+ if (!options.dragged) {
+ this.clipValue(v)
+ this.faders.x.setValue(v[0], {sync: false, send:false, dragged:false, doubleTap: options.doubleTap})
+ this.faders.y.setValue(v[1], {sync: false, send:false, dragged:false, doubleTap: options.doubleTap})
+ }
+
+ this.value = [
+ this.faders.x.value,
+ this.faders.y.value
+ ]
+
+ this.clipValue(this.value)
+
+ if (options.send) this.sendValue()
+ if (options.sync) this.changed(options)
+
+ this.batchDraw()
+
+ }
+
+ clipValue(v) {
+
+ if (this.getProp('clipX')) {
+ if (this.getProp('clipX').min !== undefined) v[0] = Math.max(this.getProp('clipX').min, v[0])
+ if (this.getProp('clipX').max !== undefined) v[0] = Math.min(this.getProp('clipX').max, v[0])
+ }
+ if (this.getProp('clipY')) {
+ if (this.getProp('clipY').min !== undefined) v[1] = Math.max(this.getProp('clipY').min, v[1])
+ if (this.getProp('clipY').max !== undefined) v[1] = Math.min(this.getProp('clipY').max, v[1])
+ }
+
+ }
+
+ draw() {
+
+ if (!this.visible) return
+
+ var pointSize = this.pointSize,
+ x = this.faders.x.percentToCoord(this.faders.x.valueToPercent(this.value[0])),
+ y = this.faders.y.percentToCoord(this.faders.y.valueToPercent(this.value[1])),
+ ephemeral = this.getProp('ephemeral')
+
+ this.clear()
+
+ if (!ephemeral || this.active) {
+ this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize - 3 * PXSCALE, Math.PI * 2, false)
+ this.ctx.fill()
+ }
+
+
+
+ if (this.getProp('pips')) this.drawPips()
+ else {
+ this.clearRect = [[x - pointSize - 2 * PXSCALE, y - pointSize - 2 * PXSCALE, (pointSize + 2 * PXSCALE) * 2, (pointSize + 2 * PXSCALE) * 2]]
+ }
+
+ if (!ephemeral || this.active) {
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.active ? 1 : 0.75
+ this.ctx.lineWidth = 1.5 * PXSCALE
+ this.ctx.beginPath()
+ this.ctx.arc(x, y, pointSize, Math.PI * 2, false)
+ this.ctx.stroke()
+
+ var t = this.getProp('label')
+ if (t) {
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.globalAlpha = 1
+ this.ctx.textAlign = 'center'
+ this.ctx.fillText(t, x + 0.5 * PXSCALE, y + PXSCALE)
+
+ if (!this.getProp('pips')) {
+ var length = this.fontSize * t.length
+ this.clearRect.push([x - length / 2, y - this.fontSize / 2, length, this.fontSize + 2 * PXSCALE])
+ }
+
+ }
+ }
+
+
+
+ }
+
+ onPropChanged(propName, options, oldPropValue) {
+
+ if (super.onPropChanged(...arguments)) return true
+
+ switch (propName) {
+
+ case 'label':
+ this.batchDraw()
+ return
+ case 'spring':
+ if (this.getProp('spring') && !this.touched) {
+ var x = this.faders.x.getSpringValue(),
+ y = this.faders.y.getSpringValue()
+ if (x !== this.value[0] || y !== this.value[1]) this.setValue([x, y], {...options})
+ }
+ return
+
+ }
+
+ }
+
+
+ onRemove() {
+
+ this.faders.x.onRemove()
+ this.faders.y.onRemove()
+ super.onRemove()
+
+ }
+
+}
diff --git a/src/client/widgets/scripts/gyro-archive.js b/src/client/widgets/scripts/gyro-archive.js
deleted file mode 100644
index b3baa851..00000000
--- a/src/client/widgets/scripts/gyro-archive.js
+++ /dev/null
@@ -1,125 +0,0 @@
-var Widget = require('../common/widget'),
- GyroNorm = require('gyronorm/dist/gyronorm.complete.min.js'),
- {icon} = require('../../ui/utils'),
- {clip} = require('../utils'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw')
-
-
-class Gyroscope extends Widget {
-
- static description() {
-
- return 'Device motion/orientation sensor.'
-
- }
-
- static defaults() {
-
- return super.defaults({
-
- _class_specific: 'gyroscope',
-
- frequency: {type: 'number', value: 30, help: 'Value update frequency (updates per seconds)'},
- normalize: {type: 'boolean', value: true, help: 'Normalize gravity related values'},
- compass: {type: 'boolean', value: false, help: 'Set to `true` to return the orientation values with respect to the actual north direction of the world instead of the head direction of the device'},
- screenAdjusted: {type: 'boolean', value: false, help: 'Set to `true` to return screen adjusted values'}
-
- }, [], {
-
- value: {type: 'object', value: '', help: [
- 'The gyroscope\'s value is an object containing multiple values, which can be used by other widgets via the property maths syntax',
- '- `value.do.alpha`: deviceorientation event alpha',
- '- `value.do.beta`: deviceorientation event beta',
- '- `value.do.gamma`: deviceorientation event gamma',
- '- `value.do.absolute`: deviceorientation event absolute',
- '- `value.dm.x`: devicemotion event acceleration x',
- '- `value.dm.y`: devicemotion event acceleration y',
- '- `value.dm.z`: devicemotion event acceleration z',
- '- `value.dm.gx`: devicemotion event accelerationIncludingGravity x',
- '- `value.dm.gy`: devicemotion event accelerationIncludingGravity y',
- '- `value.dm.gz`: devicemotion event accelerationIncludingGravity z',
- '- `value.dm.alpha`: devicemotion event rotationRate alpha',
- '- `value.dm.beta`: devicemotion event rotationRate beta',
- '- `value.dm.gamma`: devicemotion event rotationRate gamma'
- ]},
-
- })
-
- }
-
- constructor(options) {
-
- super({...options, html: html`
-
- ${raw(icon('compass'))}
-
- `})
-
- this.sensor = new GyroNorm()
- this.sensor.init({
-
- frequency: 1000 / clip(this.getProp('frequency'), [0.01, 60]),
- gravityNormalized: this.getProp('normalize'),
- orientationBase: this.getProp('compass') ? GyroNorm.WORLD : GyroNorm.GAME,
- decimalCount: this.getProp('decimals'),
- screenAdjusted: this.getProp('screenAdjusted'),
- logger: null
-
- }).then(()=>{
-
- this.sensor.start((data)=>{
-
- this.setValue(data, {sync: true, send: true})
-
- // data.do.alpha ( deviceorientation event alpha value )
- // data.do.beta ( deviceorientation event beta value )
- // data.do.gamma ( deviceorientation event gamma value )
- // data.do.absolute ( deviceorientation event absolute value )
-
- // data.dm.x ( devicemotion event acceleration x value )
- // data.dm.y ( devicemotion event acceleration y value )
- // data.dm.z ( devicemotion event acceleration z value )
-
- // data.dm.gx ( devicemotion event accelerationIncludingGravity x value )
- // data.dm.gy ( devicemotion event accelerationIncludingGravity y value )
- // data.dm.gz ( devicemotion event accelerationIncludingGravity z value )
-
- // data.dm.alpha ( devicemotion event rotationRate alpha value )
- // data.dm.beta ( devicemotion event rotationRate beta value )
- // data.dm.gamma ( devicemotion event rotationRate gamma value )
-
-
- })
-
- }).catch((e)=>{
-
- console.log(e)
-
- })
-
- }
-
-
-
- setValue(v, options={} ) {
-
- this.value = v
-
- // if (options.send) this.sendValue()
- if (options.sync) this.changed(options)
-
- }
-
- onRemove() {
-
- this.sensor.end()
-
- super.onRemove()
-
- }
-
-
-}
-
-module.exports = Gyroscope
diff --git a/src/client/widgets/scripts/script-vm.js b/src/client/widgets/scripts/script-vm.js
deleted file mode 100644
index 9f0ac7fa..00000000
--- a/src/client/widgets/scripts/script-vm.js
+++ /dev/null
@@ -1,365 +0,0 @@
-var widgetManager = require('../../managers/widgets'),
- stateManager = require('../../managers/state'),
- cache = require('../../managers/cache'),
- {deepCopy} = require('../../utils'),
- {urlParser} = require('../utils'),
- Vm = require('../vm'),
- toolbar
-
-
-class ScriptVm extends Vm {
-
- constructor() {
-
- super()
-
- this.valueOptions = []
- this.widget = []
-
- }
-
- getValueOptions() {
-
- return this.valueOptions[this.valueOptions.length - 1] || {send: true, sync: true}
-
- }
-
- setValueOptions(options) {
-
- if (!options) this.valueOptions.pop()
- else this.valueOptions.push(options)
-
- }
-
- setWidget(widget) {
-
- if (!widget) this.widget.pop()
- else this.widget.push(widget)
-
- }
-
- getWidget() {
-
- return this.widget[this.widget.length - 1]
-
- }
-
- resolveId(id) {
-
- var widget = this.getWidget()
- if (widget.builtIn) widget = widget.parent
-
- if (id === 'this') return [widget]
- else if (id === 'parent' && widget.parent !== widgetManager) return [widget.parent]
- else return widgetManager.getWidgetById(id)
-
- }
-
- registerGlobals() {
-
- super.registerGlobals()
-
- this.sandbox.contentWindow.set = (id, value, extraOptions = {send: true, sync: true})=>{
-
- var options = this.getValueOptions()
- options.fromScript = true
-
- // if (id === options.id) options.sync = false // loop stop
- // if (this.getWidget() === options.widget) options.sync = false // loop stop
-
- if (extraOptions.send === false) options.send = false
- if (extraOptions.sync === false) options.sync = false
-
- var widgets
- if (id.includes('*')) {
- var widget = this.getWidget()
- if (widget.builtIn) widget = widget.parent
- widgets = this.resolveId(
- Object.keys(widgetManager.idRoute).filter(key => key.match(new RegExp('^' + id.replace(/\*/g, '.*') + '$')))
- ).filter(w => w !== widget)
- } else {
- widgets = this.resolveId(id).slice(0, 1)
- }
-
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- widgets[i].setValue(value, options)
-
- }
-
- }
-
- this.sandbox.contentWindow.send = (target, address, ...args)=>{
-
- var options = this.getValueOptions()
-
- if (!options.send) return
-
- if (target && target[0] === '/') {
- args.unshift(address)
- address = target
- target = null
- }
-
- var overrides = {
- address,
- v: args,
- preArgs: []
- }
-
- if (target) overrides.target = Array.isArray(target) ? target : [target]
-
- var widget = this.getWidget()
- if (widget.builtIn) widget = widget.parent
-
- widget.sendValue(overrides, {force: true})
-
- }
-
- this.sandbox.contentWindow.get = (id)=>{
-
- var widgets = this.resolveId(id)
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- if (widgets[i].getValue) {
-
- var v = widgets[i].getValue()
- if (v !== undefined) return v
-
- }
-
- }
-
- }
-
- this.sandbox.contentWindow.getProp = (id, prop)=>{
-
- var widgets = this.resolveId(id)
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- var v = widgets[i].getProp(prop)
- if (v !== undefined) return v
-
- }
-
- }
-
- this.sandbox.contentWindow.updateProp = (id, prop)=>{
-
- var widgets = this.resolveId(id),
- widget = this.getWidget()
-
- if (widget.builtIn) widget = widget.parent
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- widgets[i].updateProps(Array.isArray(prop) ? prop : [prop], widget)
-
- }
-
- }
-
- this.sandbox.contentWindow.getIndex = (id = 'this')=>{
-
- var widget = this.resolveId(id).pop()
- if (widget) return widget.parent.children.indexOf(widget)
-
- }
-
- this.sandbox.contentWindow.getScroll = (id)=>{
-
- var widgets = this.resolveId(id)
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- if (widgets[i].scroll) return widgets[i].scroll()
-
- }
-
- return []
-
- }
-
- this.sandbox.contentWindow.setScroll = (id, x, y)=>{
-
- var widgets = this.resolveId(id)
-
- for (var i = widgets.length - 1; i >= 0; i--) {
-
- if (widgets[i].scroll) widgets[i].scroll([x, y])
-
- }
-
- }
-
- this.sandbox.contentWindow.httpGet = (url, callback)=>{
-
- var parser = urlParser(url),
- err = (e)=>{console.error(e)}
-
- if (!parser.isLocal()) return err('httpGet error (' + url + '): non-local url')
-
- var xhr = new XMLHttpRequest()
- xhr.open('GET', url, true)
- xhr.onload = (e)=>{
- if (xhr.readyState === 4 && xhr.status === 200 && callback) {
- callback(xhr.responseText)
- }
- }
- xhr.onerror = (e)=>err('httpGet error (' + url + '): ' + xhr.statusText)
- xhr.send(null)
-
- }
-
- this.sandbox.contentWindow.stateGet = (filter)=>{
-
- if (filter) {
-
- filter = Array.isArray(filter) ? filter : [filter]
-
- var containers = filter.map(x=>this.resolveId(x)).reduce((a,b)=>a.concat(b), [])
-
- if (!containers.length) return
- filter = (widget)=>{
- return containers.some(x=>x.contains(widget) || x === widget)
- }
- }
-
- return deepCopy(stateManager.get(filter))
-
- }
-
- this.sandbox.contentWindow.stateSet = (state)=>{
-
- var options = this.getValueOptions()
- stateManager.set(state, options.send)
-
- }
-
-
- this.sandbox.contentWindow.storage = {
-
- setItem: (k, v)=>cache.set('script.' + k, v),
- getItem: (k)=>cache.get('script.' + k),
- removeItem: (k)=>cache.remove('script.' + k),
- clear: ()=>cache.clear('script.')
-
- }
-
- this.sandbox.contentWindow.setTimeout = (id, callback, timeout)=>{
-
- if (typeof id === 'function') {
- timeout = callback
- callback = id
- id = undefined
- }
-
- var widget = this.getWidget(),
- options = this.getValueOptions()
-
-
- if (widget.timeouts[id] !== undefined) {
- clearTimeout(widget.timeouts[id])
- delete widget.timeouts[id]
- }
- widget.timeouts[id] = setTimeout(()=>{
- this.setWidget(widget)
- this.setValueOptions(options)
- try {
- callback()
- } catch(e) {
- this.errorProp('script', 'setTimeout', e)
- }
- this.setWidget()
- this.setValueOptions()
- }, timeout)
-
- }
-
- this.sandbox.contentWindow.clearTimeout = (id)=>{
-
- var widget = this.getWidget()
-
- clearTimeout(widget.timeouts[id])
- delete widget.timeouts[id]
-
- }
-
- this.sandbox.contentWindow.setInterval = (id, callback, timeout)=>{
-
- if (typeof id === 'function') {
- timeout = callback
- callback = id
- id = undefined
- }
-
- var widget = this.getWidget(),
- options = this.getValueOptions()
-
-
- if (widget.intervals[id] !== undefined) clearTimeout(widget.intervals[id])
- delete widget.intervals[id]
-
- widget.intervals[id] = setInterval(()=>{
- this.setWidget(widget)
- this.setValueOptions(options)
- try {
- callback()
- } catch(e) {
- this.errorProp('script', 'setInterval', e)
- }
- this.setWidget()
- this.setValueOptions()
- }, timeout)
-
- }
-
- this.sandbox.contentWindow.clearInterval = (id)=>{
-
- var widget = this.getWidget()
-
- clearInterval(widget.intervals[id])
- delete widget.intervals[id]
-
- }
-
- this.sandbox.contentWindow.unfocus = ()=>{
-
- // built-in client only: electron will call window.blur()
- console.debug('ELECTRON.BLUR()')
-
- }
-
- this.sandbox.contentWindow.toolbar = (...args)=>{
-
- var options = this.getValueOptions()
-
- if (!options.send) return
-
- toolbar = toolbar || require('../../ui/main-menu')
-
- var action = toolbar.entries.filter(x=>!x.separator)
-
- for (var i of args) {
- if (action[i]) action = action[i].action
- if (!Array.isArray(action)) break
- action = action.filter(x=>!x.separator)
- }
-
- if (typeof action === 'function') action()
-
- }
-
- for (var imports of ['set', 'get', 'getProp', 'getIndex', 'updateProp', 'send', 'httpGet', 'stateGet', 'stateSet', 'storage',
- 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'unfocus', 'setScroll', 'getScroll', 'toolbar']) {
- this.sanitize(this.sandbox.contentWindow[imports])
- }
-
- }
-
-}
-
-module.exports = ScriptVm
diff --git a/src/client/widgets/scripts/script-vm.mjs b/src/client/widgets/scripts/script-vm.mjs
new file mode 100644
index 00000000..e5312e32
--- /dev/null
+++ b/src/client/widgets/scripts/script-vm.mjs
@@ -0,0 +1,686 @@
+import widgetManager from '../../managers/widgets.mjs'
+import stateManager from '../../managers/state.mjs'
+import cache from '../../managers/cache.mjs'
+import {deepCopy} from '../../utils.mjs'
+import {urlParser} from '../utils.mjs'
+import Vm from '../vm.mjs'
+import ipc from '../../ipc/index.mjs'
+import uiFilebrowser from '../../ui/ui-filebrowser.mjs'
+import uiFileUpload from '../../ui/ui-fileupload.mjs'
+import {setFOCUSABLE} from '../../globals.mjs'
+
+var toolbar
+setTimeout(async()=>{
+ // use setTimeout to fix init order in safari...
+ toolbar = (await import('../../ui/main-menu.mjs')).default
+})
+
+class ScriptVm extends Vm {
+
+ constructor() {
+
+ super()
+
+ this.valueOptions = []
+
+ }
+
+ getValueOptions() {
+
+ return this.valueOptions[this.valueOptions.length - 1] || {send: true, sync: true}
+
+ }
+
+ setValueOptions(options) {
+
+ if (!options) this.valueOptions.pop()
+ else this.valueOptions.push(options)
+
+ }
+
+ resolveId(id) {
+
+ var widget = this.getWidget()
+
+ if (id === 'this') return [widget]
+ else if (id === 'parent' && widget.parent !== widgetManager) return [widget.parent]
+ else return widgetManager.getWidgetById(id, widget.scopes)
+
+ }
+
+ checkContext(name) {
+ if (this.widget.length === 0) throw name + '() cannot be called from outside the script property'
+ }
+
+ registerGlobals() {
+
+ this.globals.set = (id, value, extraOptions = {send: true, sync: true})=>{
+
+ this.checkContext('set')
+
+ var widget = this.getWidget()
+ var options = {},
+ valueOptions = this.getValueOptions()
+
+ for (var k in valueOptions) {
+ if (k === 'widget') options[k] = valueOptions[k]
+ else options[k] = deepCopy(valueOptions[k])
+ }
+
+ options.fromScript = widget.hash
+
+ if (options.dragged) options.dragged = false
+ if (options.local) options.local = false
+
+ // if (id === options.id) options.sync = false // loop stop
+ // if (this.getWidget() === options.widget) options.sync = false // loop stop
+
+ if (extraOptions.send === false) options.send = false
+ if (extraOptions.sync === false) options.sync = false
+ if (extraOptions.script === false) options.script = false
+ if (extraOptions.external === true) {
+ options.fromExternal = true
+ options.send = false
+ }
+
+ var widgets
+ if (id.includes('*')) {
+ widgets = this.resolveId(
+ Object.keys(widgetManager.idRoute).filter(key => key.match(new RegExp('^' + id.replace(/\*/g, '.*') + '$')))
+ ).filter(w => w !== widget)
+ } else {
+ widgets = this.resolveId(id).slice(0, 1)
+ }
+
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ widgets[i].setValue(value, options)
+
+ }
+
+ }
+
+ this.globals.setVar = (id, name, value)=>{
+
+ this.checkContext('setVar')
+
+ var widgets
+ if (id.includes('*')) {
+ var widget = this.getWidget()
+ widgets = this.resolveId(
+ Object.keys(widgetManager.idRoute).filter(key => key.match(new RegExp('^' + id.replace(/\*/g, '.*') + '$')))
+ ).filter(w => w !== widget)
+ } else {
+ widgets = this.resolveId(id)
+ }
+
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+
+ if (widgets[i].variables[name]) {
+
+ widgets[i].variables[name].value = value
+ widgets[i].variables[name].updated = 1
+ widgets[i].updateProps(widgets[i].variables[name].propNames)
+ widgets[i].variables[name].updated = 0
+
+ } else {
+
+ widgets[i].variables[name] = {value: value, propNames: []}
+
+ }
+
+ }
+
+ }
+
+ this.globals.send = (target, address, ...args)=>{
+
+ this.checkContext('send')
+
+ var options = this.getValueOptions()
+
+ if (!options.send) return
+
+ if (target && target[0] === '/') {
+ args.unshift(address)
+ address = target
+ target = null
+ }
+
+ var overrides = {
+ address,
+ v: args,
+ preArgs: []
+ }
+
+ if (target) overrides.target = Array.isArray(target) ? target : [target]
+
+ var widget = this.getWidget()
+
+ widget.sendValue(overrides, {force: true})
+
+ }
+
+ this.globals.get = (id)=>{
+
+ this.checkContext('get')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].getValue) {
+
+ var v = widgets[i].getValue()
+ if (v !== undefined) return v
+
+ }
+
+ }
+
+ }
+
+ this.globals.getVar = (id, name)=>{
+
+ this.checkContext('getVar')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].variables[name]) return deepCopy(widgets[i].variables[name].value)
+
+ }
+
+ }
+
+ this.globals.getProp = (id, prop)=>{
+
+ this.checkContext('getProp')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ var v = widgets[i].getProp(prop)
+ if (v !== undefined) return deepCopy(v)
+
+ }
+
+ }
+
+ this.globals.updateProp = (id, prop)=>{
+
+ this.checkContext('updateProp')
+
+ var widgets = this.resolveId(id),
+ widget = this.getWidget()
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ widgets[i].updateProps(Array.isArray(prop) ? prop : [prop], widget)
+
+ }
+
+ }
+
+ this.globals.updateCanvas = (id)=>{
+
+ this.checkContext('updateCanvas')
+
+ var widgets = this.resolveId(id)
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].batchDraw) widgets[i].batchDraw()
+
+ }
+
+ }
+
+ this.globals.getIndex = (id = 'this')=>{
+
+ this.checkContext('getIndex')
+
+ var widget = this.resolveId(id).pop()
+ if (widget) return widget.parent.children.indexOf(widget)
+
+ }
+
+ this.globals.getScroll = (id)=>{
+
+ this.checkContext('getScroll')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].getProp('scroll')) return widgets[i].getScroll()
+
+ }
+
+ return []
+
+ }
+
+ this.globals.setScroll = (id, x, y)=>{
+
+ this.checkContext('setScroll')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].getProp('scroll')) widgets[i].setScroll(x, y, true, false)
+
+ }
+
+ }
+
+ this.globals.scrollIntoView = (id, options)=>{
+
+ this.checkContext('setScroll')
+
+ var widgets = this.resolveId(id)
+
+ for (var i = widgets.length - 1; i >= 0; i--) {
+
+ if (widgets[i].container && widgets[i].isVisible()) {
+ widgets[i].container.scrollIntoView(options)
+ }
+
+ }
+
+ }
+
+
+
+ this.globals.httpGet = (url, callback)=>{
+
+ this.checkContext('httpGet')
+
+ var parser = urlParser(url),
+ err = (e)=>{console.error(e)}
+
+ if (!parser.isLocal()) return err('httpGet error (' + url + '): non-local url')
+
+ var xhr = new XMLHttpRequest()
+ xhr.open('GET', url, true)
+ xhr.onload = (e)=>{
+ if (xhr.readyState === 4 && xhr.status === 200 && callback) {
+ callback(xhr.responseText)
+ }
+ }
+ xhr.onerror = (e)=>err(`httpGet error (${url}): ${xhr.status} ${xhr.statusText}`)
+ xhr.send(null)
+
+ }
+
+ this.globals.stateGet = (filter)=>{
+
+ this.checkContext('stateGet')
+
+ if (filter) {
+
+ filter = Array.isArray(filter) ? filter : [filter]
+
+ var containers = filter.map(x=>this.resolveId(x)).reduce((a,b)=>a.concat(b), [])
+
+ if (!containers.length) return
+ filter = (widget)=>{
+ return containers.some(x=>x.contains(widget) || x === widget)
+ }
+ }
+
+ return deepCopy(stateManager.get(filter))
+
+ }
+
+ this.globals.stateSet = (state, extraOptions = {})=>{
+
+ this.checkContext('stateSet')
+
+ var options = this.getValueOptions()
+ stateManager.set(state, extraOptions.send === false ? false : options.send)
+
+ }
+
+
+ this.globals.storage = {
+
+ setItem: (k, v)=>{
+ this.checkContext('storage.setItem')
+ cache.set('script.' + k, v)
+ },
+ getItem: (k)=>{
+ this.checkContext('storage.getItem')
+ return cache.get('script.' + k)
+ },
+ removeItem: (k)=>{
+ this.checkContext('storage.removeItem')
+ cache.remove('script.' + k)
+ },
+ clear: ()=>{
+ this.checkContext('storage.clear')
+ cache.clear('script.')
+ }
+
+ }
+
+ this.globals.setTimeout = (id, callback, timeout)=>{
+
+ this.checkContext('setTimeout')
+
+ if (typeof id === 'function') {
+ timeout = callback
+ callback = id
+ id = undefined
+ }
+
+ var widget = this.getWidget(),
+ options = this.getValueOptions()
+
+
+ if (widget.timeouts[id] !== undefined) {
+ clearTimeout(widget.timeouts[id])
+ delete widget.timeouts[id]
+ }
+ widget.timeouts[id] = setTimeout(()=>{
+ this.setWidget(widget)
+ this.setValueOptions(options)
+ try {
+ callback()
+ } catch(e) {
+ widget.errorProp('script', 'setTimeout', e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ }, timeout)
+
+ return id
+
+ }
+
+ this.globals.clearTimeout = (id)=>{
+
+ this.checkContext('clearTimeout')
+
+ var widget = this.getWidget()
+
+ clearTimeout(widget.timeouts[id])
+ delete widget.timeouts[id]
+
+ }
+
+ this.globals.setInterval = (id, callback, timeout)=>{
+
+ this.checkContext('setInterval')
+
+ if (typeof id === 'function') {
+ timeout = callback
+ callback = id
+ id = undefined
+ }
+
+ var widget = this.getWidget(),
+ options = this.getValueOptions()
+
+
+ if (widget.intervals[id] !== undefined) clearTimeout(widget.intervals[id])
+ delete widget.intervals[id]
+
+ widget.intervals[id] = setInterval(()=>{
+ this.setWidget(widget)
+ this.setValueOptions(options)
+ try {
+ callback()
+ } catch(e) {
+ widget.errorProp('script', 'setInterval', e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ }, timeout)
+
+ return id
+
+ }
+
+ this.globals.clearInterval = (id)=>{
+
+ this.checkContext('clearInterval')
+
+ var widget = this.getWidget()
+
+ clearInterval(widget.intervals[id])
+ delete widget.intervals[id]
+
+ }
+
+
+ this.globals.setFocus = (id)=>{
+
+ this.checkContext('setFocus')
+
+ if (id) {
+ var widgets = this.resolveId(id)
+
+ if (widgets.length) {
+ if (widgets[0].focus) widgets[0].focus()
+ }
+ } else if (document.activeElement) {
+ document.activeElement.blur()
+ }
+
+ // built-in client only: electron will call window.focus()
+ console.debug('ELECTRON.FOCUS()')
+
+ }
+
+ this.globals.unfocus = ()=>{
+
+ this.checkContext('unfocus')
+
+ window.blur()
+ // built-in client only: electron will call window.blur()
+ console.debug('ELECTRON.BLUR()')
+
+ }
+
+ this.globals.setFocusable = (focusable)=>{
+
+ this.checkContext('setFocusable')
+ setFOCUSABLE(!!focusable)
+ console.debug('ELECTRON.SETFOCUSABLE('+(focusable ? 1 : 0)+')')
+
+ }
+
+
+ function getToolbarActionById(id, entries) {
+ for (var a of entries) {
+ if (a.id == id) {
+ return a
+ }
+ if (Array.isArray(a.action)) {
+ var ret = getToolbarActionById(id, a.action)
+ if (ret) return ret
+ }
+ }
+ }
+
+ this.globals.toolbar = (...args)=>{
+
+ this.checkContext('toolbar')
+
+ var options = this.getValueOptions()
+
+ if (!options.send) return
+
+ var action = toolbar.entries.filter(x=>!x.separator)
+
+ if (typeof args[0] == 'string') {
+
+ action = getToolbarActionById(args[0], action)
+ if (action) action = action.action // get callback
+ if (action && typeof action.class == 'function') {
+ if (action.class().match(/disabled/)) action = null
+ }
+
+ } else {
+
+ for (var i of args) {
+ if (action[i]) action = action[i].action
+ if (!Array.isArray(action)) break
+ action = action.filter(x=>!x.separator)
+ }
+
+ }
+
+ if (typeof action === 'function') action()
+
+ }
+
+ this.globals.getToolbar = (id)=>{
+
+ this.checkContext('toolbar')
+
+ var options = this.getValueOptions()
+
+ if (!options.send) return
+
+ var action = getToolbarActionById(id, toolbar.entries.filter(x=>!x.separator))
+
+ if (action && typeof action.class == 'function') return action.class().split(' ').includes('on')
+
+ }
+
+ this.globals.openUrl = (url)=>{
+
+ this.checkContext('openUrl')
+
+ var options = this.getValueOptions()
+
+ if (options.send) window.open(url, '_blank')
+
+ }
+
+ this.globals.runAs = (id, callback)=>{
+
+ this.checkContext('runAs')
+
+ var widgets = this.resolveId(id),
+ widget = this.getWidget()
+
+ if (widgets.length) {
+
+ this.setWidget(widgets[0])
+ try {
+ callback()
+ } catch(e) {
+ widget.errorProp('script', 'runAs', e)
+ }
+ this.setWidget()
+
+ }
+
+ }
+
+ this.globals.reload = (keepState = true)=>{
+
+ this.checkContext('reload')
+
+ var options = this.getValueOptions(),
+ widget = this.getWidget()
+
+ if (options.onCreate) {
+ widget.errorProp('onCreate', '', 'reload() cannot be called from onCreate')
+ } else if (options.send){
+ if (keepState) ipc.trigger('reload')
+ else window.location.href = window.location.href
+ }
+
+
+ }
+
+ this.globals.Image = Image
+
+ this.globals.getNavigator = ()=>{
+ this.checkContext('getNavigator')
+ return navigator
+
+ }
+
+
+ this.globals.browseFile = (options, callback)=>{
+ this.checkContext('browseFile')
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+
+ if (typeof callback === 'function') {
+
+ var widget = this.getWidget(),
+ valueOptions = this.getValueOptions()
+
+ uiFilebrowser({
+ extension: options.extention || '*',
+ directory: options.directory || undefined,
+ loadDir: !!options.allowDir,
+ save: options.mode === 'save'
+ }, (path)=>{
+ this.setWidget(widget)
+ this.setValueOptions(valueOptions)
+ try {
+ callback(path.join(path[0][0] === '/' ? '/' : '\\'))
+ } catch(e) {
+ widget.errorProp('script', 'browseFile', e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ })
+ } else {
+ widget.errorProp('script', 'browseFile', 'callback argument must be a function')
+ }
+ }
+
+ this.globals.uploadFile = (options, callback)=>{
+ this.checkContext('uploadFile')
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+
+ if (typeof callback === 'function') {
+
+ var widget = this.getWidget(),
+ valueOptions = this.getValueOptions()
+
+ uiFileUpload(options.types, (path, content)=>{
+ this.setWidget(widget)
+ this.setValueOptions(valueOptions)
+ try {
+ callback(content)
+ } catch(e) {
+ widget.errorProp('script', 'uploadFile', e)
+ }
+ this.setWidget()
+ this.setValueOptions()
+ }, (e)=>{
+ widget.errorProp('script', 'uploadFile', e)
+ })
+ } else {
+ widget.errorProp('script', 'browseFile', 'callback argument must be a function')
+ }
+ }
+
+ super.registerGlobals()
+
+ }
+
+}
+
+export default new ScriptVm()
diff --git a/src/client/widgets/scripts/script-widget.mjs b/src/client/widgets/scripts/script-widget.mjs
new file mode 100644
index 00000000..0db37429
--- /dev/null
+++ b/src/client/widgets/scripts/script-widget.mjs
@@ -0,0 +1,127 @@
+import Widget from '../common/widget.mjs'
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import Script from './script.mjs'
+
+class ScriptWidget extends Widget {
+
+ static description() {
+
+ return 'Scripting widget utility with keyboard bindings.mjs'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults()
+ delete defaults.widget.visible
+ delete defaults.widget.interaction
+ delete defaults.geometry
+ delete defaults.style
+ defaults.scripting = {
+ onCreate: {type: 'script', value: '', editor: 'javascript', help: ['Script executed when the widget is created. See documentation.']},
+ onValue: {type: 'script', value: '', editor: 'javascript', help: ['Script executed when the widget\'s value updates. See documentation.']},
+ onKeyboard: {type: 'script', value: '', editor:'javascript', help: 'Script executed whenever the widget receives a keyboard event if `keyBinding` is set). See documentation.'},
+
+ _separator: 'Keyboard events',
+
+ keyBinding: {type: 'string|array', value: '', help: [
+ 'Key combo `string` or `array` of strings (see KeyboardJS documentation).',
+ 'If the editor is enabled, some keys / combos will not work.',
+ 'To process all keystroke events, write `[\'\']`'
+ ]},
+ keyRepeat: {type: 'boolean', value: true, help: 'Set to `false` to prevent keydown repeats when holding the key combo pressed'},
+ keyType: {type: 'string', value: 'keydown', choices: ['keydown', 'keyup', 'both'], help: 'Determines which key event trigger the script\'s execution'},
+
+ }
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super({...options, html: null})
+
+ this.noValueState = true
+
+
+ if (this.getProp('onKeyboard') && this.getProp('keyBinding')) {
+
+ this.keyCb = this.keyboardCallback.bind(this)
+
+ keyboardJS.withContext('global', ()=>{
+
+ keyboardJS.bind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
+
+ })
+
+ this.scripts.onKeyboard = new Script({
+ widget: this,
+ property: 'onKeyboard',
+ code: this.getProp('onKeyboard'),
+ context: {
+ type: '',
+ key: '',
+ code: 0,
+ ctrl: false,
+ shift: false,
+ alt: false,
+ meta: false,
+ }
+ })
+
+ }
+
+ }
+
+ setValue(v, options={}) {
+
+ this.value = v
+
+ if (options.sync) this.changed(options)
+
+ }
+
+ keyboardCallback(e) {
+
+ if (e.catchedByEditor) return
+
+ if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT')) return
+
+ if (this.getProp('keyType') !== 'both' && e.type !== this.getProp('keyType')) return
+
+ if (e.type === 'keydown' && !this.getProp('keyRepeat')) e.preventRepeat()
+
+ if (e.preventDefault) e.preventDefault()
+
+ this.scripts.onKeyboard.run({
+ type: e.type,
+ key: e.key,
+ code: e.code,
+ ctrl: e.ctrlKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ meta: e.metaKey
+ }, {send: true, sync: true})
+
+ }
+
+ onRemove() {
+
+
+ if (this.getProp('onKeyboard') && this.getProp('keyBinding')) {
+
+ keyboardJS.withContext('global', ()=>{
+
+ keyboardJS.unbind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
+
+ })
+
+ }
+
+ super.onRemove()
+
+ }
+
+}
+
+export default ScriptWidget
diff --git a/src/client/widgets/scripts/script.js b/src/client/widgets/scripts/script.js
deleted file mode 100644
index bf87910e..00000000
--- a/src/client/widgets/scripts/script.js
+++ /dev/null
@@ -1,192 +0,0 @@
-var Widget = require('../common/widget'),
- keyboardJS = require('keyboardjs/dist/keyboard.min.js'),
- ScriptVm = require('./script-vm'),
- scriptVm = new ScriptVm()
-
-
-class Script extends Widget {
-
- static description() {
-
- return 'Evaluates a script each time it receives a value.'
-
- }
-
- static defaults() {
-
- return super.defaults().extend({
- widget: {
- visible: null,
- interaction: null
- },
- geometry: null,
- style: null,
- class_specific: {
- event: {type: 'string', value: 'value', choices: ['value', 'keyboard'], help: 'Define which events trigger the script\'s execution.'},
- script: {type: 'script', value: '', help: 'Script executed whenever the widget\'s receives the defined event. See documentation.'},
-
- _separator: 'event: keyboard',
-
- keyBinding: {type: 'string|array', value: '', help: 'Key combo `string` or `array` of strings (see KeyboardJS documentation)'},
- keyRepeat: {type: 'boolean', value: true, help: 'Set to `false` to prevent keydown repeats when holding the key combo pressed'},
- keyType: {type: 'string', value: 'keydown', choices: ['keydown', 'keyup', 'both'], help: 'Determines which key event trigger the script\'s execution'},
- },
- value: {
- script: null
- }
- })
-
- }
-
- constructor(options) {
-
- super({...options, html: null})
-
- this.noValueState = true
-
- this.builtIn = options.builtIn
-
- this.scriptLock = false
-
- this.timeouts = {}
- this.intervals = {}
-
- if (this.getProp('event') === 'value') {
-
- this.compile({
- id: '',
- value: 0,
- touch: undefined
- })
-
- } else if (this.getProp('event') === 'keyboard' && this.getProp('keyBinding')) {
-
- this.keyCb = this.keyboardCallback.bind(this)
-
- keyboardJS.withContext('global', ()=>{
-
- keyboardJS.bind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
-
- })
-
- this.compile({
- type: '',
- key: '',
- code: 0,
- ctrl: false,
- shift: false,
- alt: false,
- meta: false,
- })
-
- }
-
- }
-
- compile(context) {
-
- try {
-
- this.script = scriptVm.compile(this.getProp('script'), context)
-
- } catch(err) {
-
- this.errorProp('script', 'javascript', err)
- this.script = ()=>{}
-
- }
-
- }
-
- run(context) {
-
- if (this.scriptLock) return
-
- scriptVm.setWidget(this)
-
- this.scriptLock = true
- var returnValue
- try {
- returnValue = this.script(context, this.builtIn ? this.parent.parsersLocalScope : this.parsersLocalScope)
- } catch(err) {
- this.errorProp('script', 'javascript', err)
- }
- this.scriptLock = false
-
- scriptVm.setWidget()
-
- return returnValue
-
- }
-
- setValue(v, options={}) {
-
- if (this.getProp('event') === 'value') {
-
- scriptVm.setValueOptions(options)
-
- var returnValue = this.run({
- value: v,
- id: options.id,
- touch: options.touch
- })
-
- scriptVm.setValueOptions(options)
-
- return returnValue
-
- }
-
- }
-
- keyboardCallback(e) {
-
- if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT')) return
-
- if (this.getProp('keyType') !== 'both' && e.type !== this.getProp('keyType')) return
-
- if (e.type === 'keydown' && !this.getProp('keyRepeat')) e.preventRepeat()
-
- e.preventDefault()
-
- this.run({
- type: e.type,
- key: e.key,
- code: e.code,
- ctrl: e.ctrlKey,
- shift: e.shiftKey,
- alt: e.altKey,
- meta: e.metaKey
- })
-
-
- }
-
- onRemove() {
-
-
- if (this.getProp('event') === 'keyboard' && this.getProp('keyBinding')) {
-
- keyboardJS.withContext('global', ()=>{
-
- keyboardJS.unbind(this.getProp('keyBinding'), this.keyCb, this.keyCb)
-
- })
-
- }
-
- for (let k in this.timeouts) {
- clearTimeout(this.timeouts[k])
- }
-
- for (let k in this.intervals) {
- clearInterval(this.intervals[k])
- }
-
- super.onRemove()
-
- }
-
-}
-
-module.exports = Script
diff --git a/src/client/widgets/scripts/script.mjs b/src/client/widgets/scripts/script.mjs
new file mode 100644
index 00000000..a43d9532
--- /dev/null
+++ b/src/client/widgets/scripts/script.mjs
@@ -0,0 +1,69 @@
+import scriptVm from './script-vm.mjs'
+
+var noop = ()=>{}
+
+class Script {
+
+ constructor(options) {
+
+ this.lock = false
+ this.timeouts = {}
+ this.intervals = {}
+ this.widget = options.widget
+ this.property = options.property
+
+ if (!options.code) {
+
+ this.script = noop
+
+ } else {
+
+ try {
+ this.script = scriptVm.compile(options.code, options.context)
+ } catch(err) {
+ this.widget.errorProp(this.property, 'javascript', err)
+ this.script = noop
+ }
+
+ }
+
+ }
+
+ run(context, options) {
+
+ if (this.lock) return
+
+ scriptVm.setValueOptions(options)
+ scriptVm.setWidget(this.widget)
+
+ this.lock = true
+ var returnValue
+ try {
+ returnValue = this.script(context, this.widget.parsersLocalScope)
+ } catch(err) {
+ this.widget.errorProp(this.property, 'javascript', err)
+ }
+ this.lock = false
+
+ scriptVm.setWidget()
+ scriptVm.setValueOptions()
+
+ return returnValue
+
+ }
+
+ onRemove() {
+
+ for (let k in this.widget.timeouts) {
+ clearTimeout(this.widget.timeouts[k])
+ }
+
+ for (let k in this.widget.intervals) {
+ clearInterval(this.widget.intervals[k])
+ }
+
+ }
+
+}
+
+export default Script
diff --git a/src/client/widgets/scripts/variable.js b/src/client/widgets/scripts/variable.mjs
similarity index 68%
rename from src/client/widgets/scripts/variable.js
rename to src/client/widgets/scripts/variable.mjs
index c03bf7d5..5bc448b4 100644
--- a/src/client/widgets/scripts/variable.js
+++ b/src/client/widgets/scripts/variable.mjs
@@ -1,7 +1,7 @@
-var Widget = require('../common/widget'),
- StaticProperties = require('../mixins/static_properties')
+import Widget from '../common/widget.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
-module.exports = class Variable extends StaticProperties(Widget, {interaction: false, visible: false}) {
+export default class Variable extends StaticProperties(Widget, {interaction: false, visible: false}) {
static description() {
@@ -34,6 +34,7 @@ module.exports = class Variable extends StaticProperties(Widget, {interaction: f
this.value = v
if (options.sync) this.changed(options)
+ if (options.send) this.sendValue(null, {syncOnly: true})
}
diff --git a/src/client/widgets/sliders/encoder.js b/src/client/widgets/sliders/encoder.mjs
similarity index 67%
rename from src/client/widgets/sliders/encoder.js
rename to src/client/widgets/sliders/encoder.mjs
index c6b213a5..5fe30ae6 100644
--- a/src/client/widgets/sliders/encoder.js
+++ b/src/client/widgets/sliders/encoder.mjs
@@ -1,27 +1,29 @@
-var Knob = require('./knob'),
- StaticProperties = require('../mixins/static_properties')
+import Knob from './knob.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
-module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range: {min: 0, max: 1}}) {
+export default class Encoder extends StaticProperties(Knob, {angle: 360, range: {min: 0, max: 1}, design: 'encoder'}) {
static description() {
- return 'A knob that sends a relative direction infomation instead of an absolute value.'
+ return 'A knob that sends a relative direction information instead of an absolute value.'
}
static defaults() {
- return super.defaults().extend({
+ var defaults = super.defaults().extend({
style: {
_separator_knob_style: null,
design: null,
pips: null,
dashed: null,
angle: null,
+ colorKnob: null
},
class_specific: {
origin: null,
steps: null,
+ spring: null,
ticks: {type: 'number', value: '', help: 'Defines the granularity / verbosity of the encoder (number of step for a 360° arc)'},
sensitivity: {type: 'number', value: 1, help: 'When set between 0 and 1, reduces the encoder\'s verbosity'},
back: {type: '*', value: -1, help: 'Defines which value is sent when rotating the encoder anticlockwise'},
@@ -31,10 +33,11 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
'- Set to `null` to send send no argument in the osc message',
'- Can be an `object` if the type needs to be specified'
]},
- mode: {type: 'string', value: 'circular', choices: ['circular', 'snap', 'vertical'], help: [
+ mode: {type: 'string', value: 'circular', choices: ['circular', 'snap', 'vertical', 'horizontal'], help: [
'- `circular`: relative move in circular motion',
'- `snap`: snap to touch position and move in vertical motion',
'- `vertical`: relative move in vertical motion',
+ '- `horizontal`: relative move in horizontal motion',
]},
doubleTap: {type: 'boolean', value: false, help: [
'Set to `true` to make the fader reset to its `default` value when receiving a double tap.',
@@ -43,6 +46,14 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
}
})
+ defaults.scripting.onValue.help.push(
+ 'Additional variables:',
+ '- `locals.speed`: encoder\'s speed (reduce `sensitivity` to increase averaging)',
+ '- `locals.angle`: encoder\'s angle in degrees'
+ )
+
+ return defaults
+
}
constructor(options) {
@@ -52,6 +63,7 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
this.previousPercent = 50
this.percent = 50
this.ignoredValues = 0
+ this.speed = []
this.setValue(this.getProp('release'), {dragged: true})
}
@@ -101,26 +113,25 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
dragHandle(e) {
// knob.js without clipping + extra case for snap
+ var inertia = e.fingers > 1 || e.ctrlKey ? 10 : e.inertia
- if ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
+ if ((this.getProp('mode') === 'vertical' && !e.traversing)) {
// vertical
- this.setPercent(-100 * e.movementY / this.height + this.percent)
+ this.setPercent(this.percent - 100 * (e.movementY / inertia * this.getProp('sensitivity')) / this.minDimension)
+
+ } else if ((this.getProp('mode') === 'horizontal' && !e.traversing)) {
+ // horizontal
+ this.setPercent(this.percent + 100 * (e.movementX / inertia * this.getProp('sensitivity')) / this.minDimension)
} else {
// snap or circular
var offsetX = this.lastOffsetX + e.movementX,
offsetY = this.lastOffsetY + e.movementY
- if (e.traversing || this.getProp('mode') === 'circular') {
- // circular
- var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
- if (Math.abs(diff) < 50 && diff !== 0) this.setPercent(this.percent + diff)
-
- } else {
-
- // snap
- this.setPercent(this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true))
-
+ var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
+ if (Math.abs(diff) < 50 && diff !== 0) {
+ diff = diff * this.getProp('sensitivity') / inertia
+ this.setPercent(this.percent + diff)
}
this.lastOffsetX = offsetX
@@ -138,6 +149,7 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
this.previousPercent = 50
this.percent = 50
+ this.speed = []
this.setValue(this.getProp('release'), {sync: true, send: true, dragged: true})
}
@@ -185,6 +197,8 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
var val = dir ? this.getProp('forth') : this.getProp('back')
+ this.speed.push(Math.abs(this.percent - this.previousPercent))
+
this.setValue(val, {
sync: true,
send: true,
@@ -205,13 +219,13 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
this.percent = 50
this.previousPercent = 50
} else if (
- !options.dragged ||
+ !options.dragged &&
(v !== this.getProp('forth') && v !== this.getProp('back') && (this.getProp('release') === '' && v !== this.getProp('release')))
) return
- // sensitivity = ingore value updates
+ // sensitivity = ignore value updates
var sensitivityIgnore = false
if (this.getProp('sensitivity') < 1) {
if (v != this.getProp('release')) {
@@ -224,75 +238,29 @@ module.exports = class Encoder extends StaticProperties(Knob, {angle: 360, range
}
}
+
this.value = v
this.batchDraw()
if (sensitivityIgnore) return
+ if (!options.dragged && options.widget && options.widget instanceof Encoder) {
+ this.percent = options.widget.percent
+ }
+
+ if (this.speed && this.speed.length) {
+ var s = this.speed.reduce((a,c)=>a+c) / this.speed.length
+ this.speed = []
+ this.parsersLocalScope.speed = s
+ } else {
+ this.parsersLocalScope.speed = 0
+ }
+ this.parsersLocalScope.angle = Math.abs(this.percent % 100 / 100 * 360)
+
if (options.send) this.sendValue()
if (options.sync) this.changed(options)
}
- draw() {
-
- var percent = this.percent,
- d = this.percentToAngle(percent),
- angle = 2 * Math.PI / 16,
- min = this.percentToAngle(0),
- max = this.percentToAngle(100),
- minRadius = this.minDimension / 6,
- maxRadius = this.minDimension / 2 - this.cssVars.lineWidth,
- gaugeWidth = maxRadius - minRadius,
- gaugeRadius = maxRadius - gaugeWidth / 2
-
- this.clear()
-
- if (this.minDimension < 40) {
- minRadius /= 2
- gaugeWidth = maxRadius - minRadius
- gaugeRadius = maxRadius - gaugeWidth / 2
- }
-
- // fill
- this.ctx.globalAlpha = this.cssVars.alphaFill
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
-
- if (this.cssVars.alphaFillOff) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOff
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
- this.ctx.stroke()
- }
-
- if (this.cssVars.alphaFillOn) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, d - angle, d + angle)
- this.ctx.stroke()
- }
-
- // stroke
- if (this.cssVars.lineWidth) {
-
- this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.strokeStyle = this.cssVars.colorStroke
- this.ctx.lineWidth = this.cssVars.lineWidth
-
- if (this.minDimension > 40) {
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, minRadius, 0, 2 * Math.PI)
- this.ctx.stroke()
- }
-
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
- this.ctx.stroke()
-
- }
-
- }
-
}
diff --git a/src/client/widgets/sliders/fader.js b/src/client/widgets/sliders/fader.mjs
similarity index 61%
rename from src/client/widgets/sliders/fader.js
rename to src/client/widgets/sliders/fader.mjs
index 67ef857f..180f6a99 100644
--- a/src/client/widgets/sliders/fader.js
+++ b/src/client/widgets/sliders/fader.mjs
@@ -1,5 +1,6 @@
-var {clip} = require('../utils'),
- Slider = require('./slider')
+import {clip} from '../utils.mjs'
+import Slider from './slider.mjs'
+import {PXSCALE, CANVAS_SCALING} from '../../globals.mjs'
class Fader extends Slider {
@@ -11,11 +12,12 @@ class Fader extends Slider {
static defaults() {
- return super.defaults(Fader).extend({
+ var defaults = super.defaults(Fader).extend({
style: {
_separator_fader_style: 'Fader style',
design: {type: 'string', value: 'default', choices: ['default', 'round', 'compact'], help: 'Design style'},
knobSize: {type: 'number', value: 'auto', help: 'Fader knob size'},
+ colorKnob: {type: 'string', value: 'auto', help: 'Fader knob color. Must be a valid css color.'},
horizontal: {type: 'boolean', value: false, help: 'Set to `true` to display the fader horizontally'},
pips: {type: 'boolean', value: false, help: 'Set to `true` to show range breakpoints (ignored if `design` is `compact`)'},
dashed: {type: 'boolean|array', value: false, help: 'Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]`'},
@@ -29,10 +31,18 @@ class Fader extends Slider {
},
class_specific: {
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'},
+ touchZone: {type: 'string', value: 'all', choices: ['all', 'knob', 'gauge'], help: [
+ 'Restrict interaction to a part of the widget:',
+ '- `all`: touching the widget anywhere will start an interaction',
+ '- `knob`: touching the knob will start an interaction',
+ '- `gauge`: touching anywhere in the knob\'s moving range will start an interaction',
+ 'This setting is ignored in containers with `traversing` set to `true`'
+ ]},
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: {type: 'boolean|string', value: false, choices: [false, true, 'script'], help: [
+ 'Set to `true` to make the knob reset to its `default` value when receiving a double tap.',
+ 'Can be an osc address, in which case the widget will just send an osc message with no value (but `preArgs` included).',
+ 'If set to "script", `onTouch` will be called with `event.type` set to `doubleTap`. '
]},
range: {type: 'object', value: {min:0,max:1}, help: [
'Defines the breakpoints of the fader\'s scale:',
@@ -42,16 +52,21 @@ class Fader extends Slider {
]},
logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale. Set to `-1` for exponential scale.'},
sensitivity: {type: 'number', value: 1, help: 'Defines the fader\'s sensitivity when `snap` is `false` '},
- steps: {type: 'string|number|array', value: '', help: [
+ steps: {type: 'number|array|string', value: '', help: [
'Restricts the widget\'s value:',
- '- `auto`: use values defined in `range`',
'- `number`: define a number of evenly spaced steps',
- '- `array`: use arbitrary values',
+ '- `array` of numbers: use arbitrary values as steps',
+ '- `auto`: use values defined in `range`'
]},
origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the fader\'s gauge'},
}
})
+ defaults.scripting.onTouch = {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is touched and released. See documentation.',]}
+ defaults.style.borderRadius= {type: 'number', value: 'auto', help: 'Border radius expressed as a number (same for all corners, applies only for compact design).'}
+
+ return defaults
+
}
constructor(options) {
@@ -61,6 +76,7 @@ class Fader extends Slider {
this.container.classList.toggle('horizontal', this.getProp('horizontal'))
this.gaugeGradient = null
+ this.shouldDrawPips = false
var dashed = this.getProp('dashed')
this.dashed = dashed ? Array.isArray(dashed) ? dashed.map(x=>parseFloat(x)) : [1, 1] : false
@@ -71,6 +87,11 @@ class Fader extends Slider {
super.draginitHandle(...arguments)
+ if (!e.traversing && !this.shouldDrag(e)) {
+ e.cancelDragEvent = true
+ return
+ }
+
this.percent = clip(this.percent,[0,100])
if (!(e.traversing || this.getProp('snap')) || e.ctrlKey) return
@@ -89,15 +110,69 @@ class Fader extends Slider {
var padding = this.gaugePadding
if (this.getProp('design') === 'compact') padding += this.cssVars.knobSize / 2
-
+ var inertia = e.fingers > 1 || e.ctrlKey ? 10 : e.inertia
this.percent = this.getProp('horizontal')?
- this.percent + ( e.movementX / (this.width - padding * 2)) * 100 / e.inertia * this.getProp('sensitivity'):
- this.percent + (-e.movementY / (this.height - padding * 2)) * 100 / e.inertia * this.getProp('sensitivity')
+ this.percent + ( e.movementX / (this.width - padding * 2)) * 100 / inertia * this.getProp('sensitivity'):
+ this.percent + (-e.movementY / (this.height - padding * 2)) * 100 / inertia * this.getProp('sensitivity')
this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
}
+ shouldDrag(e, testZone) {
+
+ var zone = testZone || this.getProp('touchZone'),
+ design = this.getProp('design'),
+ horizontal = this.getProp('horizontal'),
+ snap = this.getProp('snap')
+
+ if (zone == 'all') return true
+ if (e.type == 'wheel' && zone == 'knob') zone = 'gauge'
+ if (design == 'compact' && zone == 'gauge') return true
+
+ var x = e.offsetX,
+ y = e.offsetY,
+ percent = this.steps ? this.valueToPercent(this.value) : this.percent,
+ d = Math.round(this.percentToCoord(percent)),
+ m = horizontal ? this.height / 2 : this.width / 2,
+ knobHeight = this.cssVars.knobSize,
+ knobWidth = knobHeight * .6,
+ height = !horizontal ? this.height : this.width
+
+ if (design == 'round') knobWidth = knobHeight
+ if (design == 'compact') {
+ knobWidth = this.width
+ // knob position range depends on knob size in compact mode
+ d = d / (height - this.gaugePadding) * (height-this.gaugePadding - knobHeight)
+ }
+ if (horizontal) [knobWidth, knobHeight] = [knobHeight, knobWidth]
+
+ // add extra tolerance pixels
+ knobWidth += 2 * PXSCALE
+ knobHeight += 2 * PXSCALE
+
+ var knobX = (horizontal ? d : m) - knobWidth / 2,
+ knobY = (horizontal ? m : d) - knobHeight / 2,
+ condition
+
+ if (horizontal) {
+ if (design == 'compact') knobX += knobWidth / 2
+ condition = ((x >= knobX && x <= knobX + knobWidth) || (zone == 'gauge' || snap)) &&
+ y >= knobY && y <= knobY + knobHeight
+ } else {
+ if (design == 'compact') knobY += knobHeight / 2
+ condition = x >= knobX && x <= knobX + knobWidth &&
+ ((y >= knobY && y <= knobY + knobHeight) || (zone == 'gauge' || snap))
+ }
+
+ if (condition) {
+ return true
+ } else {
+ return false
+ }
+
+ }
+
percentToCoord(percent) {
if (this.getProp('horizontal')) {
@@ -108,18 +183,20 @@ class Fader extends Slider {
}
- resizeHandle(event) {
+ extraResizeHandle(event) {
var ratio = CANVAS_SCALING * this.scaling
- super.resizeHandle(event)
+ super.extraResizeHandle(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')) {
@@ -131,7 +208,7 @@ class Fader extends Slider {
(typeof colors === 'object' && Object.keys(colors).length > 1)
) {
- var grad = this.ctx.createLinearGradient(0, this.getProp('horizontal') ? 0 : this.height, 0, this.getProp('horizontal') ? this.width : 0)
+ var grad = this.ctx.createLinearGradient(this.gaugePadding, this.getProp('horizontal') ? this.gaugePadding : this.height - this.gaugePadding, this.gaugePadding, this.getProp('horizontal') ? this.width - this.gaugePadding : this.gaugePadding)
try {
if (Array.isArray(colors)) {
@@ -152,21 +229,20 @@ class Fader extends Slider {
}
} catch(err) {
- this.errors.gradient = err
+ this.errorProp('gradient', '', err)
}
}
}
-
}
cacheCanvasStyle(style) {
super.cacheCanvasStyle(style)
- if (this.getProp('pips') && this.getProp('design') !== 'compact') this.drawPips()
+ if (this.getProp('pips') && this.getProp('design') !== 'compact') this.shouldDrawPips = true
}
@@ -176,7 +252,7 @@ class Fader extends Slider {
var width = this.getProp('horizontal') ? this.height : this.width,
height = !this.getProp('horizontal') ? this.height : this.width
- var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
+ var percent = this.steps ? this.valueToPercent(this.value) : this.percent,
d = Math.round(this.percentToCoord(percent)),
o = Math.round(this.percentToCoord(this.valueToPercent(this.originValue))),
m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
@@ -231,33 +307,76 @@ class Fader extends Slider {
if (compact) {
+ // flat knob
+
+ this.ctx.globalAlpha = this.cssVars.alphaKnob || 1
+ this.ctx.fillStyle = this.cssVars.colorKnob
+
+ this.ctx.beginPath()
+ // adjust position to keep knob within gauge boundaries
+ d = (d - this.gaugePadding ) / (height - this.gaugePadding * 2 ) * (height - this.gaugePadding * 2 - knobHeight) + this.gaugePadding
+ this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
+ this.ctx.fill()
+
+ let x, y, w, h,
+ rad = PXSCALE * this.cssVars.borderRadius
+
+ // border radius: clip gauge & knob
+ if (rad > 0) {
+ rad = Math.min(Math.min(height, width) / 2, rad)
+ x = this.gaugePadding
+ y = this.gaugePadding
+ w = width - this.gaugePadding * 2
+ h = height - this.gaugePadding * 2
+ this.ctx.beginPath()
+ this.ctx.moveTo(x + rad, y)
+ this.ctx.arcTo(x + w, y, x + w, y + h, rad)
+ this.ctx.arcTo(x + w, y + h, x, y + h, rad)
+ this.ctx.arcTo(x, y + h, x, y, rad)
+ this.ctx.arcTo(x, y, x + w, y, rad)
+ this.ctx.closePath()
+
+ var tmpOp = this.ctx.globalCompositeOperation
+ this.ctx.globalCompositeOperation = 'destination-in'
+ this.ctx.fillStyle = '#ffffff'
+ this.ctx.globalAlpha = 1
+ this.ctx.fill()
+ this.ctx.globalCompositeOperation = tmpOp
+ }
+
// stroke
if (this.cssVars.lineWidth) {
this.ctx.globalAlpha = this.cssVars.alphaStroke
this.ctx.strokeStyle = this.cssVars.colorStroke
+ // draw stroke
+ x = 0.5 * this.cssVars.lineWidth
+ y = 0.5 * this.cssVars.lineWidth
+ w = width - this.cssVars.lineWidth
+ h = height - this.cssVars.lineWidth
+
this.ctx.beginPath()
- this.ctx.moveTo(0, 0)
- this.ctx.lineTo(width, 0)
- this.ctx.lineTo(width, height)
- this.ctx.lineTo(0, height)
+ if (rad > 0) {
+ this.ctx.moveTo(x + rad, y)
+ this.ctx.arcTo(x + w, y, x + w, y + h, rad)
+ this.ctx.arcTo(x + w, y + h, x, y + h, rad)
+ this.ctx.arcTo(x, y + h, x, y, rad)
+ this.ctx.arcTo(x, y, x + w, y, rad)
+ } else {
+ this.ctx.moveTo(x, y)
+ this.ctx.lineTo(x + w, y)
+ this.ctx.lineTo(x + w, y + h)
+ this.ctx.lineTo(x, y + h)
+ }
+
this.ctx.closePath()
- this.ctx.lineWidth = 2 * this.cssVars.lineWidth
+ this.ctx.lineWidth = this.cssVars.lineWidth
this.ctx.stroke()
}
- // flat knob
-
- this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorFill
-
- this.ctx.beginPath()
- d = d / (height - this.gaugePadding) * (height-this.gaugePadding - knobHeight)
- this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
- this.ctx.fill()
this.clearRect = [0, 0, width, height]
@@ -276,7 +395,7 @@ class Fader extends Slider {
this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.strokeStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.lineWidth = PXSCALE
@@ -286,18 +405,19 @@ class Fader extends Slider {
}
this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorStroke
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.rect(m - knobWidth / 6, d, knobWidth / 3, PXSCALE)
this.ctx.fill()
- this.clearRect = [m - knobWidth / 2 - PXSCALE, this.gaugePadding - knobHeight / 2 - PXSCALE, knobWidth + 2 * PXSCALE, height - 2 * this.gaugePadding + knobHeight + 2 * PXSCALE]
+ var clearWidth = Math.max(knobWidth, this.cssVars.lineWidth)
+ this.clearRect = [m - clearWidth / 2 - PXSCALE, this.gaugePadding - knobHeight / 2 - PXSCALE, clearWidth + 2 * PXSCALE, height - 2 * this.gaugePadding + knobHeight + 2 * PXSCALE]
} else {
this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.arc(m, d, knobHeight / 6, 0, 2 * Math.PI)
@@ -306,7 +426,7 @@ class Fader extends Slider {
if (this.cssVars.alphaStroke) {
this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.arc(m, d, knobHeight / 2, 0, 2 * Math.PI)
@@ -317,7 +437,12 @@ class Fader extends Slider {
}
- if (this.getProp('pips') && !compact) {
+ if (this.shouldDrawPips) {
+ this.drawPips()
+ this.shouldDrawPips = false
+ }
+
+ if (this.pips && this.pips.width && this.pips.height) {
this.ctx.globalAlpha = 1
this.ctx.drawImage(this.pips, 0, 0)
if (!compact) this.clearRect = [this.clearRect, [m + knobWidth / 2, 0, 12 * PXSCALE + this.pipsTextSize, height]]
@@ -328,7 +453,7 @@ class Fader extends Slider {
drawPips() {
- this.pips = this.canvas.cloneNode()
+ this.pips = this.pips || this.canvas.cloneNode()
this.pips.width = this.getProp('horizontal') ? this.height : this.width
this.pips.height = !this.getProp('horizontal') ? this.height : this.width
this.pipsTextSize = this.fontSize
@@ -409,11 +534,22 @@ class Fader extends Slider {
}
+ onRemove() {
+
+ if (this.pips) {
+ this.pips.width = 0
+ this.pips.height = 0
+ }
+ super.onRemove()
+
+ }
+
}
Fader.cssVariables = Fader.prototype.constructor.cssVariables.concat(
- {js: 'knobSize', css: '--knob-size', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE}
+ {js: 'knobSize', css: '--knob-size', toCss: x=>parseFloat(x) + 'rem', toJs: x=>parseFloat(x) * PXSCALE},
+ {js: 'colorKnob', css: '--color-knob'},
)
-module.exports = Fader
+export default Fader
diff --git a/src/client/widgets/sliders/knob.js b/src/client/widgets/sliders/knob.js
deleted file mode 100644
index 7b9e40f1..00000000
--- a/src/client/widgets/sliders/knob.js
+++ /dev/null
@@ -1,373 +0,0 @@
-var {clip} = require('../utils'),
- Slider = require('./slider')
-
-module.exports = class Knob extends Slider {
-
- static description() {
-
- return 'Rotative knob slider.'
-
- }
-
- static defaults() {
-
- return super.defaults(Knob).extend({
- style: {
- _separator_knob_style: 'Knob style',
- design: {type: 'string', value: 'default', choices: ['default', 'solid', 'line'], help: [
- 'Design style',
- 'Note: "solid" design uses "colorStroke" for the central knob color.'
- ]},
- pips: {type: 'boolean', value: false, help: 'Set to `true` to show the scale\'s breakpoints'},
- dashed: {type: 'boolean|array', value: false, help: 'Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]`'},
- angle: {type: 'number', value: 270, help: 'Defines the angle\'s width of the knob, in degrees'},
- },
- class_specific: {
- mode: {type: 'string', value: 'vertical', choices: ['vertical', 'circular', 'snap'], help: [
- '- `circular`: relative move in circular motion',
- '- `snap`: snap to touch position and move in vertical motion',
- '- `vertical`: relative move in vertical motion',
- ]},
- spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
- 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 (`/ `)'
- ]},
- range: {type: 'object', value: {min:0,max:1}, help: [
- 'Defines the breakpoints of the fader\'s scale:',
- '- keys can be percentages and/or `min` / `max`',
- '- values can be `number` or `object` if a custom label is needed',
- 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
- ]},
- logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale. Set to `-1` for exponential scale.'},
- sensitivity: {type: 'number', value: 1, help: 'Defines the knob\'s sensitivity when `mode` is not `snap` '},
- steps: {type: 'string|number|array', value: '', help: [
- 'Restricts the widget\'s value:',
- '- `auto`: use values defined in `range`',
- '- `number`: define a number of evenly spaced steps',
- '- `array`: use arbitrary values',
- ]},
- origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the knob\'s gauge'},
- }
- })
-
- }
-
- constructor(options) {
-
- super(options)
-
- this.lastOffsetX = 0
- this.lastOffsetY = 0
- this.minDimension = 0
-
- this.maxAngle = this.getProp('angle')
-
- if (this.getProp('pips')) {
-
- this.widget.classList.add('has-pips')
- this.pipTexts = {}
- for (var k in this.rangeKeys) {
- this.pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
- }
-
- }
-
- }
-
- draginitHandle(e) {
-
- this.percent = clip(this.percent,[0,100])
-
- this.lastOffsetX = e.offsetX
- this.lastOffsetY = e.offsetY
-
- if (this.getProp('mode') === 'snap') {
-
- this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
-
- this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
-
- }
-
-
- }
-
- dragHandle(e) {
-
- if ((this.getProp('mode') === 'vertical' && !e.traversing) || e.ctrlKey) {
- // vertical
- this.percent = -100 * (e.movementY / e.inertia * this.getProp('sensitivity')) / this.minDimension + this.percent
-
- } else {
- // snap or circular
- var offsetX = this.lastOffsetX + e.movementX,
- offsetY = this.lastOffsetY + e.movementY
-
- if (e.traversing || this.getProp('mode') === 'circular') {
- // circular
- var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
- if (Math.abs(diff) < 50 && diff !== 0) this.percent += diff * 360 / this.maxAngle
-
- } else {
-
- // snap
- this.percent = this.angleToPercent(this.coordsToAngle(offsetX, offsetY))
-
- }
-
- this.lastOffsetX = offsetX
- this.lastOffsetY = offsetY
-
- }
-
-
- // this.percent = clip(this.percent,[0,100])
-
- this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
-
- }
-
- coordsToAngle(x,y) {
-
- var xToCenter = x - this.width /2,
- yToCenter = y - this.height / 2,
- angle = Math.atan2(-yToCenter, -xToCenter) * 180 / Math.PI + 90
-
- return angle<0?360+angle:angle
-
- }
-
- angleToPercent(angle, ignoreMaxAngle=false) {
-
- return ignoreMaxAngle ?
- clip(angle, [0, 360]) / 360 * 100
- : 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)
-
- }
-
- draw() {
-
- var percent = this.getProp('steps') ? this.valueToPercent(this.value) : this.percent,
- o = this.percentToAngle(this.valueToPercent(this.originValue)),
- d = this.percentToAngle(percent),
- min = this.percentToAngle(0),
- max = this.percentToAngle(100),
- dashed = this.getProp('dashed'),
- pips = this.getProp('pips'),
- minRadius = this.minDimension / 6 - (pips ? this.fontSize * 0.75 : 0) - this.cssVars.lineWidth / 2,
- maxRadius = this.minDimension / 2 - (pips ? this.fontSize * 2 : 0) - this.cssVars.lineWidth / 2
-
- if (dashed) dashed = Array.isArray(dashed) ? dashed.map(x=>parseFloat(x)) : [1.5, 1.5]
-
- var gaugeWidth = maxRadius - minRadius,
- gaugeRadius = maxRadius - gaugeWidth / 2
-
- this.clear()
-
- if (this.getProp('design') === 'default') {
-
- if (this.minDimension < 40) {
- minRadius /= 2
- gaugeWidth = maxRadius - minRadius
- gaugeRadius = maxRadius - gaugeWidth / 2
- }
-
- // fill
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
-
- if (dashed) this.ctx.setLineDash(dashed)
-
- if (this.cssVars.alphaFillOff) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOff
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
- this.ctx.stroke()
- }
-
- if (this.cssVars.alphaFillOn) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, o, d, o > d)
- this.ctx.stroke()
- }
-
- if (dashed) this.ctx.setLineDash([])
-
-
- // stroke
- if (this.cssVars.lineWidth) {
- this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.strokeStyle = this.cssVars.colorStroke
- this.ctx.lineWidth = this.cssVars.lineWidth
-
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
- this.ctx.stroke()
- }
-
-
- // knob
-
- this.ctx.globalAlpha = 1
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
-
- let r1 = minRadius + this.gaugePadding,
- r2 = maxRadius - this.gaugePadding,
- a = 2 * Math.PI - d
-
- this.ctx.beginPath()
- this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
- this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
- this.ctx.stroke()
-
- } else if (this.getProp('design') === 'solid') {
-
- // center
-
- this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.fillStyle = this.cssVars.colorStroke
-
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius / 1.25, 0, 2 * Math.PI)
- this.ctx.fill()
-
- // fill
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = this.cssVars.lineWidth
-
- if (dashed) this.ctx.setLineDash(dashed)
-
- if (this.cssVars.alphaFillOff) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOff
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
- this.ctx.stroke()
- }
-
- if (this.cssVars.alphaFillOn) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
- this.ctx.stroke()
- }
-
- if (dashed) this.ctx.setLineDash([])
-
- // knob
-
- this.ctx.globalAlpha = 1
- this.ctx.strokeStyle = this.cssVars.colorBg
- this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
-
- let r1 = minRadius,
- r2 = maxRadius / 1.25 + PXSCALE ,
- a = 2 * Math.PI - d
-
- this.ctx.beginPath()
- this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
- this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
- this.ctx.stroke()
-
-
-
- } else {
-
- // fill
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = this.cssVars.lineWidth
-
- if (dashed) this.ctx.setLineDash(dashed)
-
- if (this.cssVars.alphaFillOff) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOff
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
- this.ctx.stroke()
- }
-
- if (this.cssVars.alphaFillOn) {
- this.ctx.globalAlpha = this.cssVars.alphaFillOn
- this.ctx.beginPath()
- this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
- this.ctx.stroke()
- }
-
- if (dashed) this.ctx.setLineDash([])
-
- // knob
-
- this.ctx.globalAlpha = 1
- this.ctx.strokeStyle = this.cssVars.colorFill
- this.ctx.lineWidth = this.cssVars.lineWidth
-
- let r1 = minRadius * 1.5,
- r2 = maxRadius + this.cssVars.lineWidth / 2 - 0.5 * PXSCALE,
- a = 2 * Math.PI - d
-
- this.ctx.beginPath()
- this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
- this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
- this.ctx.stroke()
-
- }
-
-
- // pips
-
- if (pips) {
-
- this.ctx.lineWidth = this.fontSize / 11 * 1.5
- this.ctx.strokeStyle = this.cssVars.colorStroke
- this.ctx.globalAlpha = this.cssVars.alphaPips
-
- for (var pip of this.rangeKeys) {
-
- let r1 = maxRadius + this.cssVars.lineWidth / 2 + 2 * PXSCALE,
- r2 = r1 + 4 * PXSCALE,
- a = 2 * Math.PI - this.percentToAngle(pip)
-
-
- this.ctx.beginPath()
- this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
- this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
- this.ctx.stroke()
-
- }
- var radius = maxRadius + (this.fontSize + this.cssVars.lineWidth / 2 + 2 * PXSCALE)
- this.ctx.fillStyle = this.cssVars.colorText
- this.ctx.globalAlpha = this.cssVars.alphaPipsText
- for (var p in this.pipTexts) {
- if (this.pipTexts[p] === undefined || (this.maxAngle === 360 && p === '100')) continue
- var angle = this.percentToAngle(p),
- size = this.ctx.measureText(this.pipTexts[p]),
- x = this.width / 2 + radius * Math.cos(angle) - size.width / 2,
- y = this.height / 2 + radius * Math.sin(angle)
- this.ctx.fillText(this.pipTexts[p], x, y)
- }
-
- }
-
- }
-
-}
diff --git a/src/client/widgets/sliders/knob.mjs b/src/client/widgets/sliders/knob.mjs
new file mode 100644
index 00000000..a364e1ff
--- /dev/null
+++ b/src/client/widgets/sliders/knob.mjs
@@ -0,0 +1,435 @@
+import {clip} from '../utils.mjs'
+import Slider from './slider.mjs'
+import {PXSCALE} from '../../globals.mjs'
+
+class Knob extends Slider {
+
+ static description() {
+
+ return 'Rotative knob slider.'
+
+ }
+
+ static defaults() {
+
+ var defaults = super.defaults(Knob).extend({
+ style: {
+ _separator_knob_style: 'Knob style',
+ design: {type: 'string', value: 'default', choices: ['default', 'solid', 'line', 'encoder'], help: [
+ 'Design style',
+ 'Note: "solid" design uses "colorStroke" for the central knob color.'
+ ]},
+ colorKnob: {type: 'string', value: 'auto', help: 'Knob color. Must be a valid css color.'},
+ pips: {type: 'boolean', value: false, help: 'Set to `true` to show the scale\'s breakpoints'},
+ dashed: {type: 'boolean|array', value: false, help: 'Set to `true` to display a dashed gauge. Can be set as an `array` of two numbers : `[dash_size, gap_size]`'},
+ angle: {type: 'number', value: 270, help: 'Defines the angle\'s width of the knob, in degrees'},
+ },
+ class_specific: {
+ mode: {type: 'string', value: 'vertical', choices: ['vertical', 'horizontal', 'circular', 'snap', 'snap-alt'], help: [
+ '- `vertical`: relative move in vertical motion',
+ '- `horizontal`: relative move in horizontal motion',
+ '- `circular`: relative move in circular motion',
+ '- `snap`: snap to touch position',
+ '- `snap-alt`: alternative snap mode that allow jumping from `range.min` to `range.max`. `sensitivity` is ignored with this mode.',
+ ]},
+ spring: {type: 'boolean', value: false, help: 'When set to `true`, the widget will go back to its `default` value when released'},
+ doubleTap: {type: 'boolean|string', value: false, choices: [false, true, 'script'], help: [
+ 'Set to `true` to make the knob reset to its `default` value when receiving a double tap.',
+ 'Can be an osc address, in which case the widget will just send an osc message with no value (but `preArgs` included).',
+ 'If set to "script", `onTouch` will be called with `event.type` set to `doubleTap`. '
+ ]},
+ range: {type: 'object', value: {min:0,max:1}, help: [
+ 'Defines the breakpoints of the fader\'s scale:',
+ '- keys can be percentages and/or `min` / `max`',
+ '- values can be `number` or `object` if a custom label is needed',
+ 'Example: (`{min:{"-inf": 0}, "50%": 0.25, max: {"+inf": 1}}`)'
+ ]},
+ logScale: {type: 'boolean|number', value: false, help: 'Set to `true` to use logarithmic scale. Set to `-1` for exponential scale.'},
+ sensitivity: {type: 'number', value: 1, help: 'Defines the knob\'s sensitivity when `mode` is not `snap` '},
+ steps: {type: 'string|number|array', value: '', help: [
+ 'Restricts the widget\'s value:',
+ '- `number`: define a number of evenly spaced steps',
+ '- `array` of numbers: use arbitrary values as steps',
+ '- `auto`: use values defined in `range`'
+ ]},
+ origin: {type: 'number', value: 'auto', help: 'Defines the starting point\'s value of the knob\'s gauge'},
+ }
+ })
+
+ defaults.scripting.onTouch = {type: 'script', value: '', editor:'javascript', help: ['Script executed when the widget is touched and released. See documentation.',]}
+
+ return defaults
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.lastOffsetX = 0
+ this.lastOffsetY = 0
+ this.minDimension = 0
+
+ this.maxAngle = this.getProp('angle')
+
+ if (this.getProp('pips')) {
+
+ this.widget.classList.add('has-pips')
+ this.pipTexts = {}
+ for (var k in this.rangeKeys) {
+ this.pipTexts[this.rangeKeys[k]]=this.rangeLabels[k]
+ }
+
+ }
+
+ }
+
+ draginitHandle(e) {
+
+ this.percent = clip(this.percent,[0,100])
+
+ this.lastOffsetX = e.offsetX
+ this.lastOffsetY = e.offsetY
+
+ if (this.getProp('mode') === 'snap' || this.getProp('mode') === 'snap-alt') {
+
+ this.percent = this.angleToPercent(this.coordsToAngle(e.offsetX, e.offsetY))
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+
+ }
+
+ dragHandle(e) {
+
+ var inertia = e.fingers > 1 || e.ctrlKey ? 10 : e.inertia
+
+ if ((this.getProp('mode') === 'vertical' && !e.traversing)) {
+ // vertical
+ this.percent = -100 * (e.movementY / inertia * this.getProp('sensitivity')) / this.minDimension + this.percent
+
+ } else if ((this.getProp('mode') === 'horizontal' && !e.traversing)) {
+ // horizontal
+ this.percent = 100 * (e.movementX / inertia * this.getProp('sensitivity')) / this.minDimension + this.percent
+
+ } else {
+ // snap or circular
+ var offsetX = this.lastOffsetX + e.movementX,
+ offsetY = this.lastOffsetY + e.movementY
+
+ if (this.getProp('mode') === 'snap-alt'){
+ this.percent = this.angleToPercent(this.coordsToAngle(offsetX, offsetY))
+ } else {
+ var diff = this.angleToPercent(this.coordsToAngle(offsetX, offsetY), true) - this.angleToPercent(this.coordsToAngle(this.lastOffsetX, this.lastOffsetY), true)
+ if (Math.abs(diff) < 50 && diff !== 0) this.percent += (diff * 360 / this.maxAngle) * this.getProp('sensitivity') / inertia
+ }
+
+ this.lastOffsetX = offsetX
+ this.lastOffsetY = offsetY
+
+ }
+
+
+ // this.percent = clip(this.percent,[0,100])
+
+ this.setValue(this.percentToValue(this.percent), {send:true,sync:true,dragged:true})
+
+ }
+
+ coordsToAngle(x,y) {
+
+ var xToCenter = x - this.width /2,
+ yToCenter = y - this.height / 2,
+ angle = Math.atan2(-yToCenter, -xToCenter) * 180 / Math.PI + 90
+
+ return angle<0?360+angle:angle
+
+ }
+
+ angleToPercent(angle, ignoreMaxAngle=false) {
+
+ return ignoreMaxAngle ?
+ clip(angle, [0, 360]) / 360 * 100
+ : 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
+
+ }
+
+ extraResizeHandle(event) {
+
+ super.extraResizeHandle(event)
+
+ this.minDimension = Math.min(this.width, this.height)
+
+ }
+
+ draw() {
+
+ var percent = this.steps ? this.valueToPercent(this.value) : this.percent,
+ o = this.percentToAngle(this.valueToPercent(this.originValue)),
+ d = this.percentToAngle(percent),
+ min = this.percentToAngle(0),
+ max = this.percentToAngle(100),
+ dashed = this.getProp('dashed'),
+ pips = this.getProp('pips'),
+ minRadius = this.minDimension / 6 - (pips ? this.fontSize * 0.75 : 0) - this.cssVars.lineWidth / 2,
+ maxRadius = this.minDimension / 2 - (pips ? this.fontSize * 2 : 0) - this.cssVars.lineWidth / 2
+
+ if (dashed) dashed = Array.isArray(dashed) ? dashed.map(x=>parseFloat(x)) : [1.5, 1.5]
+
+ var gaugeWidth = maxRadius - minRadius,
+ gaugeRadius = maxRadius - gaugeWidth / 2
+
+ this.clear()
+
+ switch (this.getProp('design')) {
+ case 'default':
+ {
+ if (this.minDimension < 40) {
+ minRadius /= 2
+ gaugeWidth = maxRadius - minRadius
+ gaugeRadius = maxRadius - gaugeWidth / 2
+ }
+
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+ }
+
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorKnob
+ this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
+
+ let r1 = minRadius + this.gaugePadding,
+ r2 = maxRadius - this.gaugePadding,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+ break
+ }
+ case 'solid':
+ {
+ // center
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.fillStyle = this.cssVars.colorKnob
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius / 1.25, 0, 2 * Math.PI)
+ this.ctx.fill()
+
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorBg
+ this.ctx.lineWidth = this.cssVars.lineWidth + .5 * PXSCALE
+
+ let r1 = minRadius,
+ r2 = maxRadius / 1.25 + PXSCALE ,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+ break
+ }
+ case 'line':
+ {
+ // fill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (dashed) this.ctx.setLineDash(dashed)
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, min, max)
+ this.ctx.stroke()
+ }
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, o, d, o > d)
+ this.ctx.stroke()
+ }
+
+ if (dashed) this.ctx.setLineDash([])
+
+ // knob
+
+ this.ctx.globalAlpha = 1
+ this.ctx.strokeStyle = this.cssVars.colorKnob
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ let r1 = minRadius * 1.5,
+ r2 = maxRadius + this.cssVars.lineWidth / 2 - 0.5 * PXSCALE,
+ a = 2 * Math.PI - d
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+ break
+ }
+ case 'encoder':
+ {
+ let angle = 2 * Math.PI / 16
+
+ // fill
+ this.ctx.globalAlpha = this.cssVars.alphaFill
+ this.ctx.strokeStyle = this.cssVars.colorFill
+ this.ctx.lineWidth = gaugeWidth - this.gaugePadding * 2
+
+ if (this.cssVars.alphaFillOff) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, min - angle, max + angle)
+ this.ctx.stroke()
+ }
+
+ if (this.cssVars.alphaFillOn) {
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, gaugeRadius, d - angle, d + angle)
+ this.ctx.stroke()
+ }
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.lineWidth = this.cssVars.lineWidth
+
+ if (this.minDimension > 40) {
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, minRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+ }
+
+ this.ctx.beginPath()
+ this.ctx.arc(this.width / 2, this.height / 2, maxRadius, 0, 2 * Math.PI)
+ this.ctx.stroke()
+
+ }
+
+ break
+ }
+ }
+
+
+ // pips
+
+ if (pips) {
+
+ this.ctx.lineWidth = this.fontSize / 11 * 1.5
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.globalAlpha = this.cssVars.alphaPips
+
+ for (var pip of this.rangeKeys) {
+
+ let r1 = maxRadius + this.cssVars.lineWidth / 2 + 2 * PXSCALE,
+ r2 = r1 + 4 * PXSCALE,
+ a = 2 * Math.PI - this.percentToAngle(pip)
+
+
+ this.ctx.beginPath()
+ this.ctx.moveTo(r1 * Math.cos(a) + this.width / 2, this.height / 2 - r1 * Math.sin(a))
+ this.ctx.lineTo(r2 * Math.cos(a) + this.width / 2, this.height / 2 - r2 * Math.sin(a))
+ this.ctx.stroke()
+
+ }
+ var radius = maxRadius + (this.fontSize + this.cssVars.lineWidth / 2 + 2 * PXSCALE)
+ this.ctx.fillStyle = this.cssVars.colorText
+ this.ctx.globalAlpha = this.cssVars.alphaPipsText
+ for (var p in this.pipTexts) {
+ if (this.pipTexts[p] === undefined || (this.maxAngle === 360 && p === '100')) continue
+ let angle = this.percentToAngle(p),
+ size = this.ctx.measureText(this.pipTexts[p]),
+ x = this.width / 2 + radius * Math.cos(angle) - size.width / 2,
+ y = this.height / 2 + radius * Math.sin(angle)
+ this.ctx.fillText(this.pipTexts[p], x, y)
+ }
+
+ }
+
+ }
+
+}
+
+Knob.cssVariables = Knob.prototype.constructor.cssVariables.concat(
+ {js: 'colorKnob', css: '--color-knob'}
+)
+
+export default Knob
diff --git a/src/client/widgets/sliders/range.js b/src/client/widgets/sliders/range.mjs
similarity index 88%
rename from src/client/widgets/sliders/range.js
rename to src/client/widgets/sliders/range.mjs
index 4cb6608d..55f5097c 100644
--- a/src/client/widgets/sliders/range.js
+++ b/src/client/widgets/sliders/range.mjs
@@ -1,6 +1,7 @@
-var {clip} = require('../utils'),
- Fader = require('./fader'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import {clip} from '../utils.mjs'
+import Fader from './fader'
+import {PXSCALE} from '../../globals.mjs'
var faderDefaults = Fader.defaults()._props()
@@ -45,10 +46,12 @@ class Range extends Fader {
options.multitouch = true
- super({...options, html: html`
+ super({...options, value: [], html: html`
`})
+ this.preventChildrenTouchState = true
+
this.faders = [
new SubFader({props:{
...faderDefaults,
@@ -67,7 +70,7 @@ class Range extends Fader {
]
- this.on('change',(e)=>{
+ this.on('value-changed',(e)=>{
if (e.widget == this) return
@@ -90,9 +93,9 @@ class Range extends Fader {
}
- resizeHandle(event){
+ extraResizeHandle(event){
- super.resizeHandle(event)
+ super.extraResizeHandle(event)
for (var f of this.faders) {
f.width = this.width
@@ -138,6 +141,8 @@ class Range extends Fader {
if (!id) return
+ this.trigger('touch', {stopPropagation: true, touch: [parseInt(id), 1]})
+
for (var f of this.faders) {
f.percent = clip(f.percent,[
f.valueToPercent(f.rangeValsMin),
@@ -148,6 +153,7 @@ class Range extends Fader {
e.stopPropagation = true
this.faders[id].trigger('draginit', e)
+ this.faders[id].touched = 1
}
@@ -157,7 +163,7 @@ class Range extends Fader {
if (!i) return
- this.trigger('touch', {stopPropagation: true, touch: [parseInt(i), 1]})
+ e.fingers = 1 // cancel multifinger inertia
if (e.shiftKey) {
this.faders[0].trigger('drag', e)
@@ -175,6 +181,7 @@ class Range extends Fader {
if (!i) return
e.stopPropagation = true
+ this.faders[i].touched = 0
this.faders[i].trigger('dragend', e)
@@ -192,7 +199,7 @@ class Range extends Fader {
this.faders[0].rangeValsMax = v[1]
this.faders[1].rangeValsMin = v[0]
- if (!options.dragged) {
+ if (!options.dragged || options.fromScript) {
var opt = {
...options,
send: false,
@@ -293,17 +300,16 @@ class Range extends Fader {
// flat knob
this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorFill
- var compactAdjust = 1 / (height - this.gaugePadding) * (height-this.gaugePadding - knobHeight)
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
- d *= compactAdjust
+ d = (d - this.gaugePadding ) / (height - this.gaugePadding * 2 ) * (height - this.gaugePadding * 2 - knobHeight) + this.gaugePadding
this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
this.ctx.fill()
// extra knob
this.ctx.beginPath()
- d2 *= compactAdjust
+ d2 = (d2 - this.gaugePadding ) / (height - this.gaugePadding * 2 ) * (height - this.gaugePadding * 2 - knobHeight) + this.gaugePadding
this.ctx.rect(this.gaugePadding, d2, width - this.gaugePadding * 2, knobHeight)
this.ctx.fill()
@@ -325,7 +331,7 @@ class Range extends Fader {
this.ctx.fill()
this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.strokeStyle = this.cssVars.colorStroke
+ this.ctx.strokeStyle = this.cssVars.colorKnob
this.ctx.lineWidth = PXSCALE
this.ctx.beginPath()
@@ -335,7 +341,7 @@ class Range extends Fader {
}
this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorWidget
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.rect(m - knobWidth / 6, _d, knobWidth / 3, PXSCALE)
@@ -348,7 +354,7 @@ class Range extends Fader {
} else {
this.ctx.globalAlpha = 1
- this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.arc(m, d, knobHeight / 6, 0, 2 * Math.PI)
@@ -362,7 +368,7 @@ class Range extends Fader {
if (this.cssVars.alphaStroke) {
this.ctx.globalAlpha = this.cssVars.alphaStroke
- this.ctx.fillStyle = this.cssVars.colorFill
+ this.ctx.fillStyle = this.cssVars.colorKnob
this.ctx.beginPath()
this.ctx.arc(m, d, knobHeight / 2, 0, 2 * Math.PI)
@@ -378,7 +384,12 @@ class Range extends Fader {
}
- if (this.getProp('pips')) {
+ if (this.shouldDrawPips) {
+ this.drawPips()
+ this.shouldDrawPips = false
+ }
+
+ if (this.pips && this.pips.width && this.pips.height) {
this.ctx.globalAlpha = 1
this.ctx.drawImage(this.pips, 0, 0)
if (!compact) this.clearRect = [this.clearRect, [m + knobWidth / 2, 0, 12 * PXSCALE + this.pipsTextSize, height]]
@@ -409,4 +420,4 @@ class Range extends Fader {
}
-module.exports = Range
+export default Range
diff --git a/src/client/widgets/sliders/scrollbar.mjs b/src/client/widgets/sliders/scrollbar.mjs
new file mode 100644
index 00000000..e3dafd9f
--- /dev/null
+++ b/src/client/widgets/sliders/scrollbar.mjs
@@ -0,0 +1,350 @@
+import fastdom from 'fastdom'
+import Fader from './fader.mjs'
+import StaticProperties from '../mixins/static_properties.mjs'
+import {clip} from '../utils.mjs'
+import widgetManager from '../../managers/widgets.mjs'
+import {PXSCALE} from '../../globals.mjs'
+
+export default class Scrollbar extends StaticProperties(Fader, {
+ range: {min: 0, max: 1},
+ touchZone: 'all',
+ snap: false,
+ design: 'compact',
+ sensitivity: 1
+}) {
+
+ static defaults() {
+
+ return super.defaults().extend({
+ style: {
+ _separator_fader_style: 'Scrollbar style',
+ design: null,
+ knobSize: null,
+ pips: null,
+ },
+ class_specific: {
+ snap: null,
+ touchZone: null,
+ spring: null,
+ doubleTap: null,
+ range: null,
+ logScale: null,
+ steps: null,
+ origin: null,
+ sensitivity: null,
+ widgetId: {type: 'string', value: '', help: '`id` of the container widget to control'},
+ }
+ })
+
+ }
+
+ constructor(options) {
+
+ super(options)
+
+ this.scrollTarget = null
+ this.targetRank = null
+ this.thumbSize = 1
+
+ if (!this.getProp('horizontal')) {
+ // invert vertical fader
+ this.rangeVals[0] = 1
+ this.rangeVals[1] = 0
+ this.setValue(this.getSpringValue())
+ }
+
+
+ widgetManager.on('widget-created', (e)=>{
+
+ // if in a non-scoped context we don't watch for a closer target once we have one
+ if (!this.scopes.length && this.scrollTarget) return
+
+ var {id, widget} = e
+ if (id.includes(this.getProp('widgetId')) && widget.getProp('scroll')) {
+
+ this.getScrollTarget()
+ }
+
+ }, {context: this})
+
+ this.getScrollTarget()
+
+ }
+
+ getScrollTarget() {
+
+ var scopes = this.scopes.length ? this.scopes : [''],
+ target = null,
+ rank = 0
+
+ for (var scope of scopes) {
+ var widgets = widgetManager.getWidgetById(this.getProp('widgetId'), scope)
+ .filter(w=>w.getProp('scroll'))
+ target = widgets[0]
+
+ if (!target) {
+ rank++
+ continue
+ }
+
+ if (rank < this.targetRank || this.targetRank == null) {
+ this.unbindTarget()
+ this.bindTarget(target, rank)
+ }
+
+ return
+
+ }
+
+ }
+
+ draginitHandle(e) {
+
+ // super.draginitHandle(...arguments)
+
+ if (!e.traversing && !this.shouldDrag(e)) {
+ e.cancelDragEvent = true
+ return
+ }
+
+ this.percent = clip(this.percent,[0,100])
+
+ // snap when not touching the knob zone
+ if (this.shouldDrag(e, 'knob')) return
+
+ this.percent = this.getProp('horizontal')?
+ (e.offsetX - this.gaugePadding) / (this.width - this.gaugePadding * 2) * 100:
+ (this.height - e.offsetY - this.gaugePadding) / (this.height - this.gaugePadding * 2) * 100
+
+ this.setValue(this.percentToValue(this.percent), {send: true, sync: true, dragged: true})
+
+ }
+
+
+ mousewheelHandle(e) {
+
+ e.preventDefault()
+ e.stopPropagation()
+
+ if (!this.scrollTarget) return
+
+ var increment
+ if (this.getProp('horizontal')) {
+ increment = e.deltaY / this.scrollTarget.scrollWidth * 100
+ } else {
+ increment = -e.deltaY / this.scrollTarget.scrollHeight * 100
+ }
+
+ this.percent = clip(this.percent + increment, [0,100])
+ this.setValue(this.percentToValue(this.percent), {sync: true, send: true, dragged: true})
+
+ }
+
+ cacheCanvasStyle(style){
+
+ super.cacheCanvasStyle(style)
+
+ var size = this.getProp('horizontal') ? this.width : this.height
+ this.cssVars.knobSize = Math.max(this.thumbSize * size, 30)
+ this.cssVars.alphaKnob = 0.25
+
+ }
+
+
+ unbindTarget() {
+
+ if (!this.scrollTarget) return
+
+ this.scrollTarget.off(undefined, undefined, this)
+
+ this.scrollTarget = null
+ this.targetRank = null
+ }
+
+ bindTarget(target, rank) {
+
+ if (!target) return
+
+ this.scrollTarget = target
+ this.targetRank = rank
+
+ this.scrollTarget.on('widget-removed', (e)=>{
+ if (this.scrollTarget === e.widget) {
+ this.unbindTarget()
+ }
+ }, {context: this})
+
+ fastdom.measure(()=>{
+ if (!this.scrollTarget) return
+ this.scrollTarget.on('scroll', this.targetScroll.bind(this))
+ this.scrollTarget.on('resize', ()=>{
+ if (this.scrollTarget) {
+ this.scrollTarget.trigger('scroll', {})
+ this.targetScroll({}, true)
+ }
+ }, {element: this.scrollTarget.widget})
+ this.targetScroll({}, true)
+ })
+
+ }
+
+ targetScroll(e, init) {
+
+ if (!this.scrollTarget || (e && e.locked)) return
+
+ var index = this.getProp('horizontal') ? 0 : 1,
+ size = this.getProp('horizontal') ? this.width : this.height
+
+ this.thumbSize = this.scrollTarget.scrollThumb[index]
+ this.cssVars.knobSize = Math.max(this.thumbSize * size, 30)
+
+ if (init && this.value) {
+ // panel (re)createed: restore scroll state
+ this.setValue(this.value, {fromScrollEvent: false, send: false, sync: false})
+ } else if (this.scrollTarget.scroll[index] != this.value) {
+ // panel scrolling: update scroll state
+ this.setValue(this.scrollTarget.scroll[index], {fromScrollEvent: true, send: !init, sync: !init})
+ }
+
+ }
+
+
+ setValue(v, options={}) {
+
+ super.setValue(v, options)
+
+ if (!options.fromScrollEvent && this.scrollTarget) {
+ if (this.getProp('horizontal')) {
+ this.scrollTarget.setScroll(this.value, undefined, true)
+ } else {
+ this.scrollTarget.setScroll(undefined, this.value, true)
+ }
+ }
+
+ }
+
+ draw() {
+
+ var width = this.getProp('horizontal') ? this.height : this.width,
+ height = !this.getProp('horizontal') ? this.height : this.width
+
+ var percent = this.steps ? this.valueToPercent(this.value) : this.percent,
+ d = Math.round(this.percentToCoord(percent)),
+ m = this.getProp('horizontal') ? this.height / 2 : this.width / 2,
+ dashed = this.dashed,
+ knobHeight = this.cssVars.knobSize
+
+ this.clear()
+
+ // sharp border trick
+ if (width % 2 && parseInt(m) === m) m -= 0.5
+
+
+ this.ctx.strokeStyle = this.gaugeGradient || this.cssVars.colorFill
+
+ this.ctx.lineWidth = Math.round(width - this.gaugePadding * 2)
+
+
+ if (dashed) this.ctx.setLineDash([PXSCALE * dashed[0], PXSCALE * dashed[1]])
+
+
+ if (this.cssVars.alphaFillOff) {
+ // gaugo off
+ this.ctx.globalAlpha = this.cssVars.alphaFillOff
+ this.ctx.beginPath()
+ this.ctx.moveTo(m, height - this.gaugePadding)
+ this.ctx.lineTo(m, this.gaugePadding)
+ this.ctx.stroke()
+ }
+
+
+ if (dashed) this.ctx.setLineDash([])
+
+ // flat knob
+
+ this.ctx.globalAlpha = this.cssVars.alphaFillOn
+ this.ctx.fillStyle = this.cssVars.colorKnob
+
+ this.ctx.beginPath()
+ // adjust position to keep knob within gauge boundaries
+ d = (d - this.gaugePadding ) / (height - this.gaugePadding * 2 ) * (height - this.gaugePadding * 2 - knobHeight) + this.gaugePadding
+ if (this.cssVars.borderRadius > 0 && this.ctx.roundRect) {
+ this.ctx.roundRect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight, PXSCALE * this.cssVars.borderRadius)
+ } else {
+ this.ctx.rect(this.gaugePadding, d, width - this.gaugePadding * 2, knobHeight)
+ }
+ this.ctx.fill()
+
+ let x, y, w, h,
+ rad = PXSCALE * this.cssVars.borderRadius
+
+ // border radius: clip gauge & knob
+ if (rad > 0) {
+ rad = Math.min(Math.min(height, width) / 2, rad)
+ x = this.gaugePadding
+ y = this.gaugePadding
+ w = width - this.gaugePadding * 2
+ h = height - this.gaugePadding * 2
+ this.ctx.beginPath()
+ this.ctx.moveTo(x + rad, y)
+ this.ctx.arcTo(x + w, y, x + w, y + h, rad)
+ this.ctx.arcTo(x + w, y + h, x, y + h, rad)
+ this.ctx.arcTo(x, y + h, x, y, rad)
+ this.ctx.arcTo(x, y, x + w, y, rad)
+ this.ctx.closePath()
+
+ var tmpOp = this.ctx.globalCompositeOperation
+ this.ctx.globalCompositeOperation = 'destination-in'
+ this.ctx.fillStyle = '#ffffff'
+ this.ctx.globalAlpha = 1
+ this.ctx.fill()
+ this.ctx.globalCompositeOperation = tmpOp
+ }
+
+ // stroke
+ if (this.cssVars.lineWidth) {
+
+ this.ctx.globalAlpha = this.cssVars.alphaStroke
+ this.ctx.strokeStyle = this.cssVars.colorStroke
+
+ // draw stroke
+ x = 0.5 * this.cssVars.lineWidth
+ y = 0.5 * this.cssVars.lineWidth
+ w = width - this.cssVars.lineWidth
+ h = height - this.cssVars.lineWidth
+
+ this.ctx.beginPath()
+ if (rad > 0) {
+ this.ctx.moveTo(x + rad, y)
+ this.ctx.arcTo(x + w, y, x + w, y + h, rad)
+ this.ctx.arcTo(x + w, y + h, x, y + h, rad)
+ this.ctx.arcTo(x, y + h, x, y, rad)
+ this.ctx.arcTo(x, y, x + w, y, rad)
+ } else {
+ this.ctx.moveTo(x, y)
+ this.ctx.lineTo(x + w, y)
+ this.ctx.lineTo(x + w, y + h)
+ this.ctx.lineTo(x, y + h)
+ }
+
+ this.ctx.closePath()
+ this.ctx.lineWidth = this.cssVars.lineWidth
+ this.ctx.stroke()
+
+ }
+
+
+
+ this.clearRect = [0, 0, width, height]
+
+
+ }
+
+ onRemove(){
+
+ this.unbindTarget()
+ super.onRemove()
+
+ }
+
+}
diff --git a/src/client/widgets/sliders/slider.js b/src/client/widgets/sliders/slider.mjs
similarity index 58%
rename from src/client/widgets/sliders/slider.js
rename to src/client/widgets/sliders/slider.mjs
index 23736c26..e3ac837f 100644
--- a/src/client/widgets/sliders/slider.js
+++ b/src/client/widgets/sliders/slider.mjs
@@ -1,8 +1,8 @@
-var {clip, mapToScale} = require('../utils'),
- Canvas = require('../common/canvas'),
- touchstate = require('../mixins/touch_state'),
- doubletab = require('../mixins/double_tap'),
- html = require('nanohtml')
+import html from 'nanohtml'
+import {clip, mapToScale} from '../utils.mjs'
+import Canvas from '../common/canvas.mjs'
+import touchstate from '../mixins/touch_state.mjs'
+import doubleTap from '../mixins/double_tap'
class Slider extends Canvas {
@@ -14,30 +14,38 @@ class Slider extends Canvas {
this.container.classList.add('design-' + this.getProp('design'))
- this.value = undefined
this.percent = 0
this.gaugePadding = 0
- this.rangeKeys = []
+ this.rangeKeys = Object.keys(this.getProp('range')).sort((a,b)=>{
+ if (a === 'min' || b === 'max') return -1
+ else if (a === 'max' || b === 'min') return 1
+ else return parseFloat(a) - parseFloat(b)
+ })
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'?
+ for (var i in this.rangeKeys) {
+ var k = this.rangeKeys[i],
+ key = k == 'min' ? 0 : k == 'max' ? 100 : parseFloat(k),
+ val = typeof this.getProp('range')[k] === 'object' && this.getProp('range')[k] !== null ?
this.getProp('range')[k][Object.keys(this.getProp('range')[k])[0]]:
- this.getProp('range')[k],
- label = typeof this.getProp('range')[k] == 'object'?
+ this.getProp('range')[k]
+
+ if (isNaN(val) || val === null || val === undefined) val = 0
+
+ var label = typeof this.getProp('range')[k] === 'object' && this.getProp('range')[k] !== null ?
Object.keys(this.getProp('range')[k])[0]:
val
if (Math.abs(label) >= 1000) label = Math.round(label / 1000) + 'k'
- this.rangeKeys.push(key)
+ this.rangeKeys[i] = key
this.rangeVals.push(val)
this.rangeLabels.push(label)
}
+
this.rangeValsMax = Math.max(...this.rangeVals),
this.rangeValsMin = Math.min(...this.rangeVals)
@@ -49,35 +57,55 @@ class Slider extends Canvas {
if (typeof this.getProp('doubleTap') === 'string' && this.getProp('doubleTap')[0] === '/') {
- doubletab(this.widget, ()=>{
+ doubleTap(this, (e)=>{
+ if (!this.shouldDrag(e)) return
this.sendValue({v:null, address: this.getProp('doubleTap')})
- })
+ }, {element: this.widget})
+
+ }
+ if (this.getProp('doubleTap') == 'script') {
+
+ doubleTap(this, (e)=>{
+ if (!this.shouldDrag(e)) return
+ this.scripts.onTouch.run({
+ event: {type: 'doubleTap'},
+ value: this.value
+ }, {sync: true, send: true})
+ }, {element: this.widget})
+
} else {
- doubletab(this.widget, ()=>{
- this.setValue(this.getSpringValue(),{sync:true, send:true, fromLocal:true, doubleTab:true})
- })
+ doubleTap(this, (e)=>{
+ if (!this.shouldDrag(e)) return
+ this.setValue(this.getSpringValue(),{sync:true, send:true, fromLocal:true, doubleTap:true})
+ }, {element: this.widget})
}
}
- this.widget.addEventListener('wheel',this.mousewheelHandleProxy.bind(this))
-
touchstate(this, {element: this.widget, multitouch: options.multitouch})
this.on('draginit', this.draginitHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
this.on('drag', this.dragHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
this.on('dragend', this.dragendHandleProxy.bind(this), {element:this.widget, multitouch: options.multitouch})
+ this.on('wheel',this.mousewheelHandleProxy.bind(this), {element: this.widget})
+ this.steps = null
this.setSteps()
this.setValue(this.getSpringValue())
}
+ shouldDrag(e) {
+
+ return true
+
+ }
+
mousewheelHandleProxy() {
this.mousewheelHandle(...arguments)
@@ -104,7 +132,7 @@ class Slider extends Canvas {
mousewheelHandle(e) {
- if (e.deltaX) return
+ if (e.deltaX || this.getProp('spring') || !this.shouldDrag(e)) return
e.preventDefault()
e.stopPropagation()
@@ -112,11 +140,25 @@ class Slider extends Canvas {
var direction = e.deltaY > 0 ? -1 : 1,
increment = e.ctrlKey ? 0.25 : 1
- if (this.getProp('steps')) {
- var i = this.steps.indexOf(this.value)
- if (i > -1 && i < this.steps.length) {
- this.setValue(this.steps[i + direction], {sync: true, send: true, fromLocal: true})
+ if (this.steps) {
+ var i = this.steps.indexOf(this.value),
+ val
+ if (i === -1) {
+ val = this.steps.reduce((a, b) => {
+ let aDiff = Math.abs(a - this.value),
+ bDiff = Math.abs(b - this.value)
+
+ if (aDiff == bDiff) {
+ return (direction ? a > b : b > a) ? a : b
+ } else {
+ return bDiff < aDiff && ((b - this.value) > 0 != e.deltaY > 0)? b : a
+ }
+ })
}
+ else if (i < this.steps.length) {
+ val = this.steps[i + direction]
+ }
+ if (val !== undefined) this.setValue(val, {sync: true, send: true, fromLocal: true})
} else {
this.percent = clip(this.percent + Math.max(increment,10/Math.pow(10,this.decimals + 1)) * direction, [0,100])
this.setValue(this.percentToValue(this.percent), {sync: true, send: true, dragged: true})
@@ -184,7 +226,12 @@ class Slider extends Canvas {
setValue(v,options={}) {
if (typeof v != 'number') return
- if (this.touched && !options.dragged && !options.doubleTab) return this.setValueTouchedQueue = [v, options]
+ if (
+ this.touched &&
+ !options.dragged &&
+ !options.doubleTap &&
+ options.fromScript !== this.hash
+ ) return this.setValueTouchedQueue = [v, options]
var value = clip(v,[this.rangeValsMin,this.rangeValsMax])
@@ -192,7 +239,7 @@ class Slider extends Canvas {
this.value = value
- if (this.getProp('steps')) {
+ if (this.steps) {
var diff = this.steps.map(x => Math.abs(x - this.value)),
index = diff.indexOf(Math.min(...diff)),
@@ -215,10 +262,18 @@ class Slider extends Canvas {
if (this.getProp('steps')) {
var steps = this.getProp('steps')
- this.steps = Array.isArray(steps) ?
- steps : typeof steps === 'number' ?
- Array(steps).fill(0).map((x, i) => i / (steps - 1) * (this.rangeValsMax - this.rangeValsMin) + this.rangeValsMin)
- : this.rangeVals
+ if (steps === 'auto') {
+ this.steps = this.rangeVals
+ } else if (typeof steps === 'number' && Math.round(steps) > 0) {
+ steps = Math.round(steps)
+ this.steps = Array(steps).fill(0).map((x, i) => i / (steps - 1) * (this.rangeValsMax - this.rangeValsMin) + this.rangeValsMin)
+ } else if (Array.isArray(steps) && steps.every(x=>typeof x === 'number')) {
+ this.steps = steps
+ } else {
+ this.steps = null
+ }
+ } else {
+ this.steps = null
}
}
@@ -232,6 +287,13 @@ class Slider extends Canvas {
case 'steps':
this.setSteps()
return
+ case 'spring':
+ if (this.getProp('spring') && !this.touched) this.setValue(this.getSpringValue(), {...options})
+ return
+ case 'colorKnob':
+ case 'knobSize':
+ this.setCssVariables()
+ return
}
@@ -251,6 +313,8 @@ Slider.dynamicProps = Slider.prototype.constructor.dynamicProps
'spring',
'sensitivity',
'default',
+ 'colorKnob',
+ 'knobSize'
])
-module.exports = Slider
+export default Slider
diff --git a/src/client/widgets/utils.js b/src/client/widgets/utils.js
deleted file mode 100644
index d0e5f916..00000000
--- a/src/client/widgets/utils.js
+++ /dev/null
@@ -1,118 +0,0 @@
-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
- // value: number
- // rangeIn: [number, number]
- // rangeOut: [number, number]
- // decimals: number (-1 to bypass)
- // log: true, or manual log scale (max log value)
- // revertLog: boolean
- mapToScale: function(value, rangeIn, rangeOut, decimals, log, revertlog) {
-
- // clip in
- value = module.exports.clip(value,[rangeIn[0], rangeIn[1]])
-
-
- // normalize
- value = (value - rangeIn[0]) / (rangeIn[1] - rangeIn[0])
-
- // log scale
- if (log) {
-
- var logScale = revertlog ? Math.abs(rangeIn[1] - rangeIn[0]) :
- Math.abs(rangeOut[1] - rangeOut[0])
-
- if (log !== true && log !== -1) logScale = Math.abs(log)
- else if (logScale >= 100) logScale /= 10
- else logScale = Math.max(logScale, 10)
-
- if (log < 0) revertlog = !revertlog
-
- value = revertlog ?
- Math.log(value * (logScale - 1) + 1) / Math.log(logScale) :
- Math.pow(logScale, value) / (logScale - 1) - 1 / (logScale - 1)
-
- }
-
- // scale out
- value = value * (rangeOut[1] - rangeOut[0]) + rangeOut[0]
-
- // clip out
- value = module.exports.clip(value, [rangeOut[0], rangeOut[1]])
-
- // decimals
- if (decimals !== -1) value = parseFloat(value.toFixed(decimals))
-
- return value
-
- },
-
- hsbToRgb: function(hsb) {
- var rgb = {}
- var h = hsb.h
- var s = hsb.s*255/100
- var v = hsb.b*255/100
- if(s == 0) {
- rgb.r = rgb.g = rgb.b = v
- } else {
- var t1 = v
- var t2 = (255-s)*v/255
- var t3 = (t1-t2)*(h%60)/60
- if(h==360) h = 0
- if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
- else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
- else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
- else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
- else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
- else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
- else {rgb.r=0; rgb.g=0; rgb.b=0}
- }
- return rgb
- },
-
- rgbToHsb: function(rgb) {
- var hsb = {h: 0, s: 0, b: 0}
- var min = Math.min(rgb.r, rgb.g, rgb.b)
- var max = Math.max(rgb.r, rgb.g, rgb.b)
- var delta = max - min
- hsb.b = max
- hsb.s = max != 0 ? 255 * delta / max : 0
- if (hsb.s != 0) {
- if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta
- else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta
- else hsb.h = 4 + (rgb.r - rgb.g) / delta
- } else hsb.h = 0
- hsb.h *= 60
- if (hsb.h < 0) hsb.h += 360
- hsb.s *= 100/255
- hsb.b *= 100/255
- return hsb
- },
-
- urlParser: (()=>{
-
- var parser = document.createElement('a'),
- localUrlRe = /(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.1[6-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.2[0-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.3[0-1]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)/
-
- parser.isLocal = ()=>{
- return parser.hostname.match(localUrlRe)
- }
-
- return (url)=>{
- parser.href = url
- return parser
- }
-
- })()
-
-}
diff --git a/src/client/widgets/utils.mjs b/src/client/widgets/utils.mjs
new file mode 100644
index 00000000..62482c86
--- /dev/null
+++ b/src/client/widgets/utils.mjs
@@ -0,0 +1,156 @@
+import balanced from 'balanced-match'
+
+export function clip(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
+// value: number
+// rangeIn: [number, number]
+// rangeOut: [number, number]
+// decimals: number (-1 to bypass)
+// log: true, or manual log scale (max log value)
+// revertLog: boolean
+export function mapToScale(value, rangeIn, rangeOut, decimals, log, revertlog, noClip) {
+
+ // clip in
+ if (!noClip) {
+ value = clip(value,[rangeIn[0], rangeIn[1]])
+ }
+
+
+ // normalize
+ value = (value - rangeIn[0]) / (rangeIn[1] - rangeIn[0])
+
+ // log scale
+ if (log) {
+
+ var logScale = revertlog ? Math.abs(rangeIn[1] - rangeIn[0]) :
+ Math.abs(rangeOut[1] - rangeOut[0])
+
+ if (log !== true && log !== -1) logScale = Math.abs(log)
+ else if (logScale >= 100) logScale /= 10
+ else logScale = Math.max(logScale, 10)
+
+ if (log < 0) revertlog = !revertlog
+
+ value = revertlog ?
+ Math.log(value * (logScale - 1) + 1) / Math.log(logScale) :
+ Math.pow(logScale, value) / (logScale - 1) - 1 / (logScale - 1)
+
+ }
+
+ // scale out
+ value = value * (rangeOut[1] - rangeOut[0]) + rangeOut[0]
+
+ // clip out
+ if (!noClip) {
+ value = clip(value, [rangeOut[0], rangeOut[1]])
+ }
+
+ // decimals
+ if (decimals !== -1) value = parseFloat(value.toFixed(decimals))
+
+ return value
+
+}
+
+export function hsbToRgb(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
+}
+
+export function rgbToHsb(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
+}
+
+
+var urlParser = (()=>{
+
+ var parser = document.createElement('a'),
+ localUrlRe = /(^127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.1[6-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.2[0-9]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^172\.3[0-1]{1}[0-9]{0,1}\.[0-9]{1,3}\.[0-9]{1,3}$)|(^192\.168\.[0-9]{1,3}\.[0-9]{1,3}$)/
+
+ parser.isLocal = ()=>{
+ return parser.hostname.match(localUrlRe)
+ }
+
+ return (url)=>{
+ parser.href = url
+ return parser
+ }
+
+})()
+
+export {urlParser}
+
+export function balancedReplace(tag, open, close, string, replacement) {
+
+ var start, lastStart = -1
+
+ while ((start = string.indexOf(tag + open)) >= 0 && lastStart !== start) {
+
+ var substring = string.slice(start + tag.length),
+ b = balanced(open, close, substring)
+
+ if (b) {
+
+ if (typeof replacement === 'function') {
+
+ substring = b.pre + replacement(b.body) + b.post
+
+ } else {
+
+ substring = b.pre + replacement + b.post
+
+ }
+
+ string = string.slice(0, start) + substring
+
+ }
+
+ lastStart = start
+
+ }
+
+ return string
+
+}
diff --git a/src/client/widgets/vm.js b/src/client/widgets/vm.mjs
similarity index 50%
rename from src/client/widgets/vm.js
rename to src/client/widgets/vm.mjs
index 08416986..389dceaa 100644
--- a/src/client/widgets/vm.js
+++ b/src/client/widgets/vm.mjs
@@ -1,18 +1,38 @@
-var loopProtect = require('loop-protect'),
- {deepCopy} = require('../utils'),
- globals
+import {deepCopy} from '../utils.mjs'
+import {ENV, IP} from '../globals.mjs'
+
+var sessionManager
+setTimeout(async()=>{
+ // use setTimeout to fix init order in safari...
+ sessionManager = (await import('../managers/session/index.mjs')).default
+})
+
+
+var globals
class Vm {
constructor() {
+ this.widget = []
+
if (!globals) {
globals = {
- screen: {width: screen.width, height: screen.height},
+ screen: {
+ get width() {return screen.width},
+ get height() {return screen.height},
+ get orientation() {
+ return (screen.orientation || {}).type || window.orientation
+ }
+ },
env: deepCopy(ENV),
ip: IP,
url: document.location.host,
- platform: navigator.platform
+ platform: navigator.platform,
+ clipboard: navigator.clipboard,
+ get session() {
+ return sessionManager.sessionPath
+ }
}
}
@@ -31,14 +51,21 @@ class Vm {
this.sandbox.contentWindow.document.write('')
this.sandbox.contentWindow.document.close()
- // init infinite loop guard
- loopProtect.alias = '__protect'
- loopProtect.hit = function(line){
- throw 'Potential infinite loop found on line ' + line
- }
- this.sandbox.contentWindow.__protect = loopProtect
-
// global context
+ this.globals = {}
+ this.globals.console = {
+ ...console,
+ log: (...msg)=>{
+ msg = msg.map(m => typeof m == 'object' ? JSON.stringify(m, this.jsonReplacer) : m)
+ this.getWidget().log(msg.join(' '))
+ }
+ }
+
+ this.globals.setTimeout =
+ this.globals.setInterval = ()=>{
+ throw 'setTimeout and setInterval can\'t be used in the JS sandbox'
+ }
+
this.registerGlobals()
// detach sandbox
@@ -46,50 +73,43 @@ class Vm {
}
- registerGlobals() {
+ setWidget(widget) {
- this.sandbox.contentWindow.console = console
- this.sandbox.contentWindow.setTimeout =
- this.sandbox.contentWindow.setInterval = ()=>{
- throw 'setTimeout and setInterval can\'t be used in the JS sandbox'
- }
- this.sandbox.contentWindow.globals = globals
-
- // sanitize globals
- for (var imports of ['__protect', 'console', 'setTimeout', 'setInterval', 'globals']) {
- this.sanitize(this.sandbox.contentWindow[imports])
- }
+ if (!widget) this.widget.pop()
+ else this.widget.push(widget)
}
- sanitize(object) {
+ getWidget() {
- // non-primitives created outside the sandbox context can leak
- // the host window object... let's nuke that !
- // (we only nuke functions and objects/arrays because we don't pass anything else)
- var t = typeof o
- if (t === 'function' || (t === 'object' && o !== null)) {
- if (o.__proto__) {
- if (t === 'function') {
- o.__proto__.constructor = this.safeFunctionProto
- } else {
- o.__proto__.constructor.constructor = this.safeFunctionProto
- }
- }
- for (var k in o) {
- this.sanitize(o[k])
- }
+ return this.widget[this.widget.length - 1]
+
+ }
+
+ registerGlobals() {
+
+ this.globals.globals = globals
+
+ for (var k in this.globals) {
+ this.sandbox.contentWindow[k] = this.globals[k]
}
}
compile(code, defaultContext) {
+ if (typeof code !== 'string') code = String(code)
+
// var contextInit = 'var locals = locals;',
- var contextInit = '',
+ var contextInit = '"use strict";',
contextKeys = ['__VARS'],
contextValues = [{}]
+ // detached context + reading global navigator == crash electron
+ if (code.indexOf('navigator') !== -1) {
+ contextInit += 'var navigator;'
+ }
+
if (defaultContext) {
for (var k in defaultContext) {
contextInit += `var ${k} = ${k} === undefined ? ${JSON.stringify(defaultContext[k])} : ${k};`
@@ -98,13 +118,9 @@ class Vm {
}
}
- var compiledCode = new this.safeFunctionProto(
- ...contextKeys, 'locals',
- loopProtect('"use strict";' + contextInit + code)
- .replace(/;\n(if \(__protect.*break;)\n/g, ';$1') // prevent loop protect from breaking stack linenumber
- .replace(/(VAR_[0-9]+)/g, '__VARS.$1')
- )
+ code = contextInit + code.replace(/(VAR_[0-9]+)/g, '__VARS.$1')
+ var compiledCode = new this.safeFunctionProto(...contextKeys, 'locals', code)
return (context, locals)=>{
@@ -121,14 +137,16 @@ class Vm {
__contextValues.push(locals)
- this.sanitize(__contextValues)
-
- return compiledCode.apply(null, __contextValues)
+ return compiledCode.apply('this', __contextValues)
}
}
+ jsonReplacer(key, value) {
+ return value instanceof HTMLElement ? `<${value.tagName}#${value.id}>` : value
+ }
+
}
-module.exports = Vm
+export default Vm
diff --git a/scripts/client-shim.js b/src/docs/client-shim.mjs
similarity index 63%
rename from scripts/client-shim.js
rename to src/docs/client-shim.mjs
index 77c106d9..dc87e8ca 100644
--- a/scripts/client-shim.js
+++ b/src/docs/client-shim.mjs
@@ -1,10 +1,12 @@
// Dirty browser window shim
+import * as DOM from '../client/dom.mjs'
+// eslint-disable-next-line no-global-assign
document = {
createElement: x=>({
ownerDocument: document,
- style: {},
- contentWindow: {},
+ addEventListener: ()=>{},
+ style: {setProperty: ()=>{}},
nodeName: '',
childNodes: [],
setAttribute: ()=>{},
@@ -12,14 +14,16 @@ document = {
lastChild: {},
toString: ()=>' ',
removeChild: ()=>{},
+ getPropertyValue: ()=>{},
contentWindow: {
document: {
open: ()=>{},
close: ()=>{},
write: ()=>{},
}
- }
+ },
}),
+ getElementById: ()=>document.createElement(),
createTextNode: x=>({
nodeValue: '',
nodeName: '',
@@ -45,41 +49,44 @@ document = {
appendChild: ()=>{},
addEventListener: ()=>{}
},
- location: {},
- documentElement: {
- appendChild: ()=>{},
- removeChild: ()=>{}
- }
+ location: {search: ''},
}
+document.documentElement = document.createElement()
+// eslint-disable-next-line no-global-assign
window = {
screen: {width: 800, height: 600},
addEventListener: ()=>{},
- location: {},
+ location: {search: ''},
+ Image: Function,
document: document,
- navigator: {
- platform:'',
- userAgent: ''
- },
NodeList: Array,
WebSocket: Object,
localStorage: {
getItem(){return null}
- }, sessionStorage: {
+ },
+ sessionStorage: {
getItem(){return null},
- setItem(){},
- },
+ setItem(){},
+ },
+ getComputedStyle: ()=>document.createElement(),
+ MutationObserver: class MutationObserver{},
+ ELECTRON_NOGPU: false,
+ CANVAS_FRAMERATE: 1,
+ LANG: 'en',
+ ENV: {id: ''},
+ IP: '',
+ DOM
+}
+
+if (!global.navigator) {
+ // defined as getter since node 22
+ window.navigator = {
+ platform:'',
+ userAgent: ''
+ }
}
Object.assign(global, window)
-// Required globals
-
-DOM = require('../src/client/dom')
-DOM.get = x=>[{addEventListener:()=>{}}]
-DOM.init()
-ELECTRON_NOGPU = false
-CANVAS_FRAMERATE = 1
-LANG = 'en'
-ENV = {id: ''}
-IP = ''
+console.debug = ()=>{}
diff --git a/scripts/build-widgets-reference.js b/src/docs/widgets-reference.mjs
similarity index 74%
rename from scripts/build-widgets-reference.js
rename to src/docs/widgets-reference.mjs
index fd528d38..d4178ff3 100644
--- a/scripts/build-widgets-reference.js
+++ b/src/docs/widgets-reference.mjs
@@ -1,9 +1,9 @@
-require('./client-shim')
+import './client-shim.mjs'
+import baseClass from '../client/widgets/common/widget.mjs'
+import * as widgets from '../client/widgets/index.mjs'
// Here we go
-var widgets = require('../src/client/widgets'),
- baseClass = require('../src/client/widgets/common/widget'),
- base = baseClass.defaults(),
+var base = baseClass.defaults(),
doc = ['']
@@ -17,24 +17,24 @@ doc.push(`
`
)
-for (var categoryName in base) {
+for (let categoryName in base) {
doc.push(`\n
-=== "${categoryName}"
+ === "${categoryName}"
- | property | type |default | description |
- | --- | --- | --- | --- |`
+ | property | type |default | description |
+ | --- | --- | --- | --- |`
)
- var notEmpty = false
+ let notEmpty = false
- for (var propName in base[categoryName]) {
+ for (let propName in base[categoryName]) {
- var prop = base[categoryName][propName],
+ let prop = base[categoryName][propName],
permalink = propName
- if (propName === '_props' || propName[0] === '_') continue
+ if (propName === '_props' || propName[0] === '_') continue
- var help = Array.isArray(prop.help) ? prop.help.join('
').replace(/
-/g, '-') : prop.help || '',
+ let help = Array.isArray(prop.help) ? prop.help.join('
').replace(/
-/g, '-') : prop.help || '',
dynamic = baseClass.dynamicProps.includes(propName) ? '' : ''
if (prop.choices) {
@@ -75,24 +75,24 @@ for (var k in widgets.categories) {
)
- for (var categoryName in defaults) {
+ for (let categoryName in defaults) {
doc.push(`\n
=== "${categoryName == 'class_specific' ? type : categoryName}"
| property | type |default | description |
| --- | --- | --- | --- |`
)
- var notEmpty = false
+ let notEmpty = false
- for (var propName in defaults[categoryName]) {
+ for (let propName in defaults[categoryName]) {
- var prop = defaults[categoryName][propName],
+ let prop = defaults[categoryName][propName],
permalink = type + '_' + propName
- if (propName === '_props' || propName[0] === '_' || JSON.stringify(prop) == JSON.stringify((base[categoryName]||{})[propName])) continue
+ if (propName === '_props' || propName[0] === '_' || JSON.stringify(prop) == JSON.stringify((base[categoryName]||{})[propName])) continue
- var help = Array.isArray(prop.help) ? prop.help.join('
').replace(/
-/g, '-') : prop.help || '',
+ let help = Array.isArray(prop.help) ? prop.help.join('
').replace(/
-/g, '-') : prop.help || '',
dynamic = widgets.widgets[type].dynamicProps.includes(propName) ? '' : ''
if (prop.choices) {
diff --git a/src/html/client.html b/src/html/client.html
index c1012c7f..48ea3ece 100644
--- a/src/html/client.html
+++ b/src/html/client.html
@@ -2,21 +2,28 @@
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
@@ -29,7 +36,9 @@
-
+
+ ${productName} v${version}
+
@@ -38,7 +47,6 @@
-
@@ -52,7 +60,8 @@
-
+
+
diff --git a/src/html/launcher.html b/src/html/launcher.html
index 60f6e86b..6945d250 100644
--- a/src/html/launcher.html
+++ b/src/html/launcher.html
@@ -1,11 +1,13 @@
+
+
@@ -24,7 +26,6 @@
-
diff --git a/src/index.js b/src/index.js
new file mode 100644
index 00000000..3680c66b
--- /dev/null
+++ b/src/index.js
@@ -0,0 +1 @@
+require('./server/')
diff --git a/src/launcher/context-menu.js b/src/launcher/context-menu.js
deleted file mode 100644
index b3fb89fc..00000000
--- a/src/launcher/context-menu.js
+++ /dev/null
@@ -1,28 +0,0 @@
-var {remote} = require('electron'),
- {Menu, MenuItem} = remote.require('electron'),
- menu = new Menu()
-
-
-menu.append(new MenuItem({role: 'undo'}))
-menu.append(new MenuItem({role: 'redo'}))
-menu.append(new MenuItem({type: 'separator'}))
-menu.append(new MenuItem({role: 'copy'}))
-menu.append(new MenuItem({role: 'paste'}))
-
-// not working currently
-// menu.append(new MenuItem({type: 'submenu' , label: 'App', submenu: [
-// new MenuItem({
-// label: 'Relaunch',
-// click: ()=>{
-// app.relaunch()
-// app.exit(0)
-// }
-// }),
-// ]}))
-
-
-window.addEventListener('contextmenu', function(e) {
- menu.items[3].enabled = !!window.getSelection().toString()
- menu.items[4].enabled = e.target.tagName === 'INPUT' && !e.target.getAttribute('disabled')
- menu.popup({ window: remote.getCurrentWindow(), x: e.pageX, y: e.pageY - (document.body.scrollTop || document.documentElement.scrollTop) })
-}, false)
diff --git a/src/launcher/index.js b/src/launcher/index.js
deleted file mode 100644
index 8e61e3fb..00000000
--- a/src/launcher/index.js
+++ /dev/null
@@ -1,15 +0,0 @@
-require('../client/globals')
-
-document.addEventListener('DOMContentLoaded', function(event) {
-
- DOM.init()
- require('../client/events/event-emitter')
- require('../client/ui/ui-workspace')
- require('../client/ui/zoom')
-
- setTimeout(()=>{
- require('./main')
- }, 10)
-
-
-})
diff --git a/src/launcher/index.mjs b/src/launcher/index.mjs
new file mode 100644
index 00000000..745bd104
--- /dev/null
+++ b/src/launcher/index.mjs
@@ -0,0 +1,5 @@
+import '../client/globals.mjs'
+import '../client/events/event-emitter.mjs'
+import '../client/ui/ui-workspace.mjs'
+import '../client/ui/zoom.mjs'
+import './main.mjs'
diff --git a/src/launcher/main.js b/src/launcher/main.js
deleted file mode 100644
index 5add0885..00000000
--- a/src/launcher/main.js
+++ /dev/null
@@ -1,33 +0,0 @@
-var terminal = require('./terminal'),
- settings = require('./settings'),
- html = require('nanohtml'),
- semver = require('semver')
-
-require('./toolbar')
-require('./context-menu')
-
-DOM.get(document, '#osc-greeting-header')[0].appendChild(html`${window.PACKAGE.productName} v${window.PACKAGE.version}`)
-
-if (settings.remote.read('checkForUpdates') && navigator.onLine) {
-
- var request = new XMLHttpRequest()
- request.open('GET', 'https://api.github.com/repos/jean-emmanuel/open-stage-control/tags', true)
-
- request.onload = function() {
- if (request.status >= 200 && request.status < 400) {
- var data = JSON.parse(request.responseText),
- current = 'v' + window.PACKAGE.version,
- latest = data[0].name
-
- if (semver.gt(latest, current)) {
- terminal.log(`(INFO) A new version is available : ${latest}`, 'info')
- } else if (semver.gt(current, latest)) {
- terminal.log(`(WARNING) Using development version ${current}`, 'warning')
- }
-
- }
- }
-
- request.send()
-
-}
diff --git a/src/launcher/main.mjs b/src/launcher/main.mjs
new file mode 100644
index 00000000..2dcdeaac
--- /dev/null
+++ b/src/launcher/main.mjs
@@ -0,0 +1,47 @@
+import html from 'nanohtml'
+import semver from 'semver'
+import {ipcRenderer} from 'electron'
+import terminal from './terminal.mjs'
+import settings from './settings.mjs'
+import './toolbar.mjs'
+import {DOM, PACKAGE} from '../client/globals.mjs'
+
+DOM.get(document, '#osc-greeting-header')[0].appendChild(html`${PACKAGE.productName} v${PACKAGE.version}`)
+
+if (settings.remote.read('checkForUpdates') && navigator.onLine) {
+
+ var request = new XMLHttpRequest()
+ request.open('GET', 'https://framagit.org/api/v4/projects/jean-emmanuel%2Fopen-stage-control/releases', true)
+
+ request.onload = function() {
+ if (request.status >= 200 && request.status < 400) {
+
+ var data = JSON.parse(request.responseText).filter(x=>!x.name.match(/alpha|beta/)),
+ current = 'v' + PACKAGE.version,
+ latest = data[0].name
+
+ if (semver.gt(latest, current)) {
+ terminal.log(`(INFO) A new version is available : ${latest}`, 'info')
+ } else if (semver.gt(current, latest)) {
+ terminal.log(`(WARNING) Using development version ${current}`, 'warning')
+ }
+
+ }
+ }
+
+ request.send()
+
+}
+
+if (settings.remote.read('alwaysOnTop')) {
+
+ settings.remote.getCurrentWindow().setAlwaysOnTop(true)
+
+}
+
+
+if (settings.remote.read('autoStart')) {
+
+ ipcRenderer.send('start')
+
+}
diff --git a/src/launcher/settings.js b/src/launcher/settings.mjs
similarity index 87%
rename from src/launcher/settings.js
rename to src/launcher/settings.mjs
index babf3902..61a62073 100644
--- a/src/launcher/settings.js
+++ b/src/launcher/settings.mjs
@@ -1,11 +1,14 @@
-var {remote, ipcRenderer} = require('electron'),
- {dialog} = remote.require('electron'),
+import html from 'nanohtml'
+import raw from 'nanohtml/raw'
+import {ipcRenderer} from 'electron'
+import remote from '@electron/remote'
+import {icon} from '../client/ui/utils.mjs'
+import terminal from './terminal.mjs'
+import {DOM} from '../client/globals.mjs'
+
+var {dialog} = remote.require('electron'),
fs = remote.require('fs'),
- settings = remote.getGlobal('settings'),
- {icon} = require('../client/ui/utils'),
- html = require('nanohtml'),
- raw = require('nanohtml/raw'),
- terminal = require('./terminal'),
+ {settings} = remote.getGlobal('launcherSharedGlobals'),
options_remote = settings.read('options')
class Settings {
@@ -24,7 +27,7 @@ class Settings {
this.create()
this.write(true)
- ipcRenderer.on('server-started', ()=>{
+ ipcRenderer.on('server-starting', ()=>{
this.disable()
})
ipcRenderer.on('server-stopped', ()=>{
@@ -146,6 +149,21 @@ class Settings {
})
})
+ field.addEventListener('drop', (e) => {
+ e.preventDefault()
+ e.stopPropagation()
+ let paths = []
+ for (var f of event.dataTransfer.files) {
+ if (f.path.includes(' ')) {
+ paths.push('"' + f.path + '"')
+ } else {
+ paths.push(f.path)
+ }
+ }
+ input.value = paths.join(' ')
+ DOM.dispatchEvent(input, 'change')
+ })
+
}
reset = field.appendChild(html`
@@ -243,4 +261,4 @@ class Settings {
}
-module.exports = new Settings()
+export default new Settings()
diff --git a/src/launcher/terminal.js b/src/launcher/terminal.mjs
similarity index 84%
rename from src/launcher/terminal.js
rename to src/launcher/terminal.mjs
index 7b3931f4..9c382675 100644
--- a/src/launcher/terminal.js
+++ b/src/launcher/terminal.mjs
@@ -1,6 +1,12 @@
-var {ipcRenderer} = require('electron'),
- ansiHTML = require('ansi-html'),
- html = require('nanohtml')
+import {ipcRenderer} from 'electron'
+import ansiHTML from 'ansi-html'
+import html from 'nanohtml'
+import {DOM} from '../client/globals.mjs'
+
+ansiHTML.setColors({
+ magenta: 'B48EAD',
+ cyan: '81A1C1',
+})
class Terminal {
@@ -64,4 +70,4 @@ class Terminal {
}
-module.exports = new Terminal({selector: '#osc-terminal'})
+export default new Terminal({selector: '#osc-terminal'})
diff --git a/src/launcher/toolbar.js b/src/launcher/toolbar.js
deleted file mode 100644
index 9530c562..00000000
--- a/src/launcher/toolbar.js
+++ /dev/null
@@ -1,147 +0,0 @@
-var {remote, ipcRenderer} = require('electron'),
- {Menu, MenuItem} = remote.require('electron'),
- menu = new Menu(),
- terminal = require('./terminal'),
- settings = require('./settings'),
- midilist = remote.getGlobal('midilist'),
- openDocs = remote.getGlobal('openDocs'),
- serverStarted = false,
- serverStart = ()=>{
- if (serverStarted) return
- ipcRenderer.send('start')
- },
- serverStop = ()=>{
- if (!serverStarted) return
- ipcRenderer.send('stop')
- }
-
-var start = new MenuItem({
- label: 'Start',
- click: serverStart
-})
-var stop = new MenuItem({
- label: 'Stop',
- click: serverStop
-})
-var newWindow = new MenuItem({
- label: 'New window',
- visible: false,
- click: ()=>{
- ipcRenderer.send('openClient')
- }
-})
-menu.append(start)
-menu.append(stop)
-menu.append(newWindow)
-menu.append(new MenuItem({
- type: 'separator'
-}))
-menu.append(new MenuItem({
- label: 'Load',
- click: ()=>{
- settings.load()
- }
-}))
-menu.append(new MenuItem({
- label: 'Save',
- click: ()=>{
- settings.save()
- }
-}))
-menu.append(new MenuItem({
- label: 'Save as...',
- click: ()=>{
- settings.saveAs()
- }
-}))
-menu.append(new MenuItem({
- type: 'separator'
-}))
-menu.append(new MenuItem({
- label: 'List MIDI Devices',
- click: ()=>{
- midilist()
- }
-}))
-menu.append(new MenuItem({type: 'submenu' , label: 'Console', submenu: [
- new MenuItem({
- label: 'Clear',
- click: ()=>{
- terminal.clear()
- }
- }),
- new MenuItem({
- label: 'Autoscroll',
- type: 'checkbox',
- checked: true,
- click: function(e){
- terminal.autoSroll = e.checked
- }
- }),
- new MenuItem({
- label: 'Check for updates at startup',
- type: 'checkbox',
- checked: settings.remote.read('checkForUpdates'),
- click: (e)=>{
- settings.remote.write('checkForUpdates', e.checked)
- }
- })
-]}))
-menu.append(new MenuItem({
- type: 'separator'
-}))
-// menu.append(new MenuItem({
-// label: 'Restart',
-// click: ()=>{
-// app.relaunch()
-// app.exit(0)
-// }
-// }))
-menu.append(new MenuItem({
- label: 'Documentation',
- click: ()=>{
- openDocs()
- }
-}))
-menu.append(new MenuItem({
- role: 'Quit'
-}))
-
-class Toolbar {
-
- constructor() {
-
- this.container = DOM.get('osc-toolbar#menu')[0]
- this.startButton = DOM.get('osc-toolbar#start')[0]
-
- this.container.addEventListener('click', (e)=>{
- this.container.classList.add('on')
- start.visible = !serverStarted
- stop.visible = !!serverStarted
- newWindow.visible = !!serverStarted
- menu.popup({window: remote.getCurrentWindow(), x: parseInt(PXSCALE), y: parseInt(40 * PXSCALE)})
- })
-
- menu.on('menu-will-close', ()=>{
- this.container.classList.remove('on')
- })
-
- this.startButton.addEventListener('click', (e)=>{
- if (!serverStarted) serverStart()
- else serverStop()
- })
-
- ipcRenderer.on('server-started', ()=>{
- serverStarted = true
- this.startButton.classList.add('started')
- })
- ipcRenderer.on('server-stopped', ()=>{
- serverStarted = false
- this.startButton.classList.remove('started')
- })
-
- }
-
-}
-
-module.exports = new Toolbar()
diff --git a/src/launcher/toolbar.mjs b/src/launcher/toolbar.mjs
new file mode 100644
index 00000000..a6677b4d
--- /dev/null
+++ b/src/launcher/toolbar.mjs
@@ -0,0 +1,253 @@
+import {ipcRenderer} from 'electron'
+import remote from '@electron/remote'
+import keyboardJS from 'keyboardjs/dist/keyboard.min.js'
+import terminal from './terminal.mjs'
+import settings from './settings.mjs'
+import {DOM, PXSCALE} from '../client/globals.mjs'
+
+
+
+var {Menu, MenuItem} = remote.require('electron'),
+ menu = new Menu(),
+ {midiList, midiRestart, openDocs} = remote.getGlobal('launcherSharedGlobals'),
+ serverStarting = false,
+ serverStart = ()=>{
+ if (serverStarting) return
+ ipcRenderer.send('start')
+ },
+ serverStop = ()=>{
+ if (!serverStarting) return
+ ipcRenderer.send('stop')
+ },
+ showQRCode = ()=>{
+ ipcRenderer.send('showQRCode')
+ }
+
+var start = new MenuItem({
+ label: 'Start',
+ click: serverStart,
+ accelerator: 'f5'
+})
+var stop = new MenuItem({
+ label: 'Stop',
+ click: serverStop,
+ accelerator: 'f6'
+})
+var qrcode = new MenuItem({
+ label: 'Show QR code',
+ click: showQRCode,
+ accelerator: 'f7'
+})
+var newWindow = new MenuItem({
+ label: 'New window',
+ visible: false,
+ click: ()=>{
+ ipcRenderer.send('openClient')
+ },
+ accelerator: 'CmdOrCtrl + n'
+})
+menu.append(start)
+menu.append(stop)
+menu.append(qrcode)
+menu.append(newWindow)
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+menu.append(new MenuItem({
+ label: 'Load',
+ click: ()=>{
+ settings.load()
+ },
+ accelerator: 'CmdOrCtrl + o'
+}))
+menu.append(new MenuItem({
+ label: 'Save',
+ click: ()=>{
+ settings.save()
+ },
+ accelerator: 'CmdOrCtrl + s'
+}))
+menu.append(new MenuItem({
+ label: 'Save as...',
+ click: ()=>{
+ settings.saveAs()
+ },
+ accelerator: 'CmdOrCtrl + shift + s'
+}))
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+
+menu.append(new MenuItem({type: 'submenu' , label: 'MIDI', submenu: [
+ new MenuItem({
+ label: 'List devices',
+ click: ()=>{
+ midiList()
+ },
+ accelerator: 'ctrl + m'
+ }),
+ new MenuItem({
+ label: 'Restart backend',
+ id: 'midiRestart',
+ click: ()=>{
+ midiRestart()
+ },
+ enabled: false
+ }),
+
+]}))
+menu.append(new MenuItem({type: 'submenu' , label: 'Console', submenu: [
+ new MenuItem({
+ label: 'Clear',
+ click: ()=>{
+ terminal.clear()
+ },
+ accelerator: 'CmdOrCtrl + l'
+ }),
+ new MenuItem({
+ label: 'Autoscroll',
+ type: 'checkbox',
+ checked: true,
+ click: function(e){
+ terminal.autoSroll = e.checked
+ }
+ }),
+ new MenuItem({
+ label: 'Check for updates at startup',
+ type: 'checkbox',
+ checked: settings.remote.read('checkForUpdates'),
+ click: (e)=>{
+ settings.remote.write('checkForUpdates', e.checked)
+ }
+ })
+]}))
+menu.append(new MenuItem({type: 'submenu' , label: 'Launcher', submenu: [
+ new MenuItem({
+ label: 'Autostart',
+ type: 'checkbox',
+ checked: settings.remote.read('autoStart'),
+ click: (e)=>{
+ settings.remote.write('autoStart', e.checked)
+ remote.getCurrentWindow().setAlwaysOnTop(e.checked)
+ }
+ }),
+ new MenuItem({
+ label: 'Always on top',
+ type: 'checkbox',
+ checked: settings.remote.read('alwaysOnTop'),
+ click: (e)=>{
+ settings.remote.write('alwaysOnTop', e.checked)
+ remote.getCurrentWindow().setAlwaysOnTop(e.checked)
+ }
+ }),
+ new MenuItem({
+ label: 'Use tray icon',
+ type: 'checkbox',
+ checked: settings.remote.read('useTray'),
+ click: (e)=>{
+ settings.remote.write('useTray', e.checked)
+ }
+ }),
+ new MenuItem({
+ label: 'Start minimized',
+ type: 'checkbox',
+ checked: settings.remote.read('startMinimized'),
+ click: (e)=>{
+ settings.remote.write('startMinimized', e.checked)
+ }
+ }),
+]}))
+menu.append(new MenuItem({
+ type: 'separator'
+}))
+// menu.append(new MenuItem({
+// label: 'Restart',
+// click: ()=>{
+// app.relaunch()
+// app.exit(0)
+// }
+// }))
+menu.append(new MenuItem({
+ label: 'Documentation',
+ click: ()=>{
+ openDocs()
+ }
+}))
+
+if (settings.remote.read('useTray')) {
+ menu.append(new MenuItem({
+ label: 'Hide',
+ click: ()=>{
+ ipcRenderer.send('hide')
+ }
+ }))
+}
+
+menu.append(new MenuItem({
+ role: 'Quit'
+}))
+
+
+function bindShortcuts(menu) {
+
+ for (let m of menu.items) {
+
+ if (m.type === 'submenu') {
+
+ bindShortcuts(m.submenu)
+
+ } else if (m.accelerator && m.click) {
+
+ keyboardJS.bind(m.accelerator.replace('CmdOrCtrl', 'mod'), (e)=>{
+ m.click()
+ })
+
+ }
+
+ }
+
+}
+
+bindShortcuts(menu)
+
+class Toolbar {
+
+ constructor() {
+
+ this.container = DOM.get('osc-toolbar#menu')[0]
+ this.startButton = DOM.get('osc-toolbar#start')[0]
+
+ this.container.addEventListener('click', (e)=>{
+ this.container.classList.add('on')
+ start.visible = !serverStarting
+ stop.visible = !!serverStarting
+ qrcode.visible = !!serverStarting
+ newWindow.visible = !!serverStarting
+ menu.getMenuItemById('midiRestart').enabled = !!serverStarting
+
+ menu.popup({window: remote.getCurrentWindow(), x: parseInt(PXSCALE), y: parseInt(40 * PXSCALE)})
+ })
+
+ menu.on('menu-will-close', ()=>{
+ this.container.classList.remove('on')
+ })
+
+ this.startButton.addEventListener('click', (e)=>{
+ if (!serverStarting) serverStart()
+ else serverStop()
+ })
+
+ ipcRenderer.on('server-starting', ()=>{
+ serverStarting = true
+ this.startButton.classList.add('started')
+ })
+ ipcRenderer.on('server-stopped', ()=>{
+ serverStarting = false
+ this.startButton.classList.remove('started')
+ })
+
+ }
+
+}
+
+export default new Toolbar()
diff --git a/src/python/head.py b/src/python/head.py
deleted file mode 100644
index cb59c2ec..00000000
--- a/src/python/head.py
+++ /dev/null
@@ -1,33 +0,0 @@
-from sys import argv, stdin, stdout, version_info, version, exit
-from binascii import hexlify, unhexlify
-import traceback
-import json as JSON
-import re
-
-def ipc_send(name, data):
- print(JSON.dumps([name, data]))
- stdout.flush()
-
-try:
- import rtmidi
- from rtmidi.midiconstants import *
-
- API = rtmidi.API_UNIX_JACK if 'jack' in argv else rtmidi.API_UNSPECIFIED
- if API == rtmidi.API_UNIX_JACK and rtmidi.API_UNIX_JACK not in rtmidi.get_compiled_api():
- API = rtmidi.API_UNSPECIFIED
- ipc_send('log', '(ERROR, MIDI) python-rtmidi was not compiled with jack midi support, falling back to default API')
-
- JACK = API == rtmidi.API_UNIX_JACK
-
- in_dev = rtmidi.MidiIn(API, 'MIDI->OSC probe')
- out_dev = rtmidi.MidiOut(API, 'OSC->MIDI probe')
-
-except:
- ipc_send('log', '(ERROR, MIDI) python-rtmidi not found (or wrong version) (running with python %s)' % ".".join(map(str, version_info[:3])))
- ipc_send('log', '(INFO, MIDI) Get python-rtmidi at https://spotlightkid.github.io/python-rtmidi/')
- exit()
-
-if version_info.major == 3:
- raw_input = input
-
-debug = 'debug' in argv
diff --git a/src/python/requirements.txt b/src/python/requirements.txt
deleted file mode 100644
index fddc08e3..00000000
--- a/src/python/requirements.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-python-rtmidi == 1.4.2
-pyinstaller
diff --git a/src/scss/index.scss b/src/scss/index.scss
index 51608a84..6bb35dec 100644
--- a/src/scss/index.scss
+++ b/src/scss/index.scss
@@ -60,7 +60,7 @@ body {
font-family: $font;
font-size:11rem;
line-height:100%;
- font-weight: 500;
+ font-weight: 400;
// text-transform: uppercase;
letter-spacing: 1rem;
text-rendering: optimizeSpeed;
@@ -93,7 +93,7 @@ body {
.fa-osc:before {
content:"\f111";
color: transparent;
- background-image: url(../assets/favicon.png);
+ background-image: url(../assets/favicon.png?__OSC_ASSET__=1);
background-size: contain;
background-repeat: no-repeat;
}
diff --git a/src/scss/reset.scss b/src/scss/reset.scss
index d4d9a88a..286c7846 100644
--- a/src/scss/reset.scss
+++ b/src/scss/reset.scss
@@ -1,4 +1,3 @@
-
* {
margin:0;
padding:0;
@@ -14,10 +13,3 @@
-moz-user-select: none;
user-select: none;
}
-
-
-select, input, textarea {
- -webkit-appearance:none;
- -moz-appearance:none;
- appearance:none;
-}
diff --git a/src/scss/themes/default.scss b/src/scss/themes/default.scss
index 66fa786e..1001ec15 100644
--- a/src/scss/themes/default.scss
+++ b/src/scss/themes/default.scss
@@ -12,7 +12,8 @@ $font-menu: sans-serif;
--color-background: #21252b;
- --color-ui-background: #2c313a;
+ --color-ui-foreground: hsl(219, 14%, 23%);
+ --color-ui-background: hsl(217, 14%, 19%);
--color-ui-button: #{$nord1};
--color-accent: #6db5fd;
@@ -33,7 +34,6 @@ $font-menu: sans-serif;
--alpha-scrollbar: 0.25;
--alpha-scrollbar-on: 0.75;
- --scrollbar-size: 12rem;
--color-grid: rgba(0,0,0, 0.1);
--color-notification: #{rgba(black, 0.8)};
diff --git a/src/scss/themes/nord.scss b/src/scss/themes/nord.scss
index f9afb9f6..4615906e 100644
--- a/src/scss/themes/nord.scss
+++ b/src/scss/themes/nord.scss
@@ -2,6 +2,7 @@
:root {
--color-background: #{$nord0};
+ --color-ui-foreground: #{$nord2};
--color-ui-background: #{$nord1};
--color-ui-button: #{$nord3};
--color-accent: #{$nord8};
diff --git a/src/scss/themes/orange.scss b/src/scss/themes/orange.scss
index bb52f76f..712e486e 100644
--- a/src/scss/themes/orange.scss
+++ b/src/scss/themes/orange.scss
@@ -2,7 +2,8 @@
:root {
--color-background: #404040;
- --color-ui-background: #505050;
+ --color-ui-foreground: #505050;
+ --color-ui-background: #4A4A4A;
--color-ui-button: #606060;
--color-accent: #d98533;
}
diff --git a/src/scss/ui.scss b/src/scss/ui.scss
index 357868a7..107ca9d5 100644
--- a/src/scss/ui.scss
+++ b/src/scss/ui.scss
@@ -14,3 +14,4 @@
@import 'ui/loading';
@import 'ui/toolbar';
@import 'ui/launcher';
+@import 'ui/keyboard';
diff --git a/src/scss/ui/button.scss b/src/scss/ui/button.scss
index 409076c7..2f2bb9be 100644
--- a/src/scss/ui/button.scss
+++ b/src/scss/ui/button.scss
@@ -1,5 +1,6 @@
.btn {
- background: var(--color-background);
+ background: var(--color-ui-button);
+ border: 1rem solid var(--color-background);
display: block;
padding: 0 15rem;
position: relative;
@@ -7,9 +8,13 @@
text-overflow: ellipsis;
overflow: hidden;
text-align: center;
+ padding-top: 1rem;
cursor: pointer;
&.disabled {
pointer-events: none;
opacity: 0.5;
}
+ &.active {
+ color: var(--color-accent)
+ }
}
diff --git a/src/scss/ui/console.scss b/src/scss/ui/console.scss
index 8253c7f0..492f8e60 100644
--- a/src/scss/ui/console.scss
+++ b/src/scss/ui/console.scss
@@ -3,7 +3,7 @@ $padding: 8rem;
#osc-console {
background: var(--color-background);
osc-panel-header {
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
border-top: 1rem solid var(--color-background);
}
.toggle-button {
@@ -43,52 +43,72 @@ $padding: 8rem;
}
+.editor-disabled #osc-console.minimized {
+ &:after {
+ // disable hover trap
+ display: none;
+ }
+ > .toggle-button {
+ // disable toggle button
+ display: none;
+ }
+}
+
osc-console {
height: 100%;
- padding: $padding;
+ padding: $padding 0;
overflow-y: auto;
- border-bottom: 1rem solid var(--color-background);
+ border-bottom: 1rem dotted rgba(255,255,255,0.2);
user-select: text;
}
+.editor-enabled osc-console:focus {
+ outline: 1rem dotted var(--color-accent);
+ outline-offset: -1rem;
+}
+
osc-console-message {
+
user-select: text;
cursor: text;
display: block;
white-space: pre-line;
position: relative;
- padding-left: 10rem;
+ padding-left: $padding + 18rem;
+ padding-right: $padding;
+ padding-bottom: 6rem;
+ border-bottom: 1rem dotted rgba(255,255,255,0.1);
&:before {
font-family: FontAwesome;
- width: 6rem;
+ width: 12rem;
display: inline-block;
text-align: center;
position: absolute;
- left: 0;
+ left: $padding;
}
- &.log:before, &.error:before {
- content: "";
- border-left: 2rem solid;
- top: 0;
- bottom: 0;
- left: 2rem;
- opacity: 0.75;
+ &.log:before {
+ content: "\f105\f105"
}
&.error {
color: var(--color-error);
+ &:before {
+ content: "x"
+ }
}
&.input {
&:before {
- content: "\f105";
+ content: "\f105\f105";
}
}
&.output {
&:before {
- content: "\f104"
+ content: "\f104\f104"
}
&.undefined {
+ // color: var(--color-text)
opacity: 0.5;
+ border-bottom: 1rem dotted rgba(255,255,255,0.20);
}
&.value {
@@ -97,6 +117,7 @@ osc-console-message {
}
}
+
margin-bottom: 4rem;
&:last-child {
@@ -106,10 +127,11 @@ osc-console-message {
.edit-widget {
cursor: pointer;
display: inline-block;
- padding: 2rem;
+ position: relative;
+ // padding: 2rem;
border-radius: 2rem;
&.editing {
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
}
&[data-widget="CONSOLE"] {
cursor: default;
@@ -130,22 +152,22 @@ osc-console-input {
padding-left: 10rem;
&:before {
- content: "\f105";
+ content: "\f105\f105";
font-family: FontAwesome;
- width: 6rem;
+ width: 16rem;
display: inline-block;
text-align: center;
position: absolute;
left: 0;
- line-height: $field-height - 8rem;
+ line-height: $field-height - 6rem;
padding: 4rem 6rem;
color: var(--color-accent);
}
textarea {
font-family: $font-mono;
- line-height: $field-height - 8rem;
- padding: 4rem 6rem;
+ line-height: $field-height - 6rem;
+ padding: 4rem 16rem;
flex: 1;
overflow-x: auto;
overflow-y: hidden;
diff --git a/src/scss/ui/dragresize.scss b/src/scss/ui/dragresize.scss
index 2c427dc0..2710ce16 100644
--- a/src/scss/ui/dragresize.scss
+++ b/src/scss/ui/dragresize.scss
@@ -40,6 +40,10 @@
display: block;
}
+ &.copying {
+ --color-accent: var(--color-warning);
+ }
+
.handle {
$size: 10rem;
diff --git a/src/scss/ui/filebrowser.scss b/src/scss/ui/filebrowser.scss
index b04a1f42..13884578 100644
--- a/src/scss/ui/filebrowser.scss
+++ b/src/scss/ui/filebrowser.scss
@@ -4,15 +4,18 @@ $padding: 8rem;
display: flex;
flex-direction: column;
flex: 1;
-
+ overflow: hidden;
.ariane {
height: 40rem;
flex-shrink: 0;
line-height: 40rem;
padding-left: $padding + 2rem;
+ padding-right: $padding + 2rem;
background: var(--color-ui-button);
-
+ overflow-x: auto;
+ overflow-y: hidden;
+ --scrollbar-size: 4rem;
}
.file-list {
overflow-y: auto;
@@ -66,9 +69,9 @@ $padding: 8rem;
height: 42rem + $padding * 2;
line-height: 38rem;
flex-shrink: 0;
- // border: $padding solid var(--color-ui-background);
+ // border: $padding solid var(--color-ui-foreground);
padding: $padding;
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
.btn {
margin: 1rem;
margin-left: $padding;
diff --git a/src/scss/ui/inspector.scss b/src/scss/ui/inspector.scss
index 09a000e5..e668e72d 100644
--- a/src/scss/ui/inspector.scss
+++ b/src/scss/ui/inspector.scss
@@ -1,37 +1,216 @@
$header-height: 28rem;
$field-height: 24rem;
+$label-width: 94rem;
$padding: 8rem;
+$radius: 3rem;
+
+osc-panel-container.right.editor-breakout {
+ osc-panel-inner {
+ contain: initial;
+ }
+ .resize-handle {
+ display: none;
+ }
+}
#osc-inspector {
+ select, input, textarea {
+ -webkit-appearance:none;
+ -moz-appearance:none;
+ appearance:none;
+ -webkit-user-select: auto;
+ -moz-user-select: auto;
+ user-select: auto;
+ }
+
+
--widget-padding: -1rem;
+ .lock {
+ osc-inspector-field {
+ filter: saturate(0);
+ pointer-events: none;
+ opacity: 0.65;
+ }
+ osc-inspector-field[name=lock] {
+ filter: none;
+ pointer-events: auto;
+ opacity: 1.0;
+ }
+ }
+
+ .toolbar {
+ display: flex;
+ flex-direction: row;
+ padding: $padding / 2;
+ height: 46rem;
+ position: relative;
+ top:0;
+ z-index: 21;
+ background: var(--color-ui-background);
+ border-bottom:1rem solid var(--color-background);
+ .btn {
+ margin: $padding / 2;
+ padding: 0 8rem 1rem;
+ align-items: center;
+ justify-content: center;
+ display: flex;
+ span{
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ i {
+ pointer-events: none;
+ }
+ &[data-action="toggle-grid"] {
+ color: var(--color-accent)
+ }
+ &[data-action="reset-selection"] i:after {
+ content: "";
+ position: absolute;
+ border-left: 1.5rem solid;
+ left: 50%;
+ top: 50%;
+ margin-top: -8rem;
+ margin-left: -1rem;
+ height: 16rem;
+ transform: rotate(45deg);
+ }
+ }
+ [data-action="selected-id"] {
+ flex: 1;
+ cursor: default;
+ }
+ }
+
+ overflow: hidden;
+ > .content {
+ overflow: auto;
+ flex:1;
+ height: calc(100% - 46rem);
+ box-shadow: 0 1rem 0 0 inset rgba(white, 0.025);
+
+ }
+
}
+body.no-grid #osc-inspector .toolbar .btn[data-action="toggle-grid"] {
+ color: inherit;
+}
+
+
+
osc-inspector-field {
display: flex;
flex-direction: row;
line-height: $field-height;
- margin-top: 2rem;
+ margin-top: -1rem;
position: relative;
+ &:after {
+ content:"";
+ position: absolute;
+ left:$label-width;
+ top:0;
+ right: 1rem;
+ border-top:1rem solid var(--color-ui-background);
+ z-index: 1;
+ // opacity: 0.5;
+ }
+
--widget-padding: -1rem;
-
- label {
- width: 90rem;
- // order: 35;
- text-align: right;
+ > label {
+ width: $label-width;
text-transform: none;
- padding-right: 8rem;
- line-height: $field-height + 1rem;
+ padding-left: 4rem;
+ padding-right: 4rem;
+ line-height: $field-height;
height: $field-height;
- cursor: help;
- // background: rgba(white, 0.1);
+ cursor: pointer;
+ background: var(--color-ui-foreground);
+ border:1rem solid var(--color-background);
+ border-right: none;
+ border-top-left-radius: inherit;
+ border-bottom-left-radius: inherit;
}
- textarea, input {
+ &.has-editor {
+
+ flex-direction: column;
+ height: auto;
+ border-radius: $radius;
+
+ > label {
+ border:1rem solid var(--color-background);
+ border-bottom: none;
+ width: 100%;
+ position: relative;
+ border-top-left-radius: inherit;
+ border-top-right-radius: inherit;
+ border-bottom-left-radius: 0;
+ border-bottom-right-radius: 0;
+ }
+ .btn {
+ position: absolute;
+ top:3rem;
+ background: var(--color-ui-button);
+ line-height: $field-height - 6;
+ box-shadow: 0 0 1rem 0 var(--color-background);
+ border: 0;
+ }
+ .fullscreen {
+ right:3rem;
+ width: 24rem;
+ padding-left: 0;
+ padding-right: 0;
+ border-top-right-radius: inherit;
+ }
+ .help {
+ right:30rem;
+ }
+ &:after {
+ content:none;
+ }
+
+ &.fullscreen {
+ position: fixed;
+ width:auto;
+ height: auto;
+ top:0;
+ left:0;
+ right:0;
+ bottom:0;
+ padding: 50rem;
+ margin: 0;
+ z-index: 99;
+ background: rgba(black, 0.3);
+ > label:before {
+ content: var(--prefix);
+ }
+ &.dirty label:after{
+ content: "*"
+ }
+ .btn {
+ margin-top: 50rem;
+ margin-right: 50rem;
+ &.fullscreen {
+ color: var(--color-accent);
+ }
+ }
+ .ace_editor {
+ height: 100%!important;
+ }
+ }
+ }
+ .ace_editor {
+ min-height: $field-height;
+ border-bottom-left-radius: inherit;
+ border-bottom-right-radius: inherit;
+ }
+ > textarea, > input {
font-family: $font-mono;
line-height: $field-height - 8rem;
@@ -45,16 +224,14 @@ osc-inspector-field {
background: var(--color-background);
cursor: text;
- user-select: initial;
-
- --scrollbar-size: 6rem;
-
- // Chromium scrollbar
- &::-webkit-scrollbar-thumb:horizontal {
- cursor: normal;
+ &:last-child{
+ border-top-right-radius: inherit;
+ border-bottom-right-radius: inherit;
}
- // Firefox scrollbar (hidden to preserve height)
+ user-select: initial;
+
+ // hide scrollbar to preserve height
scrollbar-width: thin;
&[rows="1"] {
scrollbar-width: none;
@@ -76,6 +253,176 @@ osc-inspector-field {
}
+osc-inspector-field .ace_editor {
+
+ color: var(--color-text);
+ font-size: inherit;
+ background: var(--color-background);
+ line-height: 1.3;
+ border: 1rem solid var(--color-background);
+
+ .ace_gutter {
+ background: var(--color-background);
+ color: #6a6f7a;
+ border-right: 1rem solid var(--color-ui-background);
+ line-height: 1.5
+ }
+ .ace_print-margin {
+ display: none;
+ }
+ .ace_mobile-menu {
+ display: none;
+ }
+
+ .ace_cursor {
+ color: var(--color-accent);
+ border-right-width: 2rem;
+ }
+ .ace_hidden-cursors .ace_cursor {
+ opacity: 0;
+ }
+ .ace_marker-layer .ace_selection {
+ background: #3d4350
+ }
+ .ace_multiselect .ace_selection.ace_start {
+ box-shadow: 0 0 3rem 0 #282c34;
+ border-radius: 2rem
+ }
+ .ace_marker-layer .ace_step {
+ background: #c6dbae
+ }
+ .ace_marker-layer .ace_bracket {
+ border: none;
+ border-radius: 0;
+ margin-top: 1rem;
+ border-bottom: 1rem solid var(--color-accent)
+ }
+ .ace_marker-layer .ace_active-line {
+ background: rgba(white, 0.05);
+ }
+ .ace_gutter-active-line {
+ background-color: rgba(white, 0.05);
+ z-index: 99
+ }
+ .ace_marker-layer .ace_selected-word {
+ border: none;
+ border-bottom: 1rem solid rgba(white, 0.2);
+ background: none;
+ }
+ .ace_fold {
+ background-color: #61afef;
+ border-color: #abb2bf
+ }
+ .ace_keyword {
+ color: #c678dd
+ }
+ .ace_keyword.ace_operator {
+ color: #c678dd
+ }
+ .ace_keyword.ace_other.ace_unit {
+ color: #d19a66
+ }
+ .ace_constant.ace_language {
+ color: #d19a66
+ }
+ .ace_constant.ace_numeric {
+ color: #d19a66
+ }
+ .ace_constant.ace_character {
+ color: #56b6c2
+ }
+ .ace_constant.ace_other {
+ color: #56b6c2
+ }
+ .ace_support.ace_function {
+ color: #61afef
+ }
+ .ace_support.ace_constant {
+ color: #d19a66
+ }
+ .ace_support.ace_class {
+ color: #e5c07b
+ }
+ .ace_support.ace_type {
+ color: #e5c07b
+ }
+ .ace_storage {
+ color: #c678dd
+ }
+ .ace_storage.ace_type {
+ color: #c678dd
+ }
+ .ace_invalid {
+ color: #fff;
+ background-color: #f2777a
+ }
+ .ace_invalid.ace_deprecated {
+ color: #272b33;
+ background-color: #d27b53
+ }
+ .ace_string {
+ color: #98c379
+ }
+ .ace_string.ace_regexp {
+ color: #e06c75
+ }
+ .ace_comment {
+ font-style: italic;
+ color: #5c6370
+ }
+ .ace_variable {
+ color: #e06c75
+ }
+ .ace_variable.ace_parameter {
+ color: #d19a66
+ }
+ .ace_meta.ace_tag {
+ color: #e06c75
+ }
+ .ace_entity.ace_other.ace_attribute-name {
+ color: #e06c75
+ }
+ .ace_entity.ace_name.ace_function {
+ color: #61afef
+ }
+ .ace_entity.ace_name.ace_tag {
+ color: #e06c75
+ }
+ .ace_markup.ace_heading {
+ color: #98c379
+ }
+ .ace_indent-guide {
+ background: none;
+ border-right: 1rem solid rgba(white, 0.05);
+ margin-left: -1rem;
+ }
+ .ace_tooltip {
+ left:$padding + 1!important;
+ max-width: 80%;
+ white-space: pre-wrap;
+ background: var(--color-context-menu);
+ color: var(--color-context-menu-text);
+ font-family: $font;
+ box-shadow: 0 0 0 0.5rem rgba(0, 0, 0, 0.15) inset;
+ border: none;
+ border-radius: 0;
+ }
+ .ace_gutter {
+ .ace_info {
+ background: linear-gradient(rgba(black, 0.5), rgba(black, 0.5)), var(--color-text)!important;
+ color: var(--color-background);
+ }
+ .ace_warning {
+ background: linear-gradient(rgba(black, 0.5), rgba(black, 0.5)), var(--color-warning);
+ color: var(--color-background);
+ }
+ .ace_error {
+ background: linear-gradient(rgba(black, 0.4), rgba(black, 0.4)), var(--color-error);
+ color: var(--color-background);
+ }
+ }
+}
+
osc-inspector-category {
@@ -91,10 +438,13 @@ osc-inspector-category {
position: relative;
cursor: pointer;
height: $header-height;
- line-height: $header-height;
+ line-height: $header-height - 1;
// padding: 0 8rem;
+ // position: sticky;
+ // top:46rem;z-index: 20;
+ // background: var(--color-ui-background);
+ font-weight: 500;
@include pseudo-fill($z: -1);
-
&:after {
left:-($padding - 1);
right:-($padding - 1);
@@ -110,23 +460,45 @@ osc-inspector-category {
transform-origin: 2rem 3rem;
width: 8rem;
margin-right: 8rem;
+ top:1rem;
+ }
+
+ &:focus, &:active {
+ text-decoration: underline
}
}
.separator {
height: $header-height;
- line-height: $header-height + 1;
- margin: 8rem 0;
- --alpha-fill: 0.75;
+ line-height: $header-height - 1;
+ margin: $padding 0;
position: relative;
- @include pseudo-fill($z: -1);
- padding: 0 16rem;
- opacity: 0.75;
- --color-fill: var(--color-background);
+ padding: 0 ($padding - 4);
+ font-weight: 500;
+ &:before {
+ position: relative;
+ font-family: FontAwesome;
+ content: "\f078";
+ // color: var(--color-background);
+ width: $field-height;
+ text-align: left;
+ display: inline-block;
+ transform-origin: 2rem 3rem;
+ width: 8rem;
+ margin-right: 12rem;
+ top: 1rem;
+ }
&:after {
- left:-($padding - 1);
- right:-($padding - 1);
+ content: "";
+ position: absolute;
+ height: 100%;
+ left:-($padding);
+ right:-($padding);
+ background: var(--color-ui-foreground);
+ border-top:1rem solid var(--color-background);
+ border-bottom:1rem solid var(--color-background);
+ z-index: -1;
}
}
@@ -152,18 +524,40 @@ osc-inspector-category {
}
}
+ osc-inspector-field.first-child,
.category-header + osc-inspector-field {
- margin-top: 8rem;
+ margin-top: $padding + 1;
+ &:after {
+ content: none;
+ }
+ osc-inspector-checkbox {
+ border-top: 0;
+ }
+ osc-inspector-color:after {
+ top:0;
+ }
+ border-top-left-radius: $radius;
+ border-top-right-radius: $radius;
+ .color-picker {
+ margin-top: 2rem;
+ }
}
+ osc-inspector-field.last-child,
osc-inspector-field:last-child {
margin-bottom: 8rem;
+
+ osc-inspector-checkbox {
+ border-bottom: none;
+ }
+
+ border-bottom-left-radius: $radius;
+ border-bottom-right-radius: $radius;
}
}
-
osc-inspector-checkbox {
- --widget-padding: 0;
+ --widget-padding: 1rem;
--color-fill: var(--color-ui-button);
--alpha-fill: 1;
@@ -176,7 +570,11 @@ osc-inspector-checkbox {
display: flex;
align-items: center;
justify-content: center;
- border: 1rem solid var(--color-background);
+ border-top: 1rem solid var(--color-background);
+ border-bottom: 1rem solid var(--color-background);
+ border-top-right-radius: inherit;
+ border-bottom-right-radius: inherit;
+
i {
// color: transparent;
opacity: 0.5;
@@ -223,14 +621,14 @@ osc-inspector-select {
width: 127rem;
opacity: 0;
optgroup {
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
font-weight: bold;
option {
background: var(--color-background);
color: var(--color-text);
margin-left: -4rem;
font-weight: normal;
- text-indent: -10px;
+ text-indent: -10rem;
margin: 0;
}
}
@@ -263,6 +661,8 @@ osc-inspector-color {
height: $field-height;
width: $field-height;
background: var(--color-background);
+ border-top-right-radius: inherit;
+ border-bottom-right-radius: inherit;
cursor: pointer;
@@ -270,45 +670,53 @@ osc-inspector-color {
--color-fill: var(--color-picker-value);
--alpha-fill: 1;
- --widget-padding: 1rem;
+ --widget-padding: 2rem;
@include pseudo-fill();
&:after {
- border: 1rem solid var(--color-ui-button)
+ border: 1rem solid var(--color-ui-button);
+ right: 0;
+ left: 0;
}
}
-.color-picker-modal {
-
- flex: 1;
+.color-picker {
+ position: absolute;
+ z-index: 99;
+ height: calc(var(--sidepanel-size) - #{$label-width} - #{$field-height * 2});
+ min-height: 111rem;
+ max-height: 227rem;
+ top: 0;
+ right: 22rem;
+ left: $label-width;
+ margin: 3rem 2rem;
display: flex;
flex-direction: column;
-
+ $padding: 2rem;
+ border: 1rem solid var(--color-ui-button);
+ overflow: hidden;
+ --point-size: 10rem;
.widget {
- background: var(--color-background);
+ background: var(--color-ui-background);
flex: 1;
width: auto;
- --widget-padding: #{$padding};
- }
-
- .actions {
- display: flex;
- flex-direction: row;
- align-items: flex-end;
- justify-content: stretch;
- height: 42rem + $padding * 2;
- line-height: 38rem;
- flex-shrink: 0;
- background: var(--color-ui-background);
- padding: $padding;
- .btn {
- flex: 1;
- text-overflow: clip;
- min-width: 0;
- background: var(--color-ui-button);
- margin-right: $padding;
- &:last-child {
- margin: 0;
- }
+ --widget-padding: 0rem;
+ inner {
+ padding: 1rem;
+ }
+ .hue {
+ margin-left: 1rem;
+ width: 16rem;
+ --knob-size: 1rem;
+ }
+ .alpha {
+ margin-top: 0.5rem;
+ left:0;
+ margin-left: 0;
+ border:0;
+ }
+ .hue:after {
+ left:0;
+ right:0;
}
}
@@ -319,6 +727,7 @@ osc-inspector-color {
width: 100%;
padding: 8rem;
background: var(--color-background);
+ overflow: auto;
p {
}
@@ -356,7 +765,7 @@ osc-inspector-color {
user-select: text;
}
.description {
- border-top: 2rem solid var(--color-ui-background);
+ border-top: 2rem solid var(--color-ui-foreground);
margin-top: 10rem;
padding-top: 10rem;
white-space: normal;
@@ -366,9 +775,36 @@ osc-inspector-color {
}
.computed {
- border-top: 2rem solid var(--color-ui-background);
+ border-top: 2rem solid var(--color-ui-foreground);
margin-top: 10rem;
padding-top: 10rem;
}
+
+ .kbd {
+ background: var(--color-ui-button);
+ padding: 4rem;
+ display: inline-block;
+ margin-bottom: 2rem;
+ }
+
+ thead tr {
+ text-align: left;
+ font-weight: 500;
+ height: 30rem;
+ }
+}
+
+
+.editor-enabled.local-zoom-in .root-container,
+.editor-enabled.local-zoom-out .root-container {
+ transform-origin: top left;
+ transform: scale(var(--local-zoom));
+ min-width: calc(100% / var(--local-zoom));
+ min-height: calc(100% / var(--local-zoom));
+}
+
+.editor-enabled.local-zoom-out .root-container.auto-height{
+ transform-origin: center left;
+
}
diff --git a/src/scss/ui/keyboard.scss b/src/scss/ui/keyboard.scss
new file mode 100644
index 00000000..fd188868
--- /dev/null
+++ b/src/scss/ui/keyboard.scss
@@ -0,0 +1,185 @@
+osc-keyboard {
+ --spacing: 2rem;
+ --max-height: 300rem;
+ --max-width: 1200rem;
+
+ height:calc(33% + 40rem);
+ z-index: 100;
+ position: fixed;
+ bottom: 0;
+ left:0;
+ right: 0;
+ backdrop-filter: blur(12px);
+ @supports not (backdrop-filter: blur(12px)) {
+ background: var(--color-ui-background);
+ }
+ display: none;
+ flex-direction: column;
+ padding: var(--spacing);
+ align-items: center;
+ background: rgba(black, 0.25);
+ max-height: var(--max-height);
+ border-top: 1rem solid var(--color-background);
+
+ @keyframes keyboard-in {
+ from {opacity: 0}
+ to {opacity: 1}
+ }
+ @keyframes caret-blink {
+ to {visibility: hidden}
+ }
+
+ animation: keyboard-in 0.25s forwards;
+
+ .textarea {
+ height: auto;
+ overflow-y: auto;
+ width: 100%;
+ height: 40rem;
+ background: transparent;
+ padding: 14rem 20rem 4rem;
+ resize: none;
+ text-align: center;
+ vertical-align: middle;
+ font: inherit;
+ margin-top:var(---spacing);
+ position: relative;
+ pointer-events: auto;
+ cursor: text;
+ char {
+ margin: 0 0.25rem;
+ position: relative;
+ }
+ .newline + char:before, char:first-child:before {
+ content: " ";
+ display: block;
+ position: absolute;
+ left: -100rem;
+ width: 100rem;
+ }
+ .newline:before, char:last-child:before {
+ content: " ";
+ display: block;
+ position: absolute;
+ top: 0;
+ right: -100rem;
+ width: 100rem;
+ }
+ .caret {
+ &:after {
+ content: "";
+ height: 10rem;
+ box-shadow: 0 0 0 1rem var(--color-accent);
+ position: relative;
+ animation: caret-blink 1.2s steps(2, start) infinite;
+ pointer-events: none;
+ }
+
+ }
+ .select {
+ background: var(--color-accent);
+ box-shadow: 0 0 0 1rem var(--color-accent);
+ color: var(--color-background);
+ }
+ &.first-char-caret {
+ &:before {
+ content: "";
+ height: 10rem;
+ position: absolute;
+ box-shadow: 0 0 0 1rem var(--color-accent);
+ animation: caret-blink 1.2s steps(2, start) infinite;
+ }
+ }
+ }
+
+ .row {
+ flex-direction: row;
+ display: flex;
+ flex: 1;
+ max-width: var(--max-width);
+ width: 100%;
+ &:last-child .key {
+ margin-bottom: 0;
+ }
+ &:first-child {
+ height: 40rem;
+ min-height: 40rem;
+ flex-shrink: 0;
+ overflow: hidden;
+ margin-bottom: var(--spacing);
+ }
+ }
+ key {
+ background: rgba(white, 0.05);
+ border-color: var(--color-ui-background);
+ flex: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ --alpha-fill: 0.1;
+ --color-fill: var(--color-accent);
+ --widget-padding: -1rem;
+ @include pseudo-fill($z: 1);
+ margin-right: var(--spacing);
+ margin-bottom: var(--spacing);
+ &:last-child{
+ margin-right: 0;
+ }
+ span {
+ pointer-events: none;
+ align-items: center;
+ justify-content: center;
+ &.display-default {
+ display: flex;
+ }
+ &.display-shift {
+ display: none;
+ }
+ }
+
+ &.active {
+ --alpha-fill: 0.3!important;
+ }
+ }
+
+ .enter {
+ --alpha-fill: 0.15;
+ }
+
+ .tab, .shift {
+ flex: 1.5;
+ }
+
+ .enter, .right-shift, .lock, .bksp {
+ flex: 2;
+ }
+
+ .sep {
+ display: none;
+ }
+ .sep ~ key {
+ flex-shrink: 0;
+ flex-grow: 0;
+ min-width: 5%;
+ --alpha-fill: 0.15;
+
+ }
+
+ &.shift {
+ key {
+ .display-shift {
+ display: flex;
+ }
+ .display-default {
+ display: none;
+ }
+ }
+ }
+ @media screen and (max-width: 800px) {
+ key {
+ font-size: 80%
+ }
+ }
+
+}
diff --git a/src/scss/ui/launcher.scss b/src/scss/ui/launcher.scss
index 1a6ab0bd..78b05ee2 100644
--- a/src/scss/ui/launcher.scss
+++ b/src/scss/ui/launcher.scss
@@ -1,7 +1,7 @@
#osc-launcher {
osc-panel-header {
- background-color: var(--color-ui-background);
+ background-color: var(--color-ui-foreground);
--alpha-fill: .75;
text-align: left;
justify-content: center;
@@ -19,12 +19,12 @@
flex-direction: column;
osc-panel-container.main {
- background-color: var(--color-ui-background);
+ background-color: var(--color-ui-foreground);
min-height: 0;
min-height: 40rem;
osc-panel-content {
padding: 8rem;
- background-color: var(--color-ui-background);
+ background-color: var(--color-ui-foreground);
}
}
osc-panel-content {
@@ -41,14 +41,14 @@
padding: 0;
}
- border-top: 2rem solid var(--color-ui-background);
+ border-top: 2rem solid var(--color-ui-foreground);
max-height: calc(100% - var(--nav-height));
background-color: var(--color-background);
osc-panel-inner {
background-color: var(--color-background);
}
- // --color-background: --color-ui-background; // scrollbar
+ // --color-background: --color-ui-foreground; // scrollbar
}
osc-panel-inner {
@@ -66,16 +66,47 @@ osc-settings {
osc-settings-field {
display: flex;
flex-direction: row;
- margin: 1rem;
+ // margin: 1rem;
+ margin-top:-1rem;
line-height: 22rem;
position: relative;
+ &:after {
+ content:"";
+ position: absolute;
+ left:100rem;
+ top:0;
+ right: 0;
+ border-top:1rem solid var(--color-ui-foreground);
+ z-index: 11;
+ }
+ &:nth-child(2n) {
+ margin-left: 8rem;
+ }
+ &:nth-child(2), &:nth-child(1) {
+ margin-top:0;
+ osc-settings-checkbox, osc-settings-reset, osc-settings-file {
+ border-top: 0;
+ }
+ &:after {
+ content: none;
+ }
+ }
+ &:nth-last-child(2), &:nth-last-child(1) {
+ osc-settings-checkbox, osc-settings-reset, osc-settings-file {
+ border-bottom: 0;
+ }
+ }
label {
width: 100rem;
- text-align: right;
- margin-right: 8rem;
+ // text-align: right;
+ background: var(--color-ui-background);
+ border:1rem solid var(--color-background);
+ border-right: none;
+ // margin-right: 8rem;
+ padding: 0 4rem;
position: relative;
- line-height: 24rem;
- height: 22rem;
+ line-height: 22rem;
+ height: 24rem;
cursor: help;
span {
opacity: 0.5;
@@ -140,7 +171,7 @@ osc-settings-checkbox, osc-settings-reset, osc-settings-file {
cursor: auto;
> div {
- margin: 0 12rem 4rem;
+ margin: 0 12rem;
}
@@ -149,7 +180,9 @@ osc-settings-checkbox, osc-settings-reset, osc-settings-file {
cursor: auto;
white-space: pre-wrap;
}
-
+ .log span {
+ background: transparent!important
+ }
.help {
font-style: italic;
color: var(--color-accent);
@@ -187,6 +220,18 @@ osc-settings-checkbox, osc-settings-reset, osc-settings-file {
user-select: none;
}
+ .qrcode svg {
+ width: 120rem;
+ margin-top: 5rem;
+ margin-left: 15rem;
+ path[fill="#ffffff"] {
+ fill: var(--color-text)!important;
+ }
+ path[stroke="#000000"] {
+ stroke: var(--color-background)!important;
+ }
+ }
+
a {
text-decoration: underline;
cursor: pointer;
diff --git a/src/scss/ui/loading.scss b/src/scss/ui/loading.scss
index ed10dc4b..4623731c 100644
--- a/src/scss/ui/loading.scss
+++ b/src/scss/ui/loading.scss
@@ -25,7 +25,7 @@
top:-3rem;
right:-3rem;
bottom:-3rem;
- border:4rem solid var(--color-ui-background);
+ border:4rem solid var(--color-ui-foreground);
border-top: 2rem solid var(--color-widget);
transform: rotateZ(0deg);
animation: spin .5s linear infinite;
diff --git a/src/scss/ui/modal.scss b/src/scss/ui/modal.scss
index 582e0c45..014a925e 100644
--- a/src/scss/ui/modal.scss
+++ b/src/scss/ui/modal.scss
@@ -46,7 +46,7 @@ $padding: 8rem;
display: flex;
padding:0 $padding * 2 - 1;
align-items: center;
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
.title {
flex:1;
overflow: hidden;
diff --git a/src/scss/ui/scrollbars.scss b/src/scss/ui/scrollbars.scss
index ce14aa62..1bf8f473 100644
--- a/src/scss/ui/scrollbars.scss
+++ b/src/scss/ui/scrollbars.scss
@@ -1,47 +1,3 @@
-// Chromium
-
-::-webkit-scrollbar {
- width: var(--scrollbar-size);
- height:var(--scrollbar-size);
-}
-
-::-webkit-scrollbar-track-piece {
- background: var(--color-background);
- &:vertical {
- border-left: 1rem solid var(--color-background);
- }
- &:horizontal {
- border-top: 1rem solid var(--color-background);
- }
-}
-
-::-webkit-scrollbar-thumb {
- background: var(--color-scrollbar);
- &:active {
- background: var(--color-scrollbar-on);
- }
- &:vertical {
- border-left: 1rem solid var(--color-background);
- }
- &:horizontal {
- border-top: 1rem solid var(--color-background);
- }
-}
-
-::-webkit-scrollbar-button:decrement:start, ::-webkit-scrollbar-button:increment:end {
- height: 0;
- width: 0;
-}
-
-::-webkit-scrollbar-corner {
- height: 0rem;
- width: 0rem;
- background: var(--color-background);
-}
-
-
-// Firefox
-
* {
scrollbar-color: var(--color-scrollbar) var(--color-background);
scrollbar-width: normal;
diff --git a/src/scss/ui/selectarea.scss b/src/scss/ui/selectarea.scss
index ff1bd1df..7d5f0ea6 100644
--- a/src/scss/ui/selectarea.scss
+++ b/src/scss/ui/selectarea.scss
@@ -41,3 +41,32 @@
box-shadow: none!important;
opacity: 1!important;
}
+
+
+
+.widget.editing.editor-blink:after,
+.modal-container.editing.editor-blink > .popup > .popup-wrapper:after {
+ display: block!important;
+ -webkit-mask-image: none;
+ mask-image: none;
+ background-color: var(--color-accent);
+ opacity: 0.5!important;
+ animation: editor-blink 0.51s steps(3) infinite;
+}
+
+@keyframes editor-blink {
+ from {--color-accent: var(--color-warning)}
+ to {--color-accent: transparent}
+}
+
+
+.editor-hide-selection {
+ #drag-resize {
+ display: none;
+ }
+ .widget.editing:after,
+ .tablink.editing:after,
+ .modal-container.editing > .popup > .popup-wrapper:after {
+ display: none;
+ }
+}
diff --git a/src/scss/ui/toolbar.scss b/src/scss/ui/toolbar.scss
index 0c051e61..802a0ece 100644
--- a/src/scss/ui/toolbar.scss
+++ b/src/scss/ui/toolbar.scss
@@ -2,7 +2,7 @@ osc-toolbar {
--size: 34rem;
position: absolute;
top: 0;
- left: 0;
+ left: -1rem;
height:var(--size);
width:var(--size);
max-width:var(--size);
diff --git a/src/scss/ui/tree.scss b/src/scss/ui/tree.scss
index 29aaca88..3acb8b0d 100644
--- a/src/scss/ui/tree.scss
+++ b/src/scss/ui/tree.scss
@@ -3,20 +3,43 @@
--alpha-fill: 0.5;
--widget-padding: -1rem;
- $padding: 16rem;
+ $padding: 8rem;
+ $radius: 3rem;
$line-height: 28rem;
- padding: 0 $padding;
-
+ $field-height: 30rem;
+ padding-right: 0;
text-transform: none;
line-height: $line-height;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+
+ .tree {
+ width: 100%;
+ flex: 1;
+ position: relative;
+ overflow: auto;
+ padding-left:$padding + 4rem;
+ padding-right:$padding;
+ border-top:1rem solid var(--color-background);
+ box-shadow: 0 1rem 0 0 inset rgba(white, 0.025);
+ padding-top:1rem;
+
+ &::-webkit-scrollbar-thumb, &::-webkit-scrollbar-track-piece {
+ border-color: var(--color-background)!important;
+ }
+
+ }
ol {
list-style: none;
position: relative;
padding-left: 16rem;
+ display: inline-block;
+ min-width: 100%;
ol:before {
content: "";
@@ -34,10 +57,40 @@
position: relative;user-select: none;
> ol {
- display: none;
+ // display: none;
+ display: block;
+ height: 0rem;
+
+ > li {
+ display: none;
+ }
}
&.expanded > ol {
display: block;
+ // min-height: 8rem;
+ opacity: 1;
+ height: auto;
+ > li {
+ display: list-item;
+ }
+
+ }
+
+ &.sortable-ghost {
+ height: 2rem;
+ margin-bottom: 6rem;
+ margin-top: 4rem;
+ color: transparent;
+ overflow: hidden;
+ display: list-item!important
+ }
+
+ > i {
+ position: relative;
+ top: 1rem;
+ left: -2rem;
+ margin-right: 2rem;
+ pointer-events: none;
}
li:before {
@@ -66,6 +119,13 @@
// right: -12rem;
// }
}
+ .fa-lock {
+ position: relative;
+ margin-left: 4rem;
+ top:0;
+ font-size: 80%;
+ opacity: 0.8;
+ }
}
@@ -91,25 +151,64 @@
z-index: 1;
@include pseudo-fill($z: -1);
&:after {
- left: calc(-1 * var(--depth) * 16rem - #{$padding});
- right: -($padding - 1);
+ left: calc(-1 * var(--depth) * 20rem - #{$padding});
+ right: 1rem - $padding;
bottom: auto;
height: $line-height;
top: 0;
}
+ &.editor-blink:after {
+ animation: tree-editor-blink 0.51s steps(3) infinite;
+ }
+ @keyframes tree-editor-blink {
+ from {--color-fill: var(--color-warning)}
+ to {--color-fill: inherit}
+ }
}
.contains-editing:not(.expanded):not(.editing) {
z-index: 1;
@include pseudo-fill($z: -1);
&:after {
- left: calc(-1 * var(--depth) * 16rem - #{$padding});
- right: -($padding - 1);
+ left: calc(-1 * var(--depth) * 20rem - #{$padding});
+ right: 1rem - $padding;
bottom: auto;
height: $line-height;
opacity: 0.1;
}
}
+
+ .filter {
+ display: block;
+ font-family: $font;
+ // line-height: $field-height;
+ padding: 0 $padding;
+ top: 0;
+ z-index: 2;
+ background: var(--color-background);
+ border: 1rem solid var(--color-background);
+ margin: $padding;
+ border-radius: $radius;
+ }
+
+ .filter-active .filter-hide {
+ display:none;
+ }
+
+ .fragment-mode-warning {
+ color: var(--color-warning);
+ padding: 0 $padding;
+ text-align: center;
+ line-height: $field-height;
+ background: var(--color-ui-foreground);
+ border-bottom: 1rem solid var(--color-background);
+ display: none;
+ }
+
+}
+
+.fragment-mode .fragment-mode-warning {
+ display: block!important;
}
diff --git a/src/scss/ui/workspaces.scss b/src/scss/ui/workspaces.scss
index fdeccc55..7db8b4c0 100644
--- a/src/scss/ui/workspaces.scss
+++ b/src/scss/ui/workspaces.scss
@@ -1,6 +1,6 @@
osc-workspace {
- background: var(--color-ui-background);
+ background: var(--color-ui-foreground);
--color-fill: var(--color-widget);
--color-stroke: var(--color-widget);
@@ -26,6 +26,8 @@ osc-workspace {
osc-panel-container {
+ background: var(--color-ui-background);
+
position: relative;
display:flex;
flex-direction: column;
@@ -64,7 +66,7 @@ osc-panel-container {
}
::-webkit-scrollbar-thumb, ::-webkit-scrollbar-track-piece {
- border-color: var(--color-ui-background)!important;
+ border-color: var(--color-ui-foreground)!important;
}
}
@@ -252,10 +254,18 @@ osc-panel-container {
}
}
+ &.disabled {
+ pointer-events: none;
+ }
+
&.disabled .toggle-button {
display: none;
}
+ &.minimized osc-panel-inner {
+ display: none;
+ }
+
}
osc-modal-container {
@@ -286,7 +296,7 @@ osc-panel-inner {
// opacity: 0;
// }
// 100% {
-// tranform: scaleX(1);
+// transform: scaleX(1);
// opacity: var(--alpha-fill);
// }
// }
@@ -298,7 +308,7 @@ osc-panel-inner {
osc-panel-header {
- --alpha-fill: 0.25;
+ --alpha-fill: 0.5;
display: flex;
height: var(--nav-height);
@@ -308,19 +318,21 @@ osc-panel-header {
position:relative;
letter-spacing: 1rem;
font-size: 109%;
+ font-weight: 500;
text-overflow: ellipsis;
padding: 0 8rem;
flex-shrink: 0;
+ background: var(--color-ui-foreground);
&:before {
content: "";
position: absolute;
left: 0rem;
right: 0rem;
- bottom: 1rem;
- opacity: var(--alpha-fill);
- height: 2rem;
- background: var(--color-fill);
+ bottom: 0rem;
+ // opacity: var(--alpha-fill);
+ height: 1rem;
+ background: var(--color-background);
z-index: 101;
}
@@ -328,12 +340,13 @@ osc-panel-header {
osc-panel-content {
+
flex: 1;
overflow-y: auto;
&.left, &.right {
&::-webkit-scrollbar-thumb, &::-webkit-scrollbar-track-piece {
- border-right: 1rem solid var(--color-ui-background);
+ border-right: 1rem solid var(--color-ui-foreground);
}
}
@@ -343,6 +356,7 @@ osc-panel-content {
#main {
flex: 1;
min-height: 40rem;
+ contain: strict;
}
#osc-greeting-header {
@@ -361,11 +375,10 @@ osc-panel-content {
left:0;
right:0;
bottom:0;
- background: rgba(black, 0.5);
+ background: rgba(black, 0.35);
}
}
- border-bottom:1rem solid var(--color-background);
&:before {
bottom: 0;
}
diff --git a/src/scss/widgets.scss b/src/scss/widgets.scss
index 967bbfa9..01c432b0 100644
--- a/src/scss/widgets.scss
+++ b/src/scss/widgets.scss
@@ -1,4 +1,5 @@
.widget {
+ font-weight: 500;
overflow: hidden;
position:relative;
@@ -36,6 +37,9 @@
--alpha-pips: 0.5;
--alpha-pips-text: 0.7;
+ --border-radius: 0;
+
+ border-radius: var(--border-radius);
color: var(--color-text);
diff --git a/src/scss/widgets/basics.scss b/src/scss/widgets/basics.scss
index e6132fd5..8d7c3cbd 100644
--- a/src/scss/widgets/basics.scss
+++ b/src/scss/widgets/basics.scss
@@ -56,6 +56,9 @@
white-space: pre-wrap;
word-break: break-all;
}
+ &.wrap-soft {
+ word-break: normal
+ }
&.vertical {
transform: rotate(180deg);
text-overflow: ellipsis;
@@ -139,6 +142,12 @@
justify-content: center;
text-overflow: clip;
overflow: hidden;
+
+ white-space: pre;
+ text-align: center;
+ word-wrap: break-word;
+
+
@include pseudo-fill($z: -1);
&:after {
--line-width: 1rem;
@@ -150,7 +159,35 @@
color: var(--color-text-on);
}
+ * {
+ pointer-events: none;
+ }
+ }
+ &.layout-vertical value:first-child {
+ border-top-left-radius: inherit;
+ border-top-right-radius: inherit;
+ }
+ &.layout-vertical value:last-child {
+ border-bottom-left-radius: inherit;
+ border-bottom-right-radius: inherit;
+ }
+ &.layout-horizontal value:first-child {
+ border-bottom-left-radius: inherit;
+ border-top-left-radius: inherit;
+ }
+ &.layout-horizontal value:last-child {
+ border-bottom-right-radius: inherit;
+ border-top-right-radius: inherit;
+ }
+
+ &.wrap value {
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+
+ &.wrap-soft value {
+ word-break: normal
}
}
@@ -193,6 +230,11 @@
z-index: 9999999999999!important;
contain: size;
overflow: visible;
+
+ // modal-breakout
+ @supports not (contain: strict) {
+ transform: none!important; // cancel new stacking context
+ }
}
@@ -266,8 +308,7 @@
position: fixed;
z-index: 999999999;
- margin-left: calc(-1 * var(--parent-scroll-x));
- margin-top: calc(-1 * var(--parent-scroll-y));
+ transform: translate(calc(-1 * var(--parent-scroll-x)), calc(-1 * var(--parent-scroll-y)));
overflow: hidden;
@@ -280,7 +321,7 @@
.item {
-
+ white-space: pre;
z-index: 1;
overflow: hidden;
div {
@@ -338,19 +379,19 @@
top: calc(-1 * var(--size) / 8);
border-radius: 100%;
pointer-events: none;
- box-shadow: 0 0 0 4rem var(--color-fill);
- opacity: 0;
+ box-shadow: 0 0 0 calc(var(--size) / 2.7 - 2rem) var(--color-fill);
+ opacity: 0.075;
}
}
&.on {
- color: var(--color-fill);
+ color: var(--color-background);
}
&.on div:before {
opacity: var(--alpha-fill-on)!important;
}
- &.active div:before, &:hover div:before {
+ &.active div:before {
opacity: var(--alpha-fill-hover);
}
@@ -371,7 +412,7 @@
width:var(--size-box-w);
height:var(--size-box-h);
-
+ border-radius: inherit;
display: flex;
flex-direction: row;
@@ -390,7 +431,7 @@
height: 100%;
flex: 1;
&:after {
- opacity: 0;
+ opacity: 0.075;
margin: 0;
top:0;left:0;right:0;bottom:0;
}
@@ -403,7 +444,7 @@
}
}
- &.active, &:hover {
+ &.active {
div:after, div:after {
opacity: var(--alpha-fill-hover);
}
@@ -419,14 +460,38 @@
display: grid;
grid-template-columns: repeat(var(--grid-columns), 1fr);
+ .item {
+ border-radius: inherit;
+ }
}
&.vertical menu {
flex-direction: column;
+ .item:first-child {
+ border-top-left-radius: inherit;
+ border-top-right-radius: inherit;
+ }
+ .item:last-child {
+ border-bottom-left-radius: inherit;
+ border-bottom-right-radius: inherit;
+ }
+
}
+ &.horizontal menu {
+
+ .item:first-child {
+ border-bottom-left-radius: inherit;
+ border-top-left-radius: inherit;
+ }
+ .item:last-child {
+ border-bottom-right-radius: inherit;
+ border-top-right-radius: inherit;
+ }
+
+ }
}
@@ -513,7 +578,9 @@
background: var(--color-background);
opacity: 0;
}
-
+ option.on {
+ background: var(--color-fill)
+ }
}
.editor-enabled {
@@ -563,6 +630,7 @@
canvas {
flex:1;
max-width: 100%;
+ height: 100%;
}
input {
@@ -574,35 +642,86 @@
padding:0;
background: transparent;
border-radius: inherit;
- -webkit-appearance:none;
- appearance: none;
text-align:inherit;
vertical-align: top;
letter-spacing: 1rem;
- -webkit-user-select: text;
- user-select: text;
-
- color:var(--color-fill);
caret-color: var(--color-fill);
-
height: 100%;
-
+ -webkit-appearance:none;
+ -moz-appearance:none;
+ appearance:none;
+ -webkit-user-select: auto;
+ -moz-user-select: auto;
+ user-select: auto;
+ &:focus {
+ color:var(--color-fill);
+ }
&:focus::selection {
background: var(--color-fill);
color: var(--color-text);
}
+ &::-webkit-outer-spin-button,
+ &::-webkit-inner-spin-button {
+ -webkit-appearance: none;
+ margin: 0;
+ }
+
+ &[type="number"] {
+ -moz-appearance: textfield;
+ }
+
}
}
+.textarea-container {
+
+ --alpha-fill-off: 0.05;
+ --widget-padding: 2rem;
+
+ inner {
+ position: relative;
+ @include pseudo-stroke();
+ @include pseudo-fill(0.05);
+ justify-content: center;
+ align-items: center;
+ display: flex;
+ padding: var(--widget-padding);
+ text-align: center;
+ &.right {
+ text-align: right;
+ }
+ &.left {
+ text-align: left;
+ }
+
+ }
+ textarea {
+ background: none;
+ width: 100%;
+ height: 100%;
+ resize: none;
+ padding: var(--widget-padding);
+ -webkit-appearance:none;
+ -moz-appearance:none;
+ appearance:none;
+ -webkit-user-select: auto;
+ -moz-user-select: auto;
+ user-select: auto;
+ }
+}
+
.editor-enabled {
- .input-container select {
+ .textarea-container textarea,
+ .input-container inner {
// prevent input focus when selecting
pointer-events: none;
}
- .clone-container.editing .input-container select,
- .input-container.editing select {
+ .clone-container.editing .textarea-container textarea,
+ .textarea-container.editing textarea,
+ .clone-container.editing .input-container inner,
+ .input-container.editing inner {
// prevent input focus when selecting
pointer-events: auto;
}
@@ -644,6 +763,11 @@
min-width: 0;
overflow: hidden;
}
+
+ &.hide-path .text {
+ display: none;
+ }
+
.icon {
order: 1;
display: block;
@@ -659,4 +783,8 @@
}
}
+ &.save .icon:after {
+ content:"\f0c7";
+ }
+
}
diff --git a/src/scss/widgets/containers.scss b/src/scss/widgets/containers.scss
index a98765af..f10598c4 100644
--- a/src/scss/widgets/containers.scss
+++ b/src/scss/widgets/containers.scss
@@ -25,10 +25,15 @@
> inner {
overflow: auto;
+ scroll-behavior: auto!important; // smooth mode breaks scrollbar widget
}
+ &.hidden-scroll > inner {
+ scrollbar-width: none;
+ }
+
&.no-scroll > inner {
overflow: hidden;
}
@@ -73,7 +78,8 @@
max-width: 100%;
}
- &.layout-vertical > inner {
+ &.layout-vertical > inner,
+ &.layout-vertical .folder-container > inner {
display: flex;
flex-direction: column;
align-items: stretch;
@@ -94,7 +100,8 @@
max-height: 100%;
}
- &.layout-grid > inner {
+ &.layout-grid > inner,
+ &.layout-grid .folder-container > inner {
display: grid;
> .widget {
top:auto!important;
@@ -120,7 +127,7 @@
display: flex;
flex-direction: column;
- overflow: hidden;
+ // overflow: hidden;
> .widget {
flex: 1;
@@ -130,13 +137,22 @@
}
}
- &.vertical-tabs {
-
- > inner {
- flex-direction: row;
- }
-
+ &.tabs-left > inner {
+ flex-direction: row;
}
+
+ &.tabs-right > inner {
+ flex-direction: row-reverse;
+ }
+
+ &.tabs-bottom > inner {
+ flex-direction: column-reverse;
+ }
+
+ &.tabs-hidden > inner > .navigation {
+ display: none;
+ }
+
}
}
@@ -165,7 +181,8 @@
.tablink.editing:after {
margin: 2rem 2rem 4rem;
}
-.vertical .tablink.editing:after {
+.tabs-left > .tablink.editing:after,
+.tabs-right > .tablink.editing:after {
margin: 2rem 4rem 2rem 2rem;
}
@@ -201,6 +218,22 @@
}
+.folder-container {
+ display: contents;
+ overflow: visible;
+ contain: unset;
+ min-width: 0;
+ width: 0;
+ min-height: 0;
+ height: 0;
+ padding: 0;
+ margin: 0;
+ > inner {
+ display: contents!important;
+ padding: 0;
+ }
+}
+
.root-container {
@extend .widget-panel-base;
@@ -244,13 +277,14 @@
.navigation {
- background-color: var(--color-ui-background);
+ background-color: var(--color-ui-foreground);
- height:calc(var(--nav-height) - 1rem);
+ height:var(--nav-height);
flex-shrink:0;
display: flex;
// padding-bottom: 1rem;
position: relative;
+ border-bottom: 1rem solid var(--color-background);
&:before {
content:"";
@@ -287,6 +321,8 @@
white-space: pre-wrap;
text-align: center;
+ border-right: 1rem solid var(--color-background);
+
i {
pointer-events: none;
position: relative;
@@ -294,6 +330,7 @@
&.on {
z-index: 1;overflow: visible;
+ background: var(--color-ui-background);
&:before {
content: "";
position: absolute;
@@ -305,26 +342,40 @@
background: var(--color-fill);
z-index: 101;
}
+
+
+ }
+ }
+ &.tabs-top, &.bottom {
+ div {
+ &:last-child {
+ border-right: 0;
+ }
&:first-child:before {
margin-left: 1rem;
}
&:last-child:before {
margin-right: 1rem;
}
-
}
}
- &.vertical {
+
+ &.tabs-left, &.tabs-right {
flex-direction: column;
height: 100%;
padding-bottom: 0;
+ border-bottom: none;
// padding-right: 1rem;
+ border-right: 1rem solid var(--color-background);
div {
height: 100%;
padding: 0 12rem;
line-height: normal;
+ border-right: none;
+ border-bottom: 1rem solid var(--color-background);
+
// justify-content: flex-start;
// text-align: left;
@@ -341,20 +392,22 @@
background: var(--color-fill);
z-index: 101;
}
+
+ &:last-child {
+ border-bottom:0
+ }
&:first-child:before {
margin-top: 1rem;
- margin-left: 0;
}
&:last-child:before {
margin-bottom: 1rem;
- margin-right: 0;
}
}
}
}
-.clone-container {
+.clone-container, .fragment-container {
&.empty {
@include pseudo-stroke();
@@ -367,7 +420,8 @@
content: none
}
- > .clone {
+ > .clone,
+ > .fragment {
--widget-spacing: 0;
flex: 1;
@@ -392,6 +446,10 @@
padding: 0!important;
}
}
+
+ &.modal-breakout {
+ overflow: visible;
+ }
}
@@ -442,19 +500,18 @@
> .toggle {
--alpha-fill:var(--alpha-fill-on);
+ z-index: 1;
}
> label {
color: var(--color-text-on);
+ z-index: 2;
}
- z-index: 9999999999999!important;
overflow: visible;
contain: size;
@supports not (contain: strict) {
transform: none; // cancel new stacking context
- z-index: initial!important; // iOS does it wrong otherwise
-
}
}
@@ -478,6 +535,7 @@
> .popup {
padding:0;
+ z-index: 9999999999999!important;
> .popup-wrapper {
width: var(--width, 100%);
@@ -517,6 +575,8 @@
}
+ --parent-scroll-x:0;
+ --parent-scroll-y:0;
&.relative {
> .popup {
left: auto;
@@ -525,8 +585,8 @@
bottom: auto;
width: var(--width, 100%);
height: var(--height, 100%);
- margin-top: calc(-1 * var(--widget-spacing));
- margin-left: calc(-1 * var(--widget-spacing));
+ margin-top: calc(-1 * var(--widget-spacing) - var(--parent-scroll-y));
+ margin-left: calc(-1 * var(--widget-spacing) - var(--parent-scroll-x));
padding: var(--widget-spacing);
align-items:flex-start;
justify-content: flex-start;
@@ -562,6 +622,7 @@
.patchbaynode-container {
justify-content: center;
+ flex: 1;
background: transparent;
}
diff --git a/src/scss/widgets/indicators.scss b/src/scss/widgets/indicators.scss
index 4a931382..f6b8a3c2 100644
--- a/src/scss/widgets/indicators.scss
+++ b/src/scss/widgets/indicators.scss
@@ -65,7 +65,7 @@
overflow: hidden;
text-align: center;
word-wrap: break-word;
- padding: 0 var(--text-padding);
+ padding: var(--text-padding);
&.right {
text-align: right;
@@ -75,10 +75,19 @@
text-align: left;
justify-content: flex-start;
}
+ &.top {
+ align-items: flex-start;
+ }
+ &.bottom {
+ align-items: flex-end;
+ }
&.wrap {
white-space: pre-wrap;
word-break: break-all;
}
+ &.wrap-soft {
+ word-break: normal
+ }
&.vertical {
transform: rotate(180deg);
text-overflow: ellipsis;
diff --git a/src/scss/widgets/pads.scss b/src/scss/widgets/pads.scss
index 89f7cbab..edc88ea2 100644
--- a/src/scss/widgets/pads.scss
+++ b/src/scss/widgets/pads.scss
@@ -1,6 +1,7 @@
.xy-container,
.multixy-container,
-.rgb-container {
+.rgb-container,
+.canvas-container {
width: 200rem;
height: 200rem;
}
@@ -29,7 +30,9 @@
.multixy-container {
- canvas:not(:first-child) {
+ --point-size: 20rem;
+
+ canvas {
position: absolute;
top: 0;
left: 0;
@@ -125,3 +128,30 @@
}
}
+
+
+.canvas-container {
+
+ --alpha-fill-off: 0.05;
+ --alpha-fill-on: 0.75;
+ --alpha-fill: var(--alpha-fill-off);
+ --widget-padding: 0rem;
+ .html {
+ pointer-events: auto;
+ }
+
+ inner {
+ position: relative;
+ flex: 1;
+ display: flex;
+
+ @include pseudo-fill($z: -1);
+ @include pseudo-stroke();
+ }
+
+ canvas {
+ width: 100%;
+ text-align: center;
+ }
+
+}
diff --git a/src/scss/widgets/sliders.scss b/src/scss/widgets/sliders.scss
index 04952919..a5f4b6fe 100644
--- a/src/scss/widgets/sliders.scss
+++ b/src/scss/widgets/sliders.scss
@@ -1,7 +1,11 @@
.fader-container,
+.scrollbar-container,
.knob-container,
.encoder-container,
.range-container {
+
+ --color-knob: var(--color-fill);
+
canvas {
image-rendering: pixelated;
width: 100%;
@@ -10,6 +14,7 @@
}
+.scrollbar-container,
.fader-container,
.range-container {
@@ -65,3 +70,8 @@
}
}
+
+.scrollbar-container {
+ --alpha-fill-off: 0;
+ --alpha-fill-on: var(--alpha-scrollbar);
+}
diff --git a/src/server/custom-module.js b/src/server/custom-module.js
deleted file mode 100644
index f29664a2..00000000
--- a/src/server/custom-module.js
+++ /dev/null
@@ -1,202 +0,0 @@
-var settings = require('./settings'),
- fs = require('fs'),
- vm = require('vm'),
- chokidar = require('chokidar'),
- path = require('path')
-
-
-
-class CustomModule {
-
- constructor(file, context, parent=null) {
-
- this.exports = null
- this.init = null
- this.oscInFilter = null
- this.oscOutFilter = null
-
- this.parent = parent
- this.submodule = !!parent
- this.filename = this.submodule && !path.isAbsolute(file) ? path.resolve(path.dirname(parent.filename), file) : file
-
- this.timeouts = []
- this.intervals = []
- this.submodules = []
-
- this.context = this.submodule ? context : {
- ...context,
- loadJSON: (url)=>{
- if (url.split('.').pop() === 'json') {
- try {
- url = path.resolve(path.dirname(this.filename), url)
- return JSON.parse(fs.readFileSync(url, 'utf8'))
- } catch(e) {
- console.error('(ERROR) could not load json file from ' + url)
- console.error(e.message)
- }
- } else {
- console.error('(ERROR) unauthorized file type for loadJSON')
- }
- },
- saveJSON: (url, data)=>{
- if (url.split('.').pop() === 'json') {
- url = path.resolve(path.dirname(this.filename), url)
- try {
- return fs.writeFileSync(url, JSON.stringify(data, null, ' '))
- } catch(e) {
- console.error('(ERROR) could not save json file to ' + url)
- console.error(e.message)
- }
- } else {
- console.error('(ERROR) unauthorized file type for saveJSON')
- }
- },
- console: console,
- settings: {
- read: settings.read,
- appAddresses: settings.appAddresses,
- },
- setTimeout: this.setTimeout.bind(this),
- clearTimeout: this.clearTimeout.bind(this),
- setInterval: this.setInterval.bind(this),
- clearInterval: this.clearInterval.bind(this),
- require: this.require.bind(this)
- }
-
- this.load()
-
- this.watcher = chokidar.watch(this.filename, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
- if (this.submodule) {
- console.log('(INFO) Submodule changed: ' + this.filename)
- this.parent.reload()
- } else {
- console.log('(INFO) Custom module changed: ' + this.filename)
- this.reload()
- }
- })
-
- // remove require function (not needed at runtime)
- // wrong: this.constructor.constructor("return process")().mainModule.require
- process.mainModule.require = process.dlopen = null
-
- }
-
- load() {
-
- var code
-
- try {
- code = fs.readFileSync(this.filename, {encoding: 'utf8', flag: 'rs'}) // flag 'rs' to avoid cache issue on windows
- } catch(err) {
- console.error(`(ERROR) ${this.submodule ? 'Submodule' : 'Custom module'} not found: ${this.filename}`)
- return false
- }
-
- var context = vm.createContext({
- ...this.context,
- module: {exports: {}}
- })
-
- try {
- vm.runInContext(code, context, {
- filename: this.filename
- })
- } catch(err) {
- console.error('(ERROR) Custom module loading error')
- console.error(err)
- return false
- }
-
- this.init = context.module.exports.init || null
- this.oscInFilter = context.module.exports.oscInFilter || null
- this.oscOutFilter = context.module.exports.oscOutFilter || null
- this.exports = context.module.exports
-
- return true
-
- }
-
- unload() {
-
- this.exports = null
- this.init = null
- this.oscInFilter = null
- this.oscOutFilter = null
-
- for (let timeout of this.timeouts) {
- clearTimeout(timeout)
- }
-
- for (let interval of this.intervals) {
- clearInterval(interval)
- }
-
- this.timeouts = []
- this.intervals = []
-
- for (let name of this.context.app.eventNames()) {
- this.context.app.removeAllListeners(name)
- }
-
- for (let mod of this.submodules) {
- mod.unload()
- }
- this.submodules = []
-
- if (this.submodule) {
- this.watcher.close()
- }
-
- }
-
- reload() {
-
- this.unload()
- console.log('(INFO) Reloading custom module...')
- if (this.load()) {
- console.log('(INFO) Custom module reloaded successfully')
- } else {
- console.error('(ERROR) Failed to reload custom module')
- this.unload()
- }
- }
-
- setTimeout(fn, t) {
- var timeout = setTimeout(fn, t)
- this.timeouts.push(timeout)
- return timeout
- }
-
- setInterval(fn, t) {
- var interval = setInterval(fn, t)
- this.intervals.push(interval)
- return interval
- }
-
- clearTimeout(timeout) {
- clearTimeout(timeout)
- if (this.timeouts.includes(timeout)) {
- this.timeouts.splice(this.timeouts.indexOf(timeout), 1)
- }
- }
-
- clearInterval(id) {
- clearInterval(interval)
- if (this.intervals.includes(interval)) {
- this.intervals.splice(this.intervals.indexOf(interval), 1)
- }
- }
-
- require(filename) {
-
- var mod = new CustomModule(filename, this.context, this.parent || this)
- this.submodules.push(mod)
-
- return mod.exports
-
- }
-
-}
-
-
-module.exports = CustomModule
diff --git a/src/server/electron-app.js b/src/server/electron/electron-app.mjs
similarity index 74%
rename from src/server/electron-app.js
rename to src/server/electron/electron-app.mjs
index e69f24ff..eac5e9b0 100644
--- a/src/server/electron-app.js
+++ b/src/server/electron/electron-app.mjs
@@ -1,9 +1,11 @@
-var {app, Menu, shell, BrowserWindow} = require('electron'),
- settings = require('./settings'),
- infos = require('../package.json')
+import {app, Menu, shell, BrowserWindow} from 'electron'
+import semver from 'semver'
+import * as settings from '../node/settings.mjs'
app.setPath('userData', settings.configPath)
+app.commandLine.appendSwitch('--ignore-certificate-errors')
+
app.commandLine.appendSwitch('--touch-events')
if (settings.read('disable-vsync')) {
@@ -19,6 +21,15 @@ if (settings.read('force-gpu')) {
app.commandLine.appendSwitch('--ignore-gpu-blacklist')
}
+// Workaround bug in electron 36 + gnome: https://github.com/electron/electron/issues/46538
+if (process.platform === 'linux') {
+ app.commandLine.appendSwitch('gtk-version', '3')
+}
+
+if (semver.gt(settings.infos.version, settings.read('version') || '0.0.0')) {
+ // set temporary flag to clean electron browser cache in case of update
+ settings.write('clearCache', true, true)
+}
var template = [{
@@ -29,7 +40,8 @@ var template = [{
{type: 'separator'},
{role: 'cut', accelerator: 'CmdOrCtrl+X'},
{role: 'copy', accelerator: 'CmdOrCtrl+C'},
- {role: 'paste', accelerator: 'CmdOrCtrl+V'}
+ {role: 'paste', accelerator: 'CmdOrCtrl+V'},
+ {role: 'selectall', accelerator: 'CmdOrCtrl+A'}
]
}]
@@ -39,7 +51,7 @@ if (process.platform === 'darwin') {
label: settings.infos.productName,
submenu: [
{
- label: 'Hide ' + infos.productName,
+ label: 'Hide ' + settings.infos.productName,
accelerator: 'Command+H',
role: 'hide'
},
@@ -98,23 +110,20 @@ if (process.platform === 'darwin') {
submenu: [
{
label: 'Documentation',
- click: ()=>shell.openExternal(infos.homepage)
+ click: ()=>shell.openExternal(settings.infos.homepage)
},
{
type: 'separator'
},
{
label: 'Report an Issue',
- click: ()=>shell.openExternal(infos.repository.url + '/issues')
+ click: ()=>shell.openExternal(settings.infos.repository.url + '/issues')
}
]
}
)
}
-app.on('before-quit',()=>{
- process.exit()
-})
app.on('ready',()=>{
var menu = Menu.buildFromTemplate(template)
@@ -122,9 +131,7 @@ app.on('ready',()=>{
})
app.on('window-all-closed', function() {
- if (process.platform !== 'darwin') {
- app.quit()
- }
+ app.quit()
})
-module.exports = app
+export default app
diff --git a/src/server/electron-window.js b/src/server/electron/electron-window.mjs
similarity index 61%
rename from src/server/electron-window.js
rename to src/server/electron/electron-window.mjs
index da818efe..5dc78b27 100644
--- a/src/server/electron-window.js
+++ b/src/server/electron/electron-window.mjs
@@ -1,20 +1,20 @@
-var path = require('path'),
- {BrowserWindow, dialog, shell, screen, Menu, MenuItem} = require('electron'),
- shortcut = require('electron-localshortcut'),
- app = require('./electron-app'),
- settings = require('./settings'),
- theme = require('./theme')
+import path from 'path'
+import {BrowserWindow, dialog, shell, screen, Menu, MenuItem} from 'electron'
+import shortcut from 'electron-localshortcut'
+import app from './electron-app.mjs'
+import * as settings from '../node/settings.mjs'
-module.exports = function(options={}) {
+export default function(options={}) {
var window
window = new BrowserWindow({
title: options.title || settings.infos.productName,
- icon: path.resolve(__dirname + '/../assets/logo.png'),
- backgroundColor: options.color || theme.backgroundColor,
+ icon: path.resolve(__dirname + '/../../assets/logo.png'),
+ backgroundColor: '#21252B',
type: options.type,
useContentSize: true,
+ darkTheme: true,
autoHideMenuBar: true,
webPreferences: {
nodeIntegration: !!options.node,
@@ -25,6 +25,7 @@ module.exports = function(options={}) {
})
+
// default geometry
var currentScreen = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()),
screenSize = currentScreen.size,
@@ -32,27 +33,55 @@ module.exports = function(options={}) {
height = options.height || screenSize.height,
bounds = currentScreen.bounds,
x = Math.ceil(bounds.x + ((bounds.width - width) / 2)),
- y = Math.ceil(bounds.y + ((bounds.height - height) / 2))
+ y = Math.ceil(bounds.y + ((bounds.height - height) / 2)),
+ geometry = {x, y, width, height}
- window.setBounds({x, y, width, height})
-
- // retreive last geometry
+ // retrieve last geometry
if (settings.read('geometry') && settings.read('geometry')[options.id]) {
- var geometry = settings.read('geometry')[options.id],
+ var last_geometry = settings.read('geometry')[options.id],
mScreen = screen.getDisplayMatching(geometry)
if (intersectionArea(geometry, mScreen.bounds) > 20000) {
// don't load geometry if the window is not visible enough
- window.setBounds(geometry)
+ Object.assign(geometry, last_geometry)
}
}
+ if (options.id === 'client') {
+ if (settings.read('client-position')) {
+ [x, y] = settings.read('client-position').split(',').map(x=>parseInt(x))
+ Object.assign(geometry, {x, y})
+ }
+
+ if (settings.read('client-size')) {
+ [width, height] = settings.read('client-size').split(',').map(x=>parseInt(x))
+ Object.assign(geometry, {width, height})
+ }
+ }
+
+ window.setBounds(geometry)
+
window.once('ready-to-show', ()=>{
- window.show()
+ if (options.id === 'launcher' && settings.read('startMinimized')) {
+ if (settings.read('useTray') || process.platform === 'darwin') {
+ window.hide()
+ } else {
+ window.show()
+ window.minimize()
+ }
+ } else {
+ window.show()
+ }
})
+ if (options.id === 'launcher' && process.platform === 'darwin' && settings.read('startMinimized')) {
+ app.on('activate', ()=>{
+ if (!window.isDestroyed()) window.show()
+ })
+ }
+
window.webContents.once('page-title-updated', ()=>{
if (options.fullscreen) {
- window.webContents.sendInputEvent({keyCode: 'F11', type: 'keyDown'})
+ window.webContents.executeJavaScript('window.ELECTRON_FULLSCREEN()', true)
}
if (app._noGpu) {
window.webContents.executeJavaScript(`
@@ -98,9 +127,18 @@ module.exports = function(options={}) {
})
- window.webContents.on('console-message', (event, level, message)=>{
+ window.webContents.on('console-message', (event)=>{
- if (level === 0 && message === 'ELECTRON.BLUR()') window.blur()
+ if (event.level === 0 && event.message === 'ELECTRON.BLUR()') window.blur()
+ if (event.level === 0 && event.message === 'ELECTRON.FOCUS()') window.focus()
+ if (event.level === 0 && event.message === 'ELECTRON.SETFOCUSABLE(1)') {
+ window.setFocusable(true)
+ window.focus()
+ }
+ if (event.level === 0 && event.message === 'ELECTRON.SETFOCUSABLE(0)') {
+ window.setFocusable(false)
+ window.blur()
+ }
})
@@ -114,11 +152,12 @@ module.exports = function(options={}) {
window.loadURL(options.address)
- if (process.platform !== 'darwin') {
+ if (process.platform === 'linux') {
// already registered in app menu on macOs
+ // already bound to alt+f4 on windows
window.webContents.on('before-input-event', (e, input)=>{
// using before-input-event because electron-localshortcut
- // gets azerty keyboards wrong (ctrl + z would also be catched)
+ // gets azerty keyboards wrong (ctrl + z would also be caught)
if ((input.key === 'w' || input.key === 'W') && input.control && input.type === 'keyDown') {
window.close()
}
@@ -129,19 +168,21 @@ module.exports = function(options={}) {
// save geometry
var geometry = settings.read('geometry') || {}
geometry[options.id] = window.getBounds()
- settings.write('geometry', geometry)
+ settings.write('geometry', geometry, false, true)
})
var menu = new Menu()
+ menu.append(new MenuItem({role: 'cut'}))
menu.append(new MenuItem({role: 'copy'}))
menu.append(new MenuItem({role: 'paste'}))
window.webContents.on('context-menu', (e, data) => {
- menu.items[0].enabled = data.editFlags.canCopy
- menu.items[1].enabled = data.editFlags.canPaste
+ menu.items[0].enabled = data.editFlags.canPaste
+ menu.items[1].enabled = data.editFlags.canCopy
+ menu.items[2].enabled = data.editFlags.canPaste
menu.popup({window: window, x: e.x, y: e.y })
}, false)
- if (options.shortcuts) {
+ if (options.shortcuts && !settings.read('read-only')) {
shortcut.register(window,'CmdOrCtrl+R',function(){
window.reload()
@@ -157,6 +198,9 @@ module.exports = function(options={}) {
})
}
+ window.setFocusable(!options.noFocus)
+
+
return window
}
diff --git a/src/server/electron/index.mjs b/src/server/electron/index.mjs
new file mode 100644
index 00000000..1f9179a4
--- /dev/null
+++ b/src/server/electron/index.mjs
@@ -0,0 +1,319 @@
+import sourceMap from 'source-map-support'
+import {fork} from 'child_process'
+import path from 'path'
+import {ipcMain} from 'electron'
+import electronRemote from '@electron/remote/main'
+import * as settings from '../node/settings.mjs'
+import DocsServer from '../node/docs-server'
+import app from './electron-app.mjs'
+import window from './electron-window'
+import createTray from './tray.mjs'
+import midi from '../node/midi.mjs'
+import qrcode from '../node/qrcode.mjs'
+
+var dev = process.argv[0].includes('node_modules'),
+ docsServer,
+ launcher = null,
+ tray = null,
+ clientWindows = [],
+ serverProcess = null
+
+sourceMap.install({handleUncaughtExceptions: false})
+
+function openDocs() {
+
+ if (!docsServer) docsServer = new DocsServer()
+
+ docsServer.open()
+
+}
+
+
+function openClient() {
+
+ var address = settings.appAddresses()[0]
+
+ function launch() {
+ var win = window({
+ address:address,
+ shortcuts:true,
+ fullscreen: settings.read('fullscreen'),
+ noFocus: settings.read('client-options') && settings.read('client-options').some(x=>x.match(/nofocus=1/i)),
+ id: 'client'
+ })
+ win.on('error', ()=>{
+ console.log('ERR')
+ })
+ if (settings.read('clearCache')) {
+ // clear browser cache and reload
+ win.webContents.session.clearCache().then(()=>{
+ settings.write('version', settings.infos.version)
+ win.webContents.reload()
+ })
+ }
+ clientWindows.push(win)
+ }
+
+
+ if (app.isReady()) {
+ launch()
+ } else {
+ app.on('ready',function(){
+ launch()
+ })
+ }
+
+}
+
+function startServerProcess() {
+
+ var args = [ '--no-gui']
+
+ for (var k in settings.read('options')) {
+ args.push('--' + k)
+ var val = settings.read(k)
+ if (typeof val === 'object') {
+ args = args.concat(val)
+ } else if (typeof val !== 'boolean') {
+ args.push(val)
+ }
+ }
+
+ serverProcess = fork(app.getAppPath(), args, {stdio: 'pipe', env: {...process.env, OSC_SERVER_PROCESS: 1, ELECTRON_RUN_AS_NODE: 1}})
+
+ var cb = (data)=>{
+ if (data.indexOf('(INFO) Server started') > -1) {
+ if (!settings.read('no-gui')) openClient()
+ if (!settings.read('no-qrcode')) setTimeout(()=>{
+ qrcode(launcher ? 'svg' : 'terminal', (qrstring)=>{
+ if (launcher) {
+ launcher.webContents.send('stdout', qrstring)
+ } else {
+ console.log(qrstring)
+ }
+ })
+ })
+ serverProcess.stdout.off('data', cb)
+ }
+ }
+ serverProcess.stdout.on('data', cb)
+
+ serverProcess.stdout.on('data', (data) => {
+ console.log(String(data).trim())
+ })
+
+ serverProcess.stderr.on('data', (data) => {
+ var str = String(data).trim()
+ if (str.includes('--debug')) return
+ console.error(str)
+ })
+
+
+
+ serverProcess.on('message', (data) => {
+ var [command, args] = data
+ if (command === 'settings.write') {
+ settings.write(args[0], args[1], false)
+ }
+ })
+
+ serverProcess.on('close', (code) => {
+ console.log('(INFO) Server stopped')
+ serverProcess = null
+ if (global.defaultClient) global.defaultClient.close()
+ })
+
+ if (launcher) {
+ serverProcess.on('close', (code) => {
+ if (!launcher.isDestroyed()) launcher.webContents.send('server-stopped')
+ })
+ launcher.webContents.send('server-starting')
+ }
+
+}
+
+function stopServerProcess() {
+
+ if (settings.read('no-gui')) {
+ if (serverProcess) serverProcess.kill('SIGINT')
+ serverProcess = null
+ return
+ }
+
+ var toClose = clientWindows.filter(w=>w && !w.isDestroyed()),
+ closed = 0
+
+ if (toClose.length === 0 && serverProcess) {
+ serverProcess.kill('SIGINT')
+ serverProcess = null
+ }
+
+ for (var w of toClose) {
+ w.on('closed', ()=>{
+ closed++
+ if (closed === toClose.length) {
+ clientWindows = []
+ if (serverProcess) {
+ serverProcess.kill('SIGINT')
+ serverProcess = null
+ }
+ }
+ })
+ w.close()
+ }
+
+}
+
+function startLauncher() {
+
+ global.launcherSharedGlobals = {
+ settings: settings,
+ openDocs: openDocs,
+ midiList: midi.list,
+ midiRestart: ()=>{
+ if (serverProcess) {
+ serverProcess.send('midiRestart')
+ }
+ }
+ }
+ var address = 'file://' + path.resolve(__dirname + '/../../launcher/' + 'index.html')
+
+ // @electron/remote won't work without this hack
+ process.mainModule = {require}
+ electronRemote.initialize()
+
+ app.on('ready', function(){
+
+ launcher = window({address:address, shortcuts:dev, width:680, height:(40 + 200 + 20 + 24 * Object.keys(settings.options).filter(x=>settings.options[x].launcher !== false).length / 2), node:true, id: 'launcher'})
+
+ electronRemote.enable(launcher.webContents)
+
+ if (settings.read('useTray')) {
+
+ tray = createTray({
+ window: launcher,
+ openClient: openClient,
+ app: app,
+ startServer: startServerProcess,
+ stopServer: stopServerProcess
+ })
+
+ launcher.on('will-close', (e)=>{
+ if (clientWindows.some(w=>w && !w.isDestroyed()) || serverProcess) {
+ launcher.hide()
+ e.preventDefault()
+ }
+ })
+
+ }
+
+
+ launcher.on('close', (e)=>{
+ if (tray && (clientWindows.some(w=>w && !w.isDestroyed()) || serverProcess)) {
+ launcher.hide()
+ e.preventDefault()
+ return
+ }
+ process.stdout.write = stdoutWrite
+ process.stderr.write = stderrWrite
+ if (process.log) process.log = processLog
+ if (tray) tray.destroy()
+ })
+
+ })
+
+ let processLog = process.log,
+ stdoutWrite = process.stdout.write,
+ stderrWrite = process.stderr.write
+
+ if (process.log) {
+ process.log = function(string, encoding, fd) {
+ processLog.apply(process, arguments)
+ launcher.webContents.send('stdout', string)
+ }
+ }
+
+ process.stdout.write = function(string, encoding, fd) {
+ stdoutWrite.apply(process.stdout, arguments)
+ launcher.webContents.send('stdout', string)
+ }
+
+ process.stderr.write = function(string, encoding, fd) {
+ stderrWrite.apply(process.stderr, arguments)
+ launcher.webContents.send('stderr', string)
+ }
+
+ ipcMain.on('start',function(e, options){
+
+ startServerProcess()
+
+ })
+
+ ipcMain.on('stop',function(e, options){
+
+ stopServerProcess()
+
+ })
+
+ ipcMain.on('openClient',function(e, options){
+
+ openClient()
+
+ })
+
+ ipcMain.on('showQRCode',function(e, options){
+
+ qrcode('svg', (qrstring)=>{
+ launcher.webContents.send('stdout', qrstring)
+ })
+
+ })
+
+
+ ipcMain.on('hide',function(e, options){
+
+ launcher.hide()
+
+ })
+}
+
+
+if (settings.read('docs')) {
+
+ openDocs()
+
+} else {
+
+ // normal mode:
+ // - electron process: launcher and/or built-in client(s)
+ // - node process: server (node mode in a forked process)
+
+ app.on('ready', ()=>{
+ process.on('SIGINT', function() {
+ if (serverProcess) {
+ serverProcess.kill('SIGINT')
+ serverProcess = null
+ }
+ process.exit(0)
+ })
+ })
+
+ app.on('before-quit',()=>{
+ if (serverProcess) {
+ serverProcess.kill('SIGINT')
+ serverProcess = null
+ }
+ })
+
+
+ if (settings.cli) {
+
+ startServerProcess()
+
+ } else {
+
+ startLauncher()
+
+ }
+
+}
diff --git a/src/server/electron/tray.mjs b/src/server/electron/tray.mjs
new file mode 100644
index 00000000..3e17cedb
--- /dev/null
+++ b/src/server/electron/tray.mjs
@@ -0,0 +1,92 @@
+import {Menu, Tray, ipcMain} from 'electron'
+import * as settings from '../node/settings.mjs'
+
+var tray = null,
+ contextMenu = null,
+ isServerRunning = false
+
+export default function(options = {}) {
+
+ var icon = __dirname + '/../../assets/logo.png'
+ if (process.platform === 'darwin') {
+ icon = __dirname + '/../../assets/logo_tray.png'
+ }
+
+ tray = new Tray(icon)
+ contextMenu = Menu.buildFromTemplate([
+ {
+ label: 'Show launcher',
+ id: 'show',
+ click: ()=>{
+ options.window.show()
+ }
+ },
+ {
+ label: 'Hide launcher',
+ id: 'hide',
+ click: ()=>{
+ options.window.hide()
+ }
+ },
+ {
+ label: 'Start server',
+ id: 'start',
+ click: ()=>{
+ ipcMain.emit('start')
+ }
+ },
+ {
+ label: 'Stop server',
+ id: 'stop',
+ click: ()=>{
+ ipcMain.emit('stop')
+ }
+ },
+ {
+ label: 'New client window',
+ id: 'new',
+ click: ()=> {
+ if (isServerRunning) {
+ options.openClient()
+ }
+ }
+ },
+ {
+ type: 'separator'
+ },
+ {
+ label: 'Quit',
+ click: ()=>{
+ options.app.quit()
+ }
+ },
+ ])
+
+ tray.setContextMenu(contextMenu)
+ tray.setToolTip(settings.infos.productName)
+
+ function updateMenu(){
+ contextMenu.getMenuItemById('start').visible = !isServerRunning
+ contextMenu.getMenuItemById('stop').visible = isServerRunning
+ contextMenu.getMenuItemById('show').visible = !options.window.isVisible()
+ contextMenu.getMenuItemById('hide').visible = options.window.isVisible()
+ contextMenu.getMenuItemById('new').visible = isServerRunning
+ tray.setContextMenu(contextMenu)
+ }
+
+ ipcMain.on('start', function(e, options) {
+ isServerRunning = true
+ updateMenu()
+ })
+
+ ipcMain.on('stop', function(e, options) {
+ isServerRunning = false
+ updateMenu()
+ })
+
+ options.window.on('show', updateMenu)
+ options.window.on('hide', updateMenu)
+
+ return tray
+
+}
diff --git a/src/server/index.js b/src/server/index.js
index 51171c8c..e8f3279d 100644
--- a/src/server/index.js
+++ b/src/server/index.js
@@ -1,224 +1,15 @@
-require('source-map-support').install({handleUncaughtExceptions: false})
-
-var dev = process.argv[0].includes('node_modules'),
- settings = require('./settings'),
- docsServer, serverStarted
-
-
-function openDocs() {
-
- if (!docsServer) {
- var DocsServer = require('./docs-server')
- docsServer = new DocsServer()
- }
-
- docsServer.open()
-
-}
-
-if (settings.read('docs')) return openDocs()
-
-
-function nodeMode() {
-
- if (!settings.read('no-gui')) {
- settings.write('no-gui', true, true)
- console.warn('(INFO) Headless mode (--no-gui) enabled automatically (running with node)')
- }
-
- process.on('uncaughtException', (err)=>{
- console.error('(ERROR) A JavaScript error occurred in the main process:')
- console.error(err.stack)
- })
-
-}
-if (process.title === 'node' || process.title === 'node.exe' || process.env.ELECTRON_RUN_AS_NODE) {
-
- nodeMode()
-
-} else {
+var runtime = 'node'
+if (!process.argv.includes('-n') && !process.argv.includes('--no-gui')
+ && process.versions.electron && !process.env.ELECTRON_RUN_AS_NODE)
+{
try {
-
- require('electron').dialog.showErrorBox = (title, err)=>{
+ var electron = require('electron')
+ electron.dialog.showErrorBox = (title, err)=>{
console.error(title + ': ' + err)
}
-
- } catch(e) {
-
- nodeMode()
-
- }
-
+ runtime = 'electron'
+ } catch {}
}
-function start() {
-
- if (!serverStarted) {
-
- var server = require('./server'),
- osc = require('./osc'),
- callbacks = require('./callbacks'),
- zeroconf = require('./zeroconf')
-
- server.bindCallbacks(callbacks)
-
- serverStarted = true
- process.on('exit',()=>{
- if (osc.midi) osc.midi.stop()
- zeroconf.unpublishAll()
- })
-
- }
-
-}
-
-function openClient() {
-
- var app = require('./electron-app')
- var address = settings.appAddresses()[0]
-
- var launch = ()=>{
- var win = require('./electron-window')({address:address, shortcuts:true, fullscreen: settings.read('fullscreen'), id: 'client'})
- win.on('error', ()=>{
- console.log('ERR')
- })
- return win
- }
- if (app.isReady()) {
- return launch()
- } else {
- app.on('ready',function(){
- launch()
- })
- }
-
-}
-
-
-if (settings.cli) {
-
- start()
- if (!settings.read('no-gui')) openClient()
-
-
-} else {
-
- var app = require('./electron-app'),
- path = require('path'),
- address = 'file://' + path.resolve(__dirname + '/../launcher/' + 'index.html'),
- {ipcMain} = require('electron'),
- {fork} = require('child_process'),
- launcher
-
- process.on('exit',()=>{
- if (global.serverProcess) global.serverProcess.kill()
- })
-
- app.on('ready',function(){
- global.settings = settings
- global.openDocs = openDocs
- global.midilist = require('./midi').list
- global.serverProcess = null
- global.clientWindows = []
- launcher = require('./electron-window')({address:address, shortcuts:dev, width:680, height:(40 + 200 + 20 + 24 * Object.keys(settings.options).filter(x=>settings.options[x].launcher !== false).length / 2), node:true, color:'#151a24', id: 'launcher'})
- launcher.on('close', ()=>{
- process.stdout.write = stdoutWrite
- process.stderr.write = stderrWrite
- if (process.log) process.log = processLog
- })
- })
-
- let processLog = process.log,
- stdoutWrite = process.stdout.write,
- stderrWrite = process.stderr.write
-
- if (process.log) {
- process.log = function(string, encoding, fd) {
- processLog.apply(process, arguments)
- launcher.webContents.send('stdout', string)
- }
- }
-
- process.stdout.write = function(string, encoding, fd) {
- stdoutWrite.apply(process.stdout, arguments)
- launcher.webContents.send('stdout', string)
- }
-
- process.stderr.write = function(string, encoding, fd) {
- stderrWrite.apply(process.stderr, arguments)
- launcher.webContents.send('stderr', string)
- }
-
- ipcMain.on('start',function(e, options){
-
- var args = ['--no-gui']
-
- // if (process.platform === 'win32') args.unshift('--') // not needed with ELECTRON_RUN_AS_NODE since '--' is always prepended
- for (var k in settings.read('options')) {
- args.push('--' + k)
- var val = settings.read(k)
- if (typeof val === 'object') {
- args = args.concat(val)
- } else if (typeof val !== 'boolean') {
- args.push(val)
- }
- }
-
- global.serverProcess = fork(app.getAppPath(), args, {stdio: 'pipe', env: process.env})
- launcher.webContents.send('server-started')
-
- if (!settings.read('no-gui')) {
- var cb = (data)=>{
- if (data.indexOf('Server started') > -1) {
- global.clientWindows.push(openClient())
- global.serverProcess.stdout.off('data', cb)
- }
- }
- global.serverProcess.stdout.on('data', cb)
- }
-
- global.serverProcess.stdout.on('data', (data) => {
- console.log(String(data).trim())
- })
-
- global.serverProcess.stderr.on('data', (data) => {
- console.error(String(data).trim())
- })
-
-
-
- global.serverProcess.on('message', (data) => {
- var [command, args] = data
- if (command === 'settings.write') {
- settings.write(args[0], args[1], false)
- }
- })
-
- global.serverProcess.on('close', (code) => {
- console.log('(INFO) Server stopped')
- global.serverProcess = null
- if (global.defaultClient) global.defaultClient.close()
- if (!launcher.isDestroyed()) launcher.webContents.send('server-stopped')
- })
-
- })
-
- ipcMain.on('stop',function(e, options){
-
- if (global.serverProcess) global.serverProcess.kill()
- for (var w of [...global.clientWindows]) {
- if (w && !w.isDestroyed()) w.close()
- }
- global.clientWindows = []
-
- })
-
- ipcMain.on('openClient',function(e, options){
-
- global.clientWindows.push(openClient())
-
- })
-
-
-}
+require(`./${runtime}/`)
diff --git a/src/server/ipc/server.js b/src/server/ipc/server.js
deleted file mode 100644
index fa0e6037..00000000
--- a/src/server/ipc/server.js
+++ /dev/null
@@ -1,73 +0,0 @@
-var EventEmitter = require('events').EventEmitter,
- WebSocketServer = require('ws').Server,
- Client = require('./client'),
- settings = require('../settings')
-
-class Ipc extends EventEmitter {
-
- constructor(server) {
-
- super()
-
- this.clients = {}
- this.server = null
-
- this.server = new WebSocketServer({server: server})
-
- this.server.on('connection', (socket, req)=>{
-
- if (settings.read('authentication')) {
- if (!req.headers.authorization) return
- if (req.headers.authorization.search('Basic ') !== 0) return
- var auth = new Buffer(req.headers.authorization.split(' ')[1], 'base64').toString()
- if (settings.read('authentication') !== auth) {
- console.log(`(WARNING) Client connexion refused for ${req.connection.remoteAddress} (authentication failed)`)
- socket.close()
- return
- }
- }
-
- var id = req.url.split('/').pop()
-
- if (!id) return
-
- if (!this.clients[id]) {
-
- var client = new Client(socket, id, req.connection.remoteAddress)
- this.clients[id] = client
-
- this.emit('connection', client)
-
- client.on('destroyed', ()=>{
- delete this.clients[id]
- })
-
- } else {
-
- this.clients[id].open(socket)
- this.clients[id].flush()
-
- }
-
- this.clients[id].emit('created')
-
- })
-
- }
-
- send(event, data, id, except) {
-
- var clients = id ? [this.clients[id]] : this.clients
-
- for (var k in clients) {
- if (!except || this.clients[k] != this.clients[except]) {
- if (clients[k]) clients[k].send(event, data)
- }
- }
-
- }
-
-
-}
-
-module.exports = Ipc
diff --git a/src/server/midi.js b/src/server/midi.js
deleted file mode 100644
index f33d626c..00000000
--- a/src/server/midi.js
+++ /dev/null
@@ -1,130 +0,0 @@
-var {PythonShell} = require('python-shell'),
- fs = require('fs'),
- path = require('path'),
- settings = require('./settings'),
- midiVersion = '1.7.2'
-
-var pythonOptions = {
- scriptPath:__dirname,
- mode:'text',
-}
-
-var midiBinaries = {
- linux: 'osc-midi-linux',
- darwin: 'osc-midi-osx',
- win32: 'osc-midi-windows.exe'
-}
-
-var pythonPathOverride
-if (process.arch === 'x64' && midiBinaries[process.platform]) {
- var p = path.resolve(__dirname, midiBinaries[process.platform])
- if (fs.existsSync(p)) {
- pythonPathOverride = p
- }
-}
-
-class MidiConverter {
-
- constructor() {
-
- this.py = new PythonShell('python/midi.py', Object.assign({
- args: [
- settings.read('debug') ? 'debug' : '',
- ...settings.read('midi')
- ],
- pythonPath: MidiConverter.getPythonPath()
- }, pythonOptions))
-
- this.py.childProcess.on('error', (e)=>{
- if (e.code === 'ENOENT') {
- console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
- } else {
- console.error(`(ERROR, MIDI) ${e.message}`)
- }
- })
-
- }
-
- send(data) {
-
- var args = []
- for (let i in data.args) {
- args.push(data.args[i].value)
- }
-
- this.py.send(JSON.stringify([data.port, data.address, ...args]))
-
- }
-
- stop() {
-
- this.py.childProcess.kill()
-
- }
-
- init(receiveOsc) {
-
- this.receiveOsc = receiveOsc
- this.py.on('message', (message)=>{
- MidiConverter.parseIpc(message, this)
- })
-
- }
-
- static parseIpc(message, instance) {
-
- // console.log(message)
- var name, data
- try {
- [name, data] = JSON.parse(message)
- } catch (err) {
- if (settings.read('debug')) console.error(`(DEBUG, MIDI) Unparsed python log:\n ${message}`)
- }
- if (name == 'log') {
- if (data.indexOf('ERROR') > -1) {
- console.error(data)
- } else {
- console.log(data)
- }
- } else if (name == 'osc') {
- instance.receiveOsc(data)
- } else if (name == 'error') {
- console.error('(ERROR, MIDI) ' + data)
- if (instance) instance.stop()
- } else if (name == 'version' && data != midiVersion) {
- console.error(`(WARNING, MIDI) binary version mismatch (${data} installed, ${midiVersion} expected)`)
- }
-
- }
-
- static list() {
-
- PythonShell.run('python/midi.py', Object.assign({pythonPath: MidiConverter.getPythonPath(), args: ['list-only']}, pythonOptions), function(e, results) {
- if (e) {
- if (e.code === 'ENOENT') {
- console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
- } else {
- console.error(`(ERROR, MIDI) ${e.message}`)
- }
- }
-
- for (let r of results) {
- MidiConverter.parseIpc(r)
- }
- })
-
- }
-
- static getPythonPath() {
-
- var pythonPath = settings.read('midi') ? settings.read('midi').filter(x=>x.includes('path=')).map(x=>x.split('=')[1])[0] : undefined
-
- if (!pythonPath && pythonPathOverride) pythonPath = pythonPathOverride
-
- return pythonPath
-
- }
-
-}
-
-module.exports = MidiConverter
diff --git a/src/server/address.js b/src/server/node/address.mjs
similarity index 56%
rename from src/server/address.js
rename to src/server/node/address.mjs
index b7969f38..013c8ac0 100644
--- a/src/server/address.js
+++ b/src/server/node/address.mjs
@@ -1,9 +1,10 @@
-var ifaces = require('os').networkInterfaces(),
- address = Object.values(ifaces)
+import {networkInterfaces} from 'os'
+
+export default (proto, port)=>{
+ var address = Object.values(networkInterfaces())
.reduce((a,b)=>a.concat(b), [])
.filter(i=>i.family === 'IPv4')
.map(i=>i.address + ':')
-module.exports = (proto, port)=>{
return address.map(x=>proto + x + port)
}
diff --git a/src/server/auth.js b/src/server/node/auth.mjs
similarity index 75%
rename from src/server/auth.js
rename to src/server/node/auth.mjs
index 56d6efc1..b1fcad0d 100644
--- a/src/server/auth.js
+++ b/src/server/node/auth.mjs
@@ -1,10 +1,11 @@
-var settings = require('./settings'),
- auth = null
+import httpAuth from 'http-auth'
+import * as settings from './settings.mjs'
+
+var auth = null
if (settings.read('authentication')) {
- var [name, pwd] = settings.read('authentication').split(':'),
- httpAuth = require('http-auth')
+ var [name, pwd] = settings.read('authentication').split(':')
auth = httpAuth.basic(
{
@@ -19,4 +20,4 @@ if (settings.read('authentication')) {
}
-module.exports = auth
+export default auth
diff --git a/src/server/node/custom-module.mjs b/src/server/node/custom-module.mjs
new file mode 100644
index 00000000..5169cd61
--- /dev/null
+++ b/src/server/node/custom-module.mjs
@@ -0,0 +1,267 @@
+import fs from 'fs'
+import vm from 'vm'
+import chokidar from 'chokidar'
+import path from 'path'
+import {Module} from 'module'
+import * as settings from './settings.mjs'
+
+var modulePathExtended = false,
+ loadedModules = {},
+ globalObject = {}
+
+class CustomModule {
+
+ constructor(file, context, parent=null, mainModule=null) {
+
+ this.module = {exports: null}
+ this.init = null
+ this.oscInFilter = null
+ this.oscOutFilter = null
+
+ this.mainModule = mainModule
+
+ this.parent = parent
+ this.submodule = !!parent
+
+ this.filename = this.submodule ? file : path.resolve(file)
+
+ this.timeouts = []
+ this.intervals = []
+ this.submodules = {}
+
+
+ this.context = this.submodule ? {
+ ...context,
+ require: this.require.bind(this),
+ } : {
+ ...context,
+ loadJSON: (url, errorCallback)=>{
+ try {
+ url = path.resolve(path.dirname(this.filename), url)
+ var content = fs.readFileSync(url, 'utf8')
+ if (content[0] === '\ufeff') content = content.slice(1) // remove BOM
+ return JSON.parse(content)
+ } catch(e) {
+ if (typeof(errorCallback) === 'function') {
+ errorCallback(e)
+ } else {
+ console.error('(ERROR, CUSTOM MODULE) could not load json file from ' + url)
+ console.error(e.message)
+ }
+ }
+ },
+ saveJSON: (url, data, errorCallback)=>{
+ url = path.resolve(path.dirname(this.filename), url)
+ try {
+ return fs.writeFileSync(url, JSON.stringify(data, null, ' '))
+ } catch(e) {
+ if (typeof(errorCallback) === 'function') {
+ errorCallback(e)
+ } else {
+ console.error('(ERROR, CUSTOM MODULE) could not save json file to ' + url)
+ console.error(e.message)
+ }
+ }
+ },
+ console: console,
+ settings: {
+ read: settings.read,
+ appAddresses: settings.appAddresses,
+ },
+ setTimeout: this.setTimeout.bind(this),
+ clearTimeout: this.clearTimeout.bind(this),
+ setInterval: this.setInterval.bind(this),
+ clearInterval: this.clearInterval.bind(this),
+ require: this.require.bind(this),
+ nativeRequire: require,
+ process: process,
+ global: globalObject
+ }
+
+ if (!this.submodule && !modulePathExtended) {
+ process.env.NODE_PATH += path.delimiter + path.resolve(path.dirname(this.filename))
+ process.env.NODE_PATH += path.delimiter + path.resolve(path.dirname(this.filename), 'node_modules')
+ Module._initPaths()
+ modulePathExtended = true
+ }
+
+ this.load()
+
+ this.watcher = chokidar.watch(this.filename, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
+ if (this.submodule) {
+ console.log('(INFO) Submodule changed: ' + this.filename)
+ this.mainModule.reload()
+ } else {
+ console.log('(INFO) Custom module changed: ' + this.filename)
+ this.reload()
+ }
+ })
+
+ }
+
+ load() {
+
+ if (loadedModules[this.filename]) {
+ this.module.exports = loadedModules[this.filename].module.exports
+ return true
+ }
+
+ var code
+
+ try {
+ code = fs.readFileSync(this.filename, {encoding: 'utf8', flag: 'rs'}) // flag 'rs' to avoid cache issue on windows
+ } catch(err) {
+ console.error(`(ERROR, CUSTOM MODULE) Module not found: ${this.filename}`)
+ return false
+ }
+
+ var context = vm.createContext({
+ ...this.context,
+ __dirname: path.resolve(path.dirname(this.filename)),
+ __filename: path.resolve(this.filename),
+ module: this.module
+ })
+
+
+ try {
+ loadedModules[this.filename] = this
+ vm.runInContext(code, context, {
+ filename: this.filename
+ })
+ } catch(err) {
+ loadedModules[this.filename] = null
+ console.error('(ERROR, CUSTOM MODULE) Error while loading module')
+ console.log(err)
+ return false
+ }
+
+ if (typeof this.module.exports === 'object' && this.module.exports !== null) {
+ this.init = this.module.exports.init || null
+ this.oscInFilter = this.module.exports.oscInFilter || null
+ this.oscOutFilter = this.module.exports.oscOutFilter || null
+ }
+
+ return true
+
+ }
+
+ unload() {
+
+ if (!loadedModules[this.filename]) return
+ loadedModules[this.filename] = null
+
+ if (this.module.exports && this.module.exports.unload) {
+ try {
+ this.module.exports.unload()
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE) Error while calling unload()')
+ console.error(e)
+ }
+ }
+
+ this.module = {exports: null}
+ this.init = null
+ this.oscInFilter = null
+ this.oscOutFilter = null
+
+ for (let timeout of this.timeouts) {
+ clearTimeout(timeout)
+ }
+
+ for (let interval of this.intervals) {
+ clearInterval(interval)
+ }
+
+ this.timeouts = []
+ this.intervals = []
+
+ for (let name of this.context.app.eventNames()) {
+ this.context.app.removeAllListeners(name)
+ }
+
+ for (let name in this.submodules) {
+ this.submodules[name].unload()
+ }
+ this.submodules = {}
+
+ if (this.submodule) {
+ this.watcher.close()
+ }
+
+ }
+
+ reload() {
+
+ this.unload()
+ console.log('(INFO) Reloading custom module...')
+ if (this.load()) {
+ console.log('(INFO) Custom module reloaded successfully')
+
+ if (this.module.exports && this.module.exports.reload) {
+ try {
+ this.module.exports.reload()
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE) Error while calling custom module reload function')
+ console.error(e)
+ }
+ }
+ } else {
+ console.error('(ERROR, CUSTOM MODULE) Failed to reload custom module')
+ this.unload()
+ }
+ }
+
+ stop() {
+
+ if (this.module.exports && this.module.exports.stop) {
+ try {
+ this.module.exports.stop()
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE) Error while calling custom module stop function')
+ console.error(e)
+ }
+ }
+ }
+
+ setTimeout(fn, t) {
+ var timeout = setTimeout(fn, t)
+ this.timeouts.push(timeout)
+ return timeout
+ }
+
+ setInterval(fn, t) {
+ var interval = setInterval(fn, t)
+ this.intervals.push(interval)
+ return interval
+ }
+
+ clearTimeout(timeout) {
+ clearTimeout(timeout)
+ if (this.timeouts.includes(timeout)) {
+ this.timeouts.splice(this.timeouts.indexOf(timeout), 1)
+ }
+ }
+
+ clearInterval(interval) {
+ clearInterval(interval)
+ if (this.intervals.includes(interval)) {
+ this.intervals.splice(this.intervals.indexOf(interval), 1)
+ }
+ }
+
+ require(filename) {
+
+ if (!path.isAbsolute(filename)) {
+ filename = path.resolve(path.dirname(this.filename), filename)
+ }
+
+ this.submodules[filename] = loadedModules[filename] || new CustomModule(filename, this.context, this, this.mainModule || this)
+
+ return this.submodules[filename].module.exports
+
+ }
+
+}
+
+
+export default CustomModule
diff --git a/src/server/docs-server.js b/src/server/node/docs-server.mjs
similarity index 89%
rename from src/server/docs-server.js
rename to src/server/node/docs-server.mjs
index a8fd215f..4de0c842 100644
--- a/src/server/docs-server.js
+++ b/src/server/node/docs-server.mjs
@@ -1,10 +1,10 @@
-var EventEmitter = require('events').EventEmitter,
- http = require('http'),
- send = require('send'),
- path = require('path'),
- fs = require('fs'),
- open = require('open'),
- address = require('./address')
+import {EventEmitter} from 'events'
+import http from 'http'
+import send from 'send'
+import path from 'path'
+import fs from 'fs'
+import open from 'open'
+import address from './address.mjs'
class DocsServer extends EventEmitter {
@@ -87,4 +87,4 @@ class DocsServer extends EventEmitter {
}
-module.exports = DocsServer
+export default DocsServer
diff --git a/src/server/node/fragment-manager.mjs b/src/server/node/fragment-manager.mjs
new file mode 100644
index 00000000..d1c5e03d
--- /dev/null
+++ b/src/server/node/fragment-manager.mjs
@@ -0,0 +1,81 @@
+import chokidar from 'chokidar'
+
+class FragmentManager {
+
+ constructor(callbacks, ipcServer, webServer) {
+
+ this.ipcServer = ipcServer
+ this.webServer = webServer
+ this.callbacks = callbacks
+
+ this.fragments = {} // fragment files contents
+ this.watchers = {} // fragment files watchers
+ this.clients = {} // client ids for each watched fragment file
+
+ }
+
+ read(path, raw, clientId, then) {
+
+ this.callbacks.fileRead({path: path, raw: raw}, clientId, true, (result)=>{
+ this.fragments[path] = result
+ then(result)
+ }, (error)=>{
+ this.ipcServer.send('errorLog', `Could not open fragment file:\n ${error}`, clientId)
+ this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
+ this.deleteFragment(path)
+ })
+
+ }
+
+ loadFragment(data, clientId) {
+
+ var path = data.path
+ var resolvedPath = this.webServer.resolvePath(path, clientId)
+
+ if (!resolvedPath) {
+ this.ipcServer.send('fragmentLoad', {path: path, notFound: true})
+ return
+ }
+
+ if (!this.clients[resolvedPath]) this.clients[resolvedPath] = []
+ if (!this.clients[resolvedPath].includes(clientId)) this.clients[resolvedPath].push(clientId)
+
+ if (!this.fragments[resolvedPath]) {
+
+ this.fragments[resolvedPath] = 'LOADING'
+
+ this.read(resolvedPath, data.raw, clientId, (result)=>{
+ this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
+ })
+
+ this.watchers[resolvedPath] = chokidar.watch(resolvedPath, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
+ this.read(resolvedPath, data.raw, clientId, (result)=>{
+ for (let id of this.clients[resolvedPath]) {
+ this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, id)
+ }
+ })
+ }).on('unlink', ()=>{
+ this.deleteFragment(resolvedPath)
+ })
+
+ } else if (this.fragments[resolvedPath] !== 'LOADING') {
+
+ this.ipcServer.send('fragmentLoad', {path: path, fileContent: this.fragments[resolvedPath], raw: data.raw}, clientId)
+
+ }
+
+ }
+
+ deleteFragment(path) {
+
+ this.watchers[path].close()
+ delete this.clients[path]
+ delete this.fragments[path]
+ delete this.fragments[path]
+
+ }
+
+}
+
+
+export default FragmentManager
diff --git a/src/server/node/index.mjs b/src/server/node/index.mjs
new file mode 100644
index 00000000..01c83bd5
--- /dev/null
+++ b/src/server/node/index.mjs
@@ -0,0 +1,46 @@
+import sourceMap from 'source-map-support'
+import * as settings from './settings.mjs'
+import qrcode from './qrcode.mjs'
+import zeroconf from './zeroconf.mjs'
+import DocsServer from './docs-server.mjs'
+import OscServer from './osc/index.mjs'
+import WebServer from './server.mjs'
+import IpcServer from './ipc/server.mjs'
+
+
+sourceMap.install({handleUncaughtExceptions: false})
+
+process.on('uncaughtException', (err)=>{
+ console.error('(ERROR) A JavaScript error occurred in the main process:')
+ console.error(err.stack)
+})
+
+
+if (settings.read('docs')) {
+
+ var docsServer = new DocsServer()
+ docsServer.open()
+
+} else {
+
+ var webServer = new WebServer(),
+ oscServer = new OscServer(),
+ ipcServer = new IpcServer(webServer, oscServer)
+
+ webServer.start(ipcServer)
+ oscServer.start(ipcServer)
+
+ process.on('SIGINT', function() {
+ webServer.stop()
+ oscServer.stop()
+ zeroconf.unpublishAll()
+ process.exit(0)
+ })
+
+ if (!process.env.OSC_SERVER_PROCESS) webServer.on('serverStarted', ()=>{
+ if (!settings.read('no-qrcode')) {
+ qrcode('terminal', (qr)=>console.log(qr))
+ }
+ })
+
+}
diff --git a/src/server/callbacks.js b/src/server/node/ipc/callbacks.mjs
similarity index 51%
rename from src/server/callbacks.js
rename to src/server/node/ipc/callbacks.mjs
index 3e6e5a4f..0d887fbc 100644
--- a/src/server/callbacks.js
+++ b/src/server/node/ipc/callbacks.mjs
@@ -1,59 +1,76 @@
-var path = require('path'),
- fs = require('fs'),
- settings = require('./settings'),
- osc = require('./osc'),
- {ipc} = require('./server'),
- {deepCopy, resolveHomeDir} = require('./utils')
+import path from 'path'
+import fs from 'fs'
+import child_process from 'child_process'
+import * as settings from '../settings.mjs'
+import {deepCopy, resolveHomeDir} from '../utils.mjs'
+import FragmentManager from '../fragment-manager.mjs'
-var widgetHashTable = {},
- clipboard = {clipboard: null, idClipboard: null}
+export default class Callbacks {
-module.exports = {
+ constructor(ipcServer, webServer, oscServer) {
+
+ this.oscServer = oscServer
+ this.ipcServer = ipcServer
+ this.webServer = webServer
+
+ this.fragmentManager = new FragmentManager(this, ipcServer, webServer)
+
+ this.clipboardContent = {clipboard: null, idClipboard: null}
+ this.widgetHashTable = {}
+ }
+
+ getEvents() {
+
+ return Object.getOwnPropertyNames(this.__proto__)
+ .filter(x=>!['constructor', 'getEvents'].includes(x))
+ .filter(x=>typeof this[x] == 'function')
+
+ }
open(data, clientId) {
// client connected
- ipc.send('connected')
+ this.ipcServer.send('connected', null, clientId)
var recentSessions = settings.read('recentSessions')
- ipc.send('sessionList', recentSessions, clientId)
- ipc.send('clipboard', clipboard, clientId)
- ipc.send('serverTargets', settings.read('send'), clientId)
+ this.ipcServer.send('sessionList', recentSessions, clientId)
+ this.ipcServer.send('clipboard', this.clipboardContent, clientId)
+ this.ipcServer.send('serverTargets', settings.read('send'), clientId)
if (settings.read('load') && !data.hotReload) return this.sessionOpen({path: settings.read('load')}, clientId)
- },
+ }
close(data, clientId) {
// client disconnected
- },
+ }
created(data, clientId) {
// client created or reconnected
- if (!widgetHashTable[clientId]) {
- widgetHashTable[clientId] = {CONSOLE: {typeTags: ''}}
+ if (!this.widgetHashTable[clientId]) {
+ this.widgetHashTable[clientId] = {CONSOLE: {typeTags: ''}}
}
- },
+ }
destroyed(data, clientId) {
// client removed (timeout)
// clear osc data cache
- if (widgetHashTable[clientId]) delete widgetHashTable[clientId]
+ if (this.widgetHashTable[clientId]) delete this.widgetHashTable[clientId]
- },
+ }
clipboard(data, clientId) {
// shared clipboard
- clipboard = data
- ipc.send('clipboard', data, null, clientId)
+ this.clipboardContent = data
+ this.ipcServer.send('clipboard', data, null, clientId)
- },
+ }
sessionAddToHistory(data) {
@@ -76,10 +93,10 @@ module.exports = {
// save history
settings.write('recentSessions', recentSessions)
- ipc.send('sessionList', recentSessions)
+ this.ipcServer.send('sessionList', recentSessions)
})
- },
+ }
sessionRemoveFromHistory(data) {
@@ -87,10 +104,10 @@ module.exports = {
if (recentSessions.indexOf(data) > -1) {
recentSessions.splice(recentSessions.indexOf(data),1)
settings.write('recentSessions',recentSessions)
- ipc.send('sessionList', recentSessions)
+ this.ipcServer.send('sessionList', recentSessions)
}
- },
+ }
sessionSetPath(data, clientId) {
// store client's current session file path
@@ -98,28 +115,41 @@ module.exports = {
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
if (!settings.read('read-only')) {
- module.exports.sessionAddToHistory(data.path)
+ this.sessionAddToHistory(data.path)
}
- ipc.clients[clientId].sessionPath = data.path
+ this.ipcServer.clients[clientId].sessionPath = data.path
- ipc.send('setTitle', path.basename(data.path), clientId)
+ this.ipcServer.send('setTitle', path.basename(data.path), clientId)
- },
+ }
sessionOpen(data, clientId) {
// attempt to read session file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
- module.exports.fileRead(data, clientId, true, (result)=>{
+ this.fileRead(data, clientId, true, (result)=>{
- ipc.clients[clientId].sessionPath = data.path // for resolving local file requests
- ipc.send('sessionOpen', {path: data.path, session: result}, clientId)
+ this.ipcServer.clients[clientId].sessionPath = data.path // for resolving local file requests
+ this.ipcServer.send('sessionOpen', {path: data.path, fileContent: result}, clientId)
+
+ }, (error)=>{
+
+ this.ipcServer.send('error', `Could not open session file:\n ${error}`, clientId)
})
- },
+ }
+
+ fragmentLoad(data, clientId) {
+ // attempt to read session file
+
+ if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
+
+ this.fragmentManager.loadFragment(data, clientId)
+
+ }
sessionOpened(data, clientId) {
// session file opened successfully
@@ -128,26 +158,29 @@ module.exports = {
if (settings.read('state')) {
var send = true
- for (var id in ipc.clients) {
+ for (var id in this.ipcServer.clients) {
// only make the client send its osc state if there are no other active clients
- if (id !== clientId && ipc.clients[id].connected()) {
+ if (id !== clientId && this.ipcServer.clients[id].connected()) {
send = false
}
}
+
+ var stateContent = fs.readFileSync(settings.read('state'), 'utf8')
+ if (stateContent[0] === '\ufeff') stateContent = stateContent.slice(1) // remove BOM
var state = {
- state: JSON.parse(fs.readFileSync(settings.read('state'), 'utf8')),
+ state: JSON.parse(stateContent),
send: send
}
- ipc.send('stateLoad', state, clientId)
+ this.ipcServer.send('stateLoad', state, clientId)
}
- ipc.send('stateSend', null, null, clientId)
+ if (data.sync) this.ipcServer.send('stateSend', null, null, clientId)
- module.exports.sessionSetPath({path: data.path}, clientId)
+ this.sessionSetPath({path: data.path}, clientId)
- },
+ }
- fileRead(data, clientId, ok, callback) {
+ fileRead(data, clientId, ok, callback, errorCallback) {
// private function
if (!ok) return
@@ -166,27 +199,28 @@ module.exports = {
error = err
} else {
try {
- result = JSON.parse(result)
+ if (result[0] === '\ufeff') result = result.slice(1) // remove BOM
+ result = data.raw ? result : JSON.parse(result)
callback(result)
} catch(err) {
error = err
}
}
- if (error) ipc.send('error', `Could not open file (${error})`)
+ if (error && errorCallback) errorCallback(error)
})
- },
+ }
fileSave(data, clientId, ok, callback) {
// private function
if (!ok) return
- if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(ipc.clients[clientId].address)) {
+ if (!data.path || settings.read('remote-saving') && !RegExp(settings.read('remote-saving')).test(this.ipcServer.clients[clientId].address)) {
- return ipc.send('notify', {
+ return this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_forbidden',
class: 'error'
@@ -205,7 +239,7 @@ module.exports = {
var root = resolveHomeDir(settings.read('remote-root'))
if (root && !path.normalize(data.path).includes(path.normalize(root))) {
console.error('(ERROR) Could not save: path outside of remote-root')
- return ipc.send('notify', {
+ return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (Could not save: path outside of remote-root)'
@@ -218,18 +252,19 @@ module.exports = {
return console.error('(ERROR) Could not save: invalid file')
}
- fs.writeFile(data.path, data.session, function(err, fdata) {
+ fs.writeFile(data.path, data.session, (err, fdata)=>{
- if (err) return ipc.send('notify', {
+ if (err) return this.ipcServer.send('notify', {
class: 'error',
locale: 'remotesave_fail',
message: ' (' + err.message + ')'
}, clientId)
- ipc.send('notify', {
+ this.ipcServer.send('notify', {
icon: 'save',
locale: 'remotesave_success',
+ class: 'session-save',
message: ' ('+ path.basename(data.path) +')'
}, clientId)
@@ -239,20 +274,24 @@ module.exports = {
}
- },
+ }
stateOpen(data, clientId) {
// attempt to open state file
if (Array.isArray(data.path)) data.path = path.resolve(...data.path)
- module.exports.fileRead(data, clientId, true, (result)=>{
+ this.fileRead(data, clientId, true, (result)=>{
- ipc.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
+ this.ipcServer.send('stateLoad', {state: result, path: data.path, send: true}, clientId)
+
+ }, (error)=>{
+
+ this.ipcServer.send('error', `Could not open state file:\n ${error}`, clientId)
})
- },
+ }
sessionSave(data, clientId) {
// save session file (.json)
@@ -261,24 +300,37 @@ module.exports = {
if (!path.basename(data.path).match(/.*\.json$/)) return console.error('(ERROR) Sessions must be saved as .json files')
- module.exports.fileSave(data, clientId, true, ()=>{
+ if (data.backup) {
+ var newpath, i = 0
+ for (;;) {
+ newpath = data.path.replace(/\.json$/, '-backup' + String(i).padStart(3, 0) + '.json')
+ if (fs.existsSync(newpath)) i++
+ else {
+ data.path = newpath
+ break
+ }
+ }
+ }
+
+
+ this.fileSave(data, clientId, true, ()=>{
console.log('(INFO) Session file saved in '+ data.path)
- ipc.send('sessionSaved', clientId)
+ if (!data.backup) this.ipcServer.send('sessionSaved', clientId)
// reload session in other clients
- for (var id in ipc.clients) {
- if (id !== clientId && ipc.clients[id].sessionPath === data.path) {
- module.exports.sessionOpen({path: data.path}, id)
+ for (var id in this.ipcServer.clients) {
+ if (id !== clientId && this.ipcServer.clients[id].sessionPath === data.path) {
+ this.sessionOpen({path: data.path}, id)
}
}
- module.exports.sessionSetPath({path: data.path}, clientId)
+ if (!data.backup) this.sessionSetPath({path: data.path}, clientId)
})
- },
+ }
stateSave(data, clientId) {
// save state file (.json)
@@ -287,21 +339,22 @@ module.exports = {
if (!path.basename(data.path).match(/.*\.state/)) return console.error('(ERROR) Statesaves must be saved as .state files')
- module.exports.fileSave(data, clientId, true, ()=>{
+ this.fileSave(data, clientId, true, ()=>{
console.log('(INFO) State file saved in '+ data.path)
})
- },
+ }
syncOsc(shortdata, clientId) {
// sync osc (or midi) message with other clients
- if (!(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
+ // if widget hash is provided, look for cached data
+ if (!(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
- data = widgetHashTable[clientId][shortdata.h]
+ data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
@@ -313,18 +366,28 @@ module.exports = {
data.args = data.preArgs ? data.preArgs.concat(value) : [value]
- if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
+ if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
- },
+ }
sendOsc(shortdata, clientId) {
// send osc (or midi) message and sync with other clients
+ // shortdata
+ // {
+ // h: 'widget_uuid',
+ // v: widget_value,
+ // ... // target, preArgs, address, typeTags
+ // // override cached data
+ // // required if data.h is not provided
+ // }
- if (!(widgetHashTable[clientId] && widgetHashTable[clientId][shortdata.h])) return
+
+ // if widget hash is provided, look for cached data
+ if (shortdata.h && !(this.widgetHashTable[clientId] && this.widgetHashTable[clientId][shortdata.h])) return
var value = shortdata.v,
- data = widgetHashTable[clientId][shortdata.h]
+ data = shortdata.h ? this.widgetHashTable[clientId][shortdata.h] : {}
data = deepCopy(data)
for (var k in shortdata) {
@@ -343,7 +406,7 @@ module.exports = {
for (var i in targets) {
if (targets[i] === 'self') {
- ipc.send('receiveOsc',data,clientId)
+ this.ipcServer.send('receiveOsc',data,clientId)
continue
} else if (targets[i] === null) {
continue
@@ -354,7 +417,7 @@ module.exports = {
if (port) {
- osc.send(host, port, data.address, data.args, data.typeTags, clientId)
+ this.oscServer.send(host, port, data.address, data.args, data.typeTags, clientId)
}
@@ -362,18 +425,29 @@ module.exports = {
}
- if (!data.noSync) ipc.send('receiveOsc', data, null, clientId)
+ if (!data.noSync) this.ipcServer.send('receiveOsc', data, null, clientId)
- },
+ }
addWidget(data, clientId) {
// cache widget osc data to reduce bandwidth usage
+ // data
+ // {
+ // hash: 'widget_uuid',
+ // data: {
+ // target: ['host:port', ...],
+ // preArgs: [arg1, ...],
+ // address: '/address',
+ // typeTags: 'iif' // one letter per arg typetag
+ // }
+ // }
+ // preArgs, target and typeTags can be empty strings
- if (!widgetHashTable[clientId][data.hash]) {
- widgetHashTable[clientId][data.hash] = {}
+ if (!this.widgetHashTable[clientId][data.hash]) {
+ this.widgetHashTable[clientId][data.hash] = {}
}
- var cache = widgetHashTable[clientId][data.hash],
+ var cache = this.widgetHashTable[clientId][data.hash],
widgetData = data.data
for (var k in widgetData) {
@@ -391,56 +465,92 @@ module.exports = {
// store raw target for client sync widget matching
cache._rawTarget = widgetData.target
- },
+ }
removeWidget(data, clientId) {
// clear widget osc data
- delete widgetHashTable[clientId][data.hash]
+ delete this.widgetHashTable[clientId][data.hash]
- },
+ }
reload(data) {
// (dev) hot reload
- ipc.send('reload')
+ this.ipcServer.send('reload')
- },
+ }
reloadCss() {
// (dev) hot css reload
- ipc.send('reloadCss')
- },
+ this.ipcServer.send('reloadCss')
+ }
log(data) {
console.log(data)
- },
+ }
error(data) {
console.error(data)
- },
+ }
errorLog(data) {
console.error(data)
- },
+ }
errorPopup(data) {
- ipc.send('error', data)
- },
+ this.ipcServer.send('error', data)
+ }
listDir(data, clientId) {
// remote file browser backend
- if (data.path) data.path[0] = resolveHomeDir(data.path[0])
- else data.path = [resolveHomeDir('~/')]
+ if (data.path) {
+ // path is requested
+ data.path[0] = resolveHomeDir(data.path[0])
+ } else if (settings.read('last-dir') && fs.existsSync(settings.read('last-dir'))) {
+ // attempt to use last visited directory
+ data.path = [settings.read('last-dir')]
+ } else {
+ // default directory fallback
+ data.path = [resolveHomeDir('~/')]
+ }
var p = path.resolve(...data.path),
root = resolveHomeDir(settings.read('remote-root'))
if (root && !path.normalize(p).includes(path.normalize(root))) p = root
+
+ if (process.platform === 'win32' && !root) {
+ // Drive list hack on windows
+ if (data.path.length === 2 && data.path[1] === '..' && (data.path[0].match(/^[A-Z]:\\$/) || data.path[0] === '\\')) {
+
+ child_process.exec('(get-wmiobject win32_volume | ? { $_.DriveType -eq 3 } | % { get-psdrive $_.DriveLetter[0] }).Root -join " "', {shell: 'powershell.exe'}, (error, stdout) => {
+
+ if (error) {
+
+ this.ipcServer.send('notify', {class: 'error', message: 'Failed to list available drives (see server console).'}, clientId)
+ console.error('(ERROR) Failed to list available drives.')
+ console.error(error.stack)
+
+ } else {
+
+ this.ipcServer.send('listDir', {
+ path: '\\',
+ files: stdout.split(' ')
+ .filter(value => /[A-Za-z]:/.test(value))
+ .map(value => {return {name: value.trim(), folder: true}})
+ }, clientId)
+
+ }
+ })
+ return
+ }
+ }
+
fs.readdir(p, (err, files)=>{
if (err) {
- ipc.send('notify', {class: 'error', message: err.message}, clientId)
+ this.ipcServer.send('notify', {class: 'error', message: err.message}, clientId)
throw err
} else {
var extRe = data.extension ? new RegExp('.*\\.' + data.extension + '$') : /.*/
@@ -455,15 +565,15 @@ module.exports = {
}
})
list = list.filter(x=>x.folder || x.name.match(extRe))
- ipc.send('listDir', {
+ this.ipcServer.send('listDir', {
path: p,
- files: list
+ files: list,
+ root: root
}, clientId)
+ settings.write('last-dir', p, false, false)
}
})
-
- },
-
+ }
}
diff --git a/src/server/ipc/client.js b/src/server/node/ipc/client.mjs
similarity index 92%
rename from src/server/ipc/client.js
rename to src/server/node/ipc/client.mjs
index 2f850c3b..5e17545e 100644
--- a/src/server/ipc/client.js
+++ b/src/server/node/ipc/client.mjs
@@ -1,10 +1,10 @@
-var EventEmitter = require('events').EventEmitter
+import {EventEmitter} from 'events'
var hearbeatInterval = 25000,
hearbeatTimeout = 5000,
dieTimeout = 60000
-class Socket extends EventEmitter {
+class Client extends EventEmitter {
constructor(ws, id, address) {
@@ -97,9 +97,9 @@ class Socket extends EventEmitter {
}
- send(event, data) {
+ send(packet) {
- var packet = JSON.stringify([event, data])
+ // see IpcServer.send
if (this.connected()) {
this.socket.send(packet)
@@ -123,4 +123,4 @@ class Socket extends EventEmitter {
}
-module.exports = Socket
+export default Client
diff --git a/src/server/node/ipc/server.mjs b/src/server/node/ipc/server.mjs
new file mode 100644
index 00000000..b3d707fb
--- /dev/null
+++ b/src/server/node/ipc/server.mjs
@@ -0,0 +1,92 @@
+import {WebSocketServer} from 'ws'
+import Client from './client.mjs'
+import * as settings from '../settings.mjs'
+import Callbacks from './callbacks.mjs'
+
+class IpcServer {
+
+ constructor(webServer, oscServer) {
+
+ this.clients = {}
+ this.webServer = webServer
+ this.oscServer = oscServer
+ this.server = new WebSocketServer({server: webServer.server})
+ this.callbacks = new Callbacks(this, webServer, oscServer)
+
+
+ this.server.on('connection', (socket, req)=>{
+ var url = req.url.split('/'),
+ auth = url.pop().replace('_', '/'),
+ id = url.pop()
+
+ if (settings.read('authentication')) {
+ if (settings.read('authentication') !== Buffer.from(auth, 'base64').toString()) {
+ console.log(`(WARNING) Client connexion refused for ${req.connection.remoteAddress} (authentication failed)`)
+ socket.close()
+ return
+ }
+ }
+
+
+ if (!id) return
+
+ id = decodeURI(id)
+
+ if (!this.clients[id]) {
+
+ var client = new Client(socket, id, req.connection.remoteAddress)
+ this.clients[id] = client
+
+ var customModule = settings.read('custom-module')
+ for (let name of this.callbacks.getEvents()) {
+ client.on(name, (data)=>{
+ if (customModule) {
+ oscServer.customModuleEventEmitter.emit(name, data, {address: client.address, id: client.id})
+ }
+ this.callbacks[name](data, client.id)
+ })
+ }
+
+ client.on('destroyed', ()=>{
+ delete this.clients[id]
+ })
+
+ } else {
+
+ this.clients[id].open(socket)
+ this.clients[id].flush()
+
+ }
+
+ this.clients[id].emit('created')
+
+ })
+
+ }
+
+ send(event, data, id, except) {
+
+ var packet = JSON.stringify([event, data])
+
+ if (id) {
+ // send to a single client
+ if (this.clients[id]){
+ this.clients[id].send(packet)
+ }
+
+ } else {
+ // send to all clients except one if specified
+ for (let id in this.clients) {
+ if (id != except) {
+ this.clients[id].send(packet)
+ }
+ }
+
+ }
+
+ }
+
+
+}
+
+export default IpcServer
diff --git a/src/server/node/midi.mjs b/src/server/node/midi.mjs
new file mode 100644
index 00000000..9cb7ee17
--- /dev/null
+++ b/src/server/node/midi.mjs
@@ -0,0 +1,203 @@
+import {PythonShell} from 'python-shell'
+import fs from 'fs'
+import path from 'path'
+import {EventEmitter} from 'events'
+import * as settings from './settings.mjs'
+
+
+var scriptPath = __dirname.includes('server/node') ?
+ path.resolve(__dirname, '../python') : // src folder structure
+ path.resolve(__dirname, './python') // app folder structure with rollup chunking
+
+var midiBinaries = {
+ x64: {
+ linux: 'osc-midi-linux',
+ darwin: 'osc-midi-osx',
+ win32: 'osc-midi-windows.exe'
+ },
+ arm64:{
+ darwin: 'osc-midi-osx',
+ }
+}
+
+var expectMidiBinaries = fs.existsSync(path.resolve(scriptPath, './.expect-midi-bin')),
+ expectMidiBinariesError = false
+
+var pythonPathOverride
+if (midiBinaries[process.arch] && midiBinaries[process.arch][process.platform]) {
+ var p = path.resolve(scriptPath, midiBinaries[process.arch][process.platform])
+ if (fs.existsSync(p)) {
+ pythonPathOverride = p
+ } else if (expectMidiBinaries) {
+ expectMidiBinariesError = true
+ }
+}
+
+class MidiConverter extends EventEmitter{
+
+ constructor() {
+
+ super()
+
+ if (expectMidiBinariesError) MidiConverter.midiBinariesError()
+
+ this.running = false
+ this.restarting = false
+ this.py = {}
+
+ this.start()
+
+
+ process.on('message', (m) => {
+ if (m == 'midiRestart') {
+ this.restart()
+ }
+ })
+
+ }
+
+ start() {
+
+ if (this.running) return
+
+ this.py = new PythonShell('midi.py', Object.assign({
+ args: [
+ '--params',
+ settings.read('debug') ? 'debug' : '',
+ ...settings.read('midi')
+ ],
+ pythonPath: MidiConverter.getPythonPath()
+ }, {scriptPath, mode:'text'}))
+
+ this.py.childProcess.on('error', (e)=>{
+ if (e.code === 'ENOENT') {
+ console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
+ } else {
+ console.error(`(ERROR, MIDI) ${e.message}`)
+ }
+ })
+
+ this.py.childProcess.on('exit', (code)=>{
+ if (code === null && !this.restarting) console.error('(ERROR, MIDI) Midi bridge process crashed')
+ this.running = false
+ this.emit('stopped')
+ })
+
+ this.running = true
+
+ }
+
+ stop() {
+
+ if (this.running) this.py.childProcess.kill()
+
+ }
+
+ restart() {
+
+ if (this.running) {
+ this.restarting = true
+ this.once('stopped', ()=>{
+ this.start()
+ this.restarting = false
+ })
+ this.stop()
+ }
+ }
+
+ send(data) {
+
+ if (!this.running) return
+
+ var args = []
+ for (let i in data.args) {
+ args.push(data.args[i].value)
+ }
+
+ this.py.send(JSON.stringify([data.port, data.address, ...args]))
+
+ }
+
+
+
+ init(receiveOsc) {
+
+ this.receiveOsc = receiveOsc
+ this.py.on('message', (message)=>{
+ MidiConverter.parseIpc(message, this)
+ })
+
+ }
+
+ static parseIpc(message, instance) {
+
+ // console.log(message)
+ var name, data
+ try {
+ [name, data] = JSON.parse(message)
+ } catch (err) {
+ if (settings.read('debug')) console.error(`(ERROR, MIDI) Unparsed python log:\n ${message}`)
+ }
+ if (name == 'log') {
+ if (data.indexOf('ERROR') > -1) {
+ console.error(data)
+ } else {
+ console.log(data)
+ }
+ } else if (name == 'debug') {
+ if (data.indexOf('in:') === 0) {
+ console.log('\x1b[36m(DEBUG, MIDI)', data, '\x1b[0m')
+ } else if (data.indexOf('out:') === 0) {
+ console.log('\x1b[35m(DEBUG, MIDI)', data, '\x1b[0m')
+ } else {
+ console.log('(DEBUG, MIDI) ' + data)
+ }
+ } else if (name == 'osc') {
+ instance.receiveOsc(data)
+ } else if (name == 'error') {
+ console.error('(ERROR, MIDI) ' + data)
+ }
+
+ }
+
+ static list() {
+
+ if (expectMidiBinariesError) MidiConverter.midiBinariesError()
+
+ PythonShell.run('midi.py', Object.assign({pythonPath: MidiConverter.getPythonPath(), args: ['--params', 'list-only']}, {scriptPath, mode:'text'}), function(e, results) {
+ if (e) {
+ if (e.code === 'ENOENT') {
+ console.error(`(ERROR, MIDI) Could not find python binary: ${e.message.replace(/spawn (.*) ENOENT/, '$1')}`)
+ } else {
+ console.error(`(ERROR, MIDI) ${e.message}`)
+ }
+ }
+
+ for (let r of results) {
+ MidiConverter.parseIpc(r)
+ }
+ })
+
+ }
+
+ static getPythonPath() {
+
+ var pythonPath = settings.read('midi') ? settings.read('midi').filter(x=>x.includes('path=')).map(x=>x.split('=')[1])[0] : undefined
+
+ if (!pythonPath && pythonPathOverride) pythonPath = pythonPathOverride
+
+ return pythonPath
+
+ }
+
+ static midiBinariesError() {
+
+ console.error(`(ERROR, MIDI) Could not find midi binary file ${p}\nIt may have been deleted by your antivirus.`)
+ console.log('(INFO, MIDI) Falling back to python implementation (see https://openstagecontrol.ammd.net/docs/midi/midi-configuration/).')
+ expectMidiBinariesError = false
+
+ }
+
+}
+
+export default MidiConverter
diff --git a/src/server/options.js b/src/server/node/options.mjs
similarity index 80%
rename from src/server/options.js
rename to src/server/node/options.mjs
index 0f265e28..37358895 100644
--- a/src/server/options.js
+++ b/src/server/node/options.mjs
@@ -1,6 +1,6 @@
-var fs = require('fs')
+import fs from 'fs'
-module.exports = {
+export default {
's': {alias: 'send', type: 'array', describe: 'default targets for all widgets (ip: port / domain: port / midi: port_name pairs)',
check: (s)=>{
return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/) && !item.match(/^midi:.*$/)) ?
@@ -17,7 +17,7 @@ module.exports = {
return fs.existsSync(arg) ? true : 'State file not found: ' + arg
}
},
- 'c': {alias: 'custom-module', type: 'string', file: {name: 'OSC Custom module (.js)', extensions: ['js']}, describe: 'custom module file to load (.js)',
+ 'c': {alias: 'custom-module', type: 'string', file: {name: 'OSC Custom module (.js)', extensions: ['js']}, describe: 'custom module file to load (.js)\n WARNING: custom module can access the file system, use at your own risk.',
check: (arg)=>{
return fs.existsSync(arg) ? true : 'Custom module file not found: ' + arg
},
@@ -42,7 +42,7 @@ module.exports = {
true : 'Port must be an integer >= 1024'
}
},
- 'tcp-targets': {type: 'array', describe: 'tcp servers to connect to (ip: port pairs), does not susbtitute for --send',
+ 'tcp-targets': {type: 'array', describe: 'tcp servers to connect to (ip: port pairs), does not substitute for --send',
check: (s, argv)=>{
if (!argv['tcp-port']) return '--tcp-port must be set'
return s.some(item=>!item.match(/^[^:]*:[0-9]{4,5}$/)) ?
@@ -51,14 +51,14 @@ module.exports = {
},
'm': {alias: 'midi', type: 'array', describe: 'midi router settings',
check: (o)=>{
- var err = o.filter(item=>!item.match(/^(list|debug|jack|sysex|mtc|pc_offset|path=(.*)|[^:]+:(virtual|[^,]+,[^,]+))$/))
+ var err = o.filter(item=>!item.match(/^(list|debug|jack|sysex|mtc|rpn|nrpn|active_sensing|note_off_velocity|no_auto_note_off|pc_offset|path=(.*)|[^:]+:(virtual|[^,]+,[^,]+))$/))
return err.length ? `Invalid option${err.length > 1 ? 's' : ''}: ${err.join(', ')}` : true
}
},
'd': {alias: 'debug', type: 'boolean', describe: 'log received osc messages in the console'},
'n': {alias: 'no-gui', type: 'boolean', describe: 'disable default gui'},
'fullscreen': {type: 'boolean', describe: 'launch in fullscreen mode (only affects the default client gui)'},
- 't': {alias: 'theme', type: 'array', describe: 'theme name or path (multiple values allowed)'},
+ 't': {alias: 'theme', type: 'array', file: {name: 'css file (.css)', extensions: ['css']}, describe: 'theme name or path (multiple values allowed)'},
'client-options': {type: 'array', describe: 'client options (opt=value pairs)',
check: (o)=>{
return o.some(item=>!item.match(/^[^=]*=[^=]*$/)) ?
@@ -85,7 +85,7 @@ module.exports = {
return a.match(/[^:]*:[^:]+/) ? true : 'Auth must be a user:password pair.'
}
},
- 'instance-name': {type: 'string', describe: 'used to differenciate multiple instances in a zeroconf network'},
+ 'instance-name': {type: 'string', describe: 'used to differentiate multiple instances in a zeroconf network'},
'use-ssl': {type: 'boolean', describe: 'set to true to use HTTPS protocol instead of HTTP (a self-signed certificate will be created)'},
// cli only
@@ -93,5 +93,18 @@ module.exports = {
'inspect': {type: 'boolean', describe: 'enable node/electron inspector', launcher: false},
'cache-dir': {type: 'string', describe: 'override default cache directory', launcher: false},
'config-file': {type: 'string', describe: 'override default config file (defaults to cache-dir/config.json)', launcher: false},
- 'docs': {type: 'boolean', describe: 'serve documentation website locally and open it with the system\'s default browser', launcher: false}
+ 'docs': {type: 'boolean', describe: 'serve documentation website locally and open it with the system\'s default browser', launcher: false},
+ 'client-position': {type: 'string', describe: 'position of the client window ("x,y" pair of integers)', launcher: false,
+ check: (s)=>{
+ return !s.match(/^[0-9]+,[0-9]+$/) ?
+ 'Position must a x,y pair of integers' : true
+ }
+ },
+ 'client-size': {type: 'string', describe: 'size of the client window ("width,height" pair of integers)', launcher: false,
+ check: (s)=>{
+ return !s.match(/^[0-9]+,[0-9]+$/) ?
+ 'Size must a x,y pair of integers' : true
+ }
+ },
+ 'no-qrcode': {type: 'boolean', describe: 'disable qrcode when the server starts', launcher: false}
}
diff --git a/src/server/osc/index.js b/src/server/node/osc/index.mjs
similarity index 51%
rename from src/server/osc/index.js
rename to src/server/node/osc/index.mjs
index 40b84483..4b0444c0 100644
--- a/src/server/osc/index.js
+++ b/src/server/node/osc/index.mjs
@@ -1,26 +1,37 @@
-var ipc = require('../server').ipc,
- settings = require('../settings'),
- tcpInPort = settings.read('tcp-port'),
- debug = settings.read('debug'),
- midi = settings.read('midi') ? require('../midi') : false,
- oscUDPServer = require('./udp'),
- oscTCPServer = require('./tcp'),
- EventEmitter = require('events').EventEmitter,
- CustomModule = require('../custom-module')
+import {EventEmitter} from 'events'
+import * as settings from '../settings.mjs'
+import OscUDPServer from './udp.mjs'
+import OscTCPServer from './tcp.mjs'
+import CustomModule from '../custom-module.mjs'
+import MidiServer from '../midi.mjs'
-
-if (midi) midi = new midi()
-
-class OscServer {
+export default class OscServer {
constructor(){
+ this.oscUDPServer = new OscUDPServer()
+ this.oscTCPServer = new OscTCPServer()
+ this.tcpInPort = settings.read('tcp-port')
+ this.midiServer = settings.read('midi') ? new MidiServer() : null
+
+ this.debug = settings.read('debug')
+
this.customModuleEventEmitter = new EventEmitter()
this.customModule = settings.read('custom-module') ? new CustomModule(settings.read('custom-module'), {
app: this.customModuleEventEmitter,
+ restartMidiBackend: ()=>{if (this.midiServer) this.midiServer.restart()},
+ tcpServer: this.oscTCPServer,
sendOsc: this.sendOsc.bind(this),
receiveOsc: this.receiveOsc.bind(this),
send: (host, port, address, ...args)=>{
+ if (host.indexOf(':') > -1) {
+ args.unshift(address)
+ address = port
+ var split = host.split(':')
+ host = split[0]
+ port = parseInt(split[1])
+ }
+
this.sendOsc({host, port, address, args:args.map(x=>this.parseArg(x))})
},
receive: (host, port, address, ...args)=>{
@@ -30,22 +41,30 @@ class OscServer {
if (port !== undefined) args.unshift(port)
address = host
host = port = undefined
+ } else if (host.indexOf(':') > -1) {
+ args.unshift(address)
+ address = port
+ var split = host.split(':')
+ host = split[0]
+ port = parseInt(split[1])
}
var lastArg = args[args.length - 1],
options = {}
if (typeof lastArg === 'object' && lastArg !== null && lastArg.clientId !== undefined) {
options = args.pop()
}
- this.receiveOsc({host, port, address, args:args.map(x=>this.parseArg(x))}, options.clientId)
+ this.receiveOsc({host, port, address, args:args.map(x=>this.parseArg(x, null, true)), cm: 1}, options.clientId)
},
}) : {}
}
- parseArg(arg, type){
+ parseArg(arg, type, allowObjects = false){
if (arg === null) return null
+ if (typeof arg === 'object' && arg.type && arg.type.length === 1) return arg
+
if (type && type[0].match(/[bhtdscrmifTFNI]/)) {
type = type[0]
@@ -72,13 +91,19 @@ class OscServer {
case 'number':
return {type: 'f', value: arg}
case 'boolean':
- return {type: arg ? 'T' : 'F'}
+ return {type: arg ? 'T' : 'F', value: arg}
case 'string':
- return {type: 's', value:arg}
- case 'object':
- if (arg.type) return arg
+ return {type: 's', value: arg}
default:
- return {type: 's', value:JSON.stringify(arg)}
+ if (allowObjects) {
+ // Allow js objects in args when receiving from a custom module
+ // they will eventually be serialized (as json) with the rest of
+ // the ws message but the client will de-serialize it automatically
+ // note: type "o" is off-spec, but we don't use typetag in this case anyway
+ return {type: 'o', value: arg}
+ } else {
+ return {type: 's', value: JSON.stringify(arg)}
+ }
}
}
@@ -88,7 +113,7 @@ class OscServer {
if (data.host == 'midi') {
- if (midi) midi.send(data)
+ if (this.midiServer) this.midiServer.send(data)
} else {
@@ -102,23 +127,25 @@ class OscServer {
return
}
- if (tcpInPort && oscTCPServer.clients[data.host] && oscTCPServer.clients[data.host][data.port]) {
+ if (this.tcpInPort && this.oscTCPServer.clients[data.host] && this.oscTCPServer.clients[data.host][data.port]) {
- oscTCPServer.clients[data.host][data.port].send({
+ this.oscTCPServer.clients[data.host][data.port].send({
address: data.address,
args: data.args
})
} else {
- oscUDPServer.send({
+ this.oscUDPServer.send({
address: data.address,
args: data.args
}, data.host, data.port)
}
- if (debug) console.log('(DEBUG, OSC) Out: ',{address:data.address, args: data.args}, 'To: ' + data.host + ':' + data.port)
+ if (this.debug) {
+ console.log('\x1b[35m(DEBUG, OSC) Out: ', `{ address: '${data.address}', args: `, data.args, '} To: ' + data.host + ':' + data.port, '\x1b[0m')
+ }
}
@@ -135,23 +162,33 @@ class OscServer {
if (data.args.length==1) data.args = data.args[0]
- ipc.send('receiveOsc', data, clientId)
+ this.ipcServer.send('receiveOsc', data, clientId)
- if (debug) console.log('(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port)
+ if (this.debug) console.log('\x1b[36m(DEBUG, OSC) In: ', {address:data.address, args: data.args}, 'From: ' + data.host + ':' + data.port, '\x1b[0m')
}
oscInFilter(data){
if (this.customModule.oscInFilter) {
- return this.customModule.oscInFilter(data)
+ try {
+ return this.customModule.oscInFilter(data)
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE)', e)
+ return data
+ }
} else {
return data
}
}
oscOutFilter(data){
if (this.customModule.oscOutFilter) {
- return this.customModule.oscOutFilter(data)
+ try {
+ return this.customModule.oscOutFilter(data)
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE)', e)
+ return data
+ }
} else {
return data
}
@@ -174,11 +211,11 @@ class OscServer {
}
}
+ start(ipcServer){
+ this.ipcServer = ipcServer
- init(){
-
- if (midi) midi.init((data)=>{
+ if (this.midiServer) this.midiServer.init((data)=>{
data = this.oscInFilter({address: data.address, args: data.args, host: data.host, port: data.port})
@@ -188,30 +225,33 @@ class OscServer {
})
- oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
- oscUDPServer.open()
+ this.oscUDPServer.on('message', this.oscInHandlerWrapper.bind(this))
+ this.oscUDPServer.start()
if (settings.read('tcp-port')) {
- oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
- oscTCPServer.open()
+ this.oscTCPServer.on('message', this.oscInHandlerWrapper.bind(this))
+ this.oscTCPServer.start()
}
if (this.customModule.init) {
- this.customModule.init()
+ try {
+ this.customModule.init()
+ } catch(e) {
+ console.error('(ERROR, CUSTOM MODULE)', e)
+ }
}
}
+ stop() {
-}
+ if (this.customModule.stop) this.customModule.stop()
+ if (this.midiServer) this.midiServer.stop()
+ }
-var oscServer = new OscServer()
-oscServer.init()
-
-module.exports = {
- server: oscServer,
- send: function(host, port, address, args, typeTags, clientId) {
+ send(host, port, address, args, typeTags, clientId) {
+ // public send function
var message = []
@@ -224,18 +264,18 @@ module.exports = {
for (var i = 0; i < args.length; i++) {
- typeTag = typeTags[i] || typeTag
- arg = oscServer.parseArg(args[i], typeTag)
+ if (typeTags && typeTags[i]) typeTag = typeTags[i]
+ arg = this.parseArg(args[i], typeTag)
if (arg !== null) message.push(arg)
}
}
- var data = oscServer.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
+ var data = this.oscOutFilter({address:address, args: message, host: host, port: port, clientId: clientId})
- oscServer.sendOsc(data)
+ this.sendOsc(data)
+
+ }
- },
- midi:midi
}
diff --git a/src/server/node/osc/osc.mjs b/src/server/node/osc/osc.mjs
new file mode 100644
index 00000000..4dc68d46
--- /dev/null
+++ b/src/server/node/osc/osc.mjs
@@ -0,0 +1,7 @@
+import osc from 'osc/src/osc.js'
+import transports from 'osc/src/platforms/osc-node.js'
+
+osc.UDPPort = transports.UDPPort
+osc.TCPSocketPort = transports.TCPSocketPort
+
+export default osc
diff --git a/src/server/osc/tcp.js b/src/server/node/osc/tcp.mjs
similarity index 79%
rename from src/server/osc/tcp.js
rename to src/server/node/osc/tcp.mjs
index 89d76546..b1096257 100644
--- a/src/server/osc/tcp.js
+++ b/src/server/node/osc/tcp.mjs
@@ -1,10 +1,8 @@
-var osc = require('./osc'),
- EventEmitter = require('events').EventEmitter,
- settings = require('../settings'),
- zeroconf = require('../zeroconf'),
- tcpInPort = settings.read('tcp-port'),
- tcpTargets = settings.read('tcp-targets'),
- net = require('net')
+import {EventEmitter} from 'events'
+import net from 'net'
+import * as settings from '../settings.mjs'
+import osc from './osc.mjs'
+import zeroconf from '../zeroconf'
class OscTCPClient extends EventEmitter {
@@ -25,7 +23,7 @@ class OscTCPClient extends EventEmitter {
this.port = new osc.TCPSocketPort(this.options)
this.port.on('error', (err)=>{
- console.error(`(ERROR, TCP) ${err.message}`)
+ console.error('(ERROR, TCP)', err)
})
this.port.on('close', (hadErr)=>{
@@ -76,14 +74,18 @@ class OscTCPClient extends EventEmitter {
}
-class OscTCPServer extends EventEmitter {
+export default class OscTCPServer extends EventEmitter {
constructor() {
super()
+ this.port = settings.read('tcp-port')
+ this.targets = settings.read('tcp-targets')
+
this.clients = {}
+ this.server = net.createServer(this.bindSocket.bind(this))
}
bindSocket(socket) {
@@ -113,17 +115,17 @@ class OscTCPServer extends EventEmitter {
}
- open() {
+ start() {
- this.server = net.createServer(this.bindSocket.bind(this))
- this.server.listen({port: tcpInPort})
- for (var i in tcpTargets) {
+ this.server.listen({port: this.port})
+
+ for (var i in this.targets) {
this.addClient(new OscTCPClient({
metadata: true,
- address: tcpTargets[i].split(':')[0],
- port: tcpTargets[i].split(':')[1]
+ address: this.targets[i].split(':')[0],
+ port: this.targets[i].split(':')[1]
}))
}
@@ -132,15 +134,17 @@ class OscTCPServer extends EventEmitter {
name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
protocol: 'tcp',
type: 'osc',
- port: tcpInPort
+ port: this.port
}).on('error', (e)=>{
console.error(`Error: Zeroconf: ${e.message}`)
})
+ }
+
+ stop() {
+
+ this.server.close()
}
+
}
-
-var oscTCPServer = new OscTCPServer()
-
-module.exports = oscTCPServer
diff --git a/src/server/node/osc/udp.mjs b/src/server/node/osc/udp.mjs
new file mode 100644
index 00000000..cf056f4e
--- /dev/null
+++ b/src/server/node/osc/udp.mjs
@@ -0,0 +1,48 @@
+import osc from './osc.mjs'
+import * as settings from '../settings.mjs'
+import zeroconf from '../zeroconf.mjs'
+
+export default class OscUDPServer {
+
+ constructor() {
+
+ this.port = settings.read('osc-port') || settings.read('port') || 8080
+
+ this.server = new osc.UDPPort({
+ localAddress: '0.0.0.0',
+ localPort: this.port,
+ metadata: true,
+ broadcast: true
+ })
+
+ this.server.on('error', function(e) {
+ if (e.code === 'EADDRINUSE') {
+ console.error(`(ERROR, UDP) could not open port ${this.port} (already in use) `)
+ } else {
+ console.error('(ERROR, UDP)', e)
+ }
+ })
+
+ this.on = this.server.on.bind(this.server)
+ this.send = this.server.send.bind(this.server)
+ }
+
+ start() {
+
+ this.server.open()
+
+ zeroconf.publish({
+ name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
+ protocol: 'udp',
+ type: 'osc',
+ port: this.port
+ })
+
+ }
+
+ stop() {
+
+ this.server.close()
+
+ }
+}
diff --git a/src/server/node/qrcode.mjs b/src/server/node/qrcode.mjs
new file mode 100644
index 00000000..b9565315
--- /dev/null
+++ b/src/server/node/qrcode.mjs
@@ -0,0 +1,39 @@
+import QRCode from 'qrcode'
+import * as settings from './settings.mjs'
+
+export default function qrcode(mode, callback){
+
+ var qrstring = '',
+ promises = []
+
+ if (mode == 'file') {
+ promises.push(QRCode.toString(settings.appAddresses().pop(), {type:'svg', small: true, margin: 1}))
+ } else {
+ for (var add of settings.appAddresses().filter(a=>!a.includes('127.0.0.1') && !a.includes('localhost'))) {
+ if (mode == 'svg') {
+ promises.push(QRCode.toString(add,{type:'svg', small: true, margin: 1}))
+ } else if (mode == 'terminal') {
+ promises.push(QRCode.toString(add,{type:'terminal', small: true}))
+ }
+ }
+ }
+
+ Promise.all(promises).then(values=>{
+ for (var qr of values) {
+ if (mode === 'svg') {
+ qrstring += '' + qr + ''
+ if (values.length > 1) {
+ qrstring += '(' + add + ')'
+ }
+ } else {
+ qrstring += '\n' + qr.replace(/^/gm, ' ' + '')
+ if (values.length > 1) {
+ qrstring += ' (' + add + ')'
+ }
+ }
+ }
+ callback(qrstring)
+ })
+
+
+}
diff --git a/src/server/node/server.mjs b/src/server/node/server.mjs
new file mode 100644
index 00000000..3f7684fc
--- /dev/null
+++ b/src/server/node/server.mjs
@@ -0,0 +1,311 @@
+import http from 'http'
+import https from 'https'
+import {EventEmitter} from 'events'
+import path from 'path'
+import fs from 'fs'
+import send from 'send'
+import replaceStream from 'replacestream'
+import * as settings from './settings.mjs'
+import './ssl.mjs'
+import auth from './auth.mjs'
+import theme from './theme.mjs'
+import zeroconf from './zeroconf.mjs'
+import qrcode from './qrcode.mjs'
+import {resolveHomeDir} from './utils.mjs'
+
+class WebServer extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.ipcServer = null
+
+ this.qrcode = ''
+ this.prod = !process.argv[0].includes('node_modules'),
+ this.debug = settings.read('debug'),
+ this.remoteRoot = settings.read('remote-root')
+
+ var route = auth ? auth.check(this.httpRoute.bind(this)) : this.httpRoute.bind(this)
+ if (settings.read('use-ssl')) {
+ this.server = https.createServer(settings.read('ssl-certificate'), route)
+ } else {
+ this.server = http.createServer(route)
+ }
+
+ // file request resolution directories
+ // add theme dirs
+ this.resolveDirs = theme.files.map(x=>path.dirname(x)),
+ // dedupe
+ this.resolveDirs = this.resolveDirs.filter((x, index)=>{return this.resolveDirs.indexOf(x) === index})
+ // add remote root or absolute
+ this.resolveDirs.push(this.remoteRoot || '')
+
+ if (!this.prod) {
+ // add src root folder for debugging
+ this.resolveDirs.push(path.resolve(__dirname + '/../../../'))
+ }
+
+ this.ignoredNotFound = [
+ '/apple-touch-icon-precomposed.png',
+ '/favicon.ico',
+ '/apple-touch-icon.png'
+ ]
+
+
+ }
+
+ start(ipcServer) {
+
+ this.ipcServer = ipcServer
+
+
+ theme.on('update', ()=>{
+ ipcServer.send('reloadCss')
+ })
+
+ this.server.listen(settings.read('port') || 8080)
+
+ var proto = settings.read('use-ssl') ? https : http
+ proto.get(settings.appAddresses()[0] + '/osc-ping', {
+ auth: settings.read('authentication'),
+ rejectUnauthorized: false
+ },()=>{}).on('error', ()=>{this.httpCheck(false)})
+
+ this.httpCheckTimeout = setTimeout(()=>{this.httpCheck(false)}, 5000)
+
+ zeroconf.publish({
+ name: settings.infos.productName + (settings.read('instanceName') ? ' (' + settings.read('instanceName') + ')' : ''),
+ type: 'http',
+ port: settings.read('port') || 8080
+ }).on('error', (e)=>{
+ console.error(`(ERROR, ZEROCONF) ${e.message}`)
+ })
+
+ this.server.on('error', (e)=>{
+ if (e.code === 'EADDRINUSE') {
+ console.error(`(ERROR, HTTP) Could not open port ${this.port} (already in use) `)
+ } else {
+ console.error(`(ERROR, HTTP) ${e.message}`)
+ }
+ })
+
+ }
+
+ stop() {
+
+ this.server.close()
+
+ }
+
+ resolvePath(url, clientId) {
+
+ var sessionPath
+
+ if (this.ipcServer.clients[clientId]) {
+ sessionPath = path.dirname(this.ipcServer.clients[clientId].sessionPath)
+ }
+
+ url = resolveHomeDir(url)
+ url = url.split('?')[0]
+
+ for (var i = sessionPath ? -1 : 0; i < this.resolveDirs.length; i++) {
+ var p = i === -1 ? sessionPath : this.resolveDirs[i]
+
+ if (i == this.resolveDirs.length - 1 && this.remoteRoot) {
+ // strip out remote-root path from request url when resolving against it
+ url = url.replace(settings.read('remote-root'), '')
+ }
+
+ p = path.resolve(path.join(p, url))
+
+ if (fs.existsSync(p)) return p
+ }
+
+ if (this.debug && !this.ipcServer.clients[clientId]) {
+ // safari seems to be picky with cookies
+ if (clientId === undefined) console.log(`(DEBUG, HTTP) Could not resolve requested url ${url} (client id not found in http cookies)`)
+ // this should never happen, but just in case...
+ // it happens when importing css file from theme
+ else console.log(`(DEBUG, HTTP) Requested url ${url} not resolved against session path (unregistered client id ${clientId})`)
+ }
+
+ return false
+
+ }
+
+ sendFile(req, res, path) {
+
+ var fpath = path.split('?')[0]
+ var stats = fs.statSync(fpath)
+ if (!stats || !stats.isFile()) {
+ throw `File "${fpath}" not found.`
+ }
+ var lastModified = new Date(stats.mtime)
+ lastModified.setMilliseconds(0)
+ res.setHeader('Cache-Control', 'no-cache')
+ res.setHeader('Last-Modified', lastModified.toUTCString())
+ if (
+ req.headers['if-modified-since'] && new Date(req.headers['if-modified-since']).getTime() >= lastModified.getTime()
+ ) {
+ res.statusCode = 304
+ res.end()
+ return
+ }
+ return send(req, fpath).pipe(res)
+ }
+
+ httpRoute(req, res) {
+
+ var url = req.url
+
+ if (url === '/qrcode'){
+
+ // qrcode image
+
+ res.setHeader('Content-Type', 'image/svg+xml')
+ let str = this.qrcode,
+ buf = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from(str) : new Buffer(str)
+ res.write(buf)
+ res.end()
+
+ } else if (url === '/' || url.indexOf('/?') === 0) {
+
+ // index.html
+
+ var ip = req.connection.remoteAddress.replace('::ffff:', '')
+
+ var clientOptions = {}
+ if (settings.read('client-options')) {
+ for (var o of settings.read('client-options')) {
+ if (!o.includes('=')) continue
+ var [k, v] = o.split('=')
+ clientOptions[k] = v
+ }
+ }
+ res.setHeader('Cache-Control', 'no-store')
+ fs.createReadStream(path.resolve(__dirname + '/../../client/index.html'))
+ .pipe(replaceStream('', `
+ `))
+ .pipe(res)
+
+ } else if (url.indexOf('__APP_THEME__.css') != -1) {
+
+ // user theme(s)
+
+ res.setHeader('Content-Type', 'text/css')
+
+ var etag = settings.read('theme') ? theme.hash : 'empty-theme'
+ res.setHeader('Cache-Control', 'no-cache')
+ res.setHeader('ETag', etag)
+ if (req.headers['if-none-match'] && req.headers['if-none-match'] === etag) {
+ res.statusCode = 304
+ res.end()
+ return
+ }
+
+ if (settings.read('theme')) {
+ let str = theme.get(),
+ buf = Buffer.from && Buffer.from !== Uint8Array.from ? Buffer.from(str) : new Buffer(str)
+ res.write(buf)
+ } else {
+ res.write('')
+ }
+ res.end()
+
+ } else if (url.match(/^\/+__APP_DIR__\//)) {
+
+ // osc asset files
+
+ try {
+ this.sendFile(req, res, path.resolve(__dirname + '/../../' + url.replace('__APP_DIR__/', '')))
+ return true
+ } catch(e) {}
+
+
+ console.error(`(ERROR, HTTP) File not found: ${url}`)
+
+ if (url.match(/\/client\/index.*\.js/)) {
+ console.warn('(WARNING) It seems a client attempted to load an older version of the app,',
+ 'this may occur when using a homescreen bookmark on mobile devices.',
+ 'If that\'s the case, please delete it and browse to the app\'s url again.')
+ }
+
+ res.writeHead(404)
+ res.end()
+
+
+ } else {
+
+ // user files
+
+ // windows absolute path fix
+ url = url.replace('_:_', ':') // escaped drive colon
+ url = url.replace(/^\/([^/]*:)/, '$1') // strip leading slash
+
+ if (url.match(/\.(svg|jpg|jpeg|png|apng|gif|webp|tiff|xbm|bmp|ico|ttf|otf|woff|woff2|html|css|js)(\?[0-9]*)?$/i) ||
+ url.match(/\.mjs$/) && !this.prod) {
+
+ // Resolution order: session path, theme path, absolute path
+ var id
+ if (req.headers.cookie) {
+ id = (req.headers.cookie.match(/client_id=([^;]+)/) || [])[1]
+ }
+
+ var resolvedPath = this.resolvePath(decodeURI(url), id)
+
+ if (resolvedPath) {
+ try {
+ this.sendFile(req, res, resolvedPath)
+ return true
+ } catch(e) {}
+ }
+
+ if (!this.ignoredNotFound.includes(url)) {
+ console.error(`(ERROR, HTTP) File not found: ${url}`)
+ }
+
+ res.writeHead(404)
+ res.end()
+
+ } else if (url.includes('/osc-ping')) {
+ this.httpCheck(true)
+ } else {
+ res.writeHead(403)
+ res.end()
+ }
+
+ }
+
+ }
+
+ httpCheck(ok, error) {
+
+ if (!this.httpCheckTimeout) return
+
+ clearTimeout(this.httpCheckTimeout)
+ this.httpCheckTimeout = null
+
+ if (ok) {
+ console.log('(INFO) Server started, app available at \n ' + settings.appAddresses().join('\n '))
+ this.emit('serverStarted')
+ qrcode('file', (qr)=>{
+ this.qrcode = qr
+ })
+ } else {
+ if (error) {
+ console.error('(ERROR, HTTP) Server setup error: ' + error.message)
+ }
+ console.error('(ERROR, HTTP) Could not setup http server, maybe try a different port ?')
+ }
+
+ }
+}
+
+export default WebServer
diff --git a/src/server/settings.js b/src/server/node/settings.mjs
similarity index 54%
rename from src/server/settings.js
rename to src/server/node/settings.mjs
index 40dcd917..804c81e0 100644
--- a/src/server/settings.js
+++ b/src/server/node/settings.mjs
@@ -1,26 +1,34 @@
-var path = require('path'),
- fs = require('fs'),
- yargs = require('yargs'),
- infos = require('../../package.json'),
- options = require('./options'),
- address = require('./address')
+import path from 'path'
+import fs from 'fs'
+import yargs from 'yargs'
+import envPaths from 'env-paths'
+import infos from '../../../package.json'
+import options from './options.mjs'
+import address from './address.mjs'
-// This prevents argv parsing to be breaked when the app is packaged (executed without 'electron' prefix)
-var firstArgIndex = path.basename(process.argv[0]).match(/electron|node/) ? 2 : 1
+var argv = process.argv.slice()
-// on windows, electron stops parsing after the first argument containing a colon
+// Note : on windows, electron stops parsing after the first argument containing a colon
// https://github.com/electron/electron/pull/13039
// windows cli users need to add a double dash (--) before their options to avoid that
// it must be stripped to let yargs work normally
-if (process.argv[firstArgIndex] === '--') process.argv.splice(firstArgIndex, 1)
-var argv = yargs(process.argv.slice(firstArgIndex))
+// rmeove all args before the first actual cli arg
+while (argv.length) {
+ if (argv[0][0] != '-' || argv[0] == '--') {
+ argv.splice(0, 1)
+ } else if (argv[0][0] == '-' ) {
+ break
+ }
+}
+
+argv = yargs(argv)
.parserConfiguration({'boolean-negation': false})
.help('help').usage('\nUsage:\n $0 [options]').alias('h', 'help')
.options(options)
.check((argv)=>{
var err = []
- for (key in options) {
+ for (let key in options) {
if (options[key].check && argv[key] != undefined) {
var c = options[key].check(argv[key],argv)
if (c!==true) {
@@ -33,12 +41,6 @@ var argv = yargs(process.argv.slice(firstArgIndex))
.strict()
.version(infos.version).alias('v','version')
-// litle hack to align long-only-options correctly
-var h = argv.getUsageInstance().help
-argv.getUsageInstance().help = ()=>{
- return h().replace(/^\s{2}--([^\s]*)\s{4}(\s*)/gm, ' --$1$2')
-}
-
argv = argv.argv
delete argv._
delete argv.$0
@@ -68,7 +70,7 @@ var cli = false
for (let i in argv) {
if (!cliOnly.includes(i)) cli = true
}
-if (process.title === 'node' || process.title === 'node.exe' || process.env.ELECTRON_RUN_AS_NODE) {
+if (!process.versions.electron || process.env.ELECTRON_RUN_AS_NODE) {
cli = true
}
@@ -79,6 +81,12 @@ var settings = {
checkForUpdates: true
}
+// store cli-only options (read-only)
+for (let k in argv) {
+ if (options[k] && options[k].launcher === false) {
+ settings[k] = argv[k]
+ }
+}
@@ -89,7 +97,6 @@ var baseDir, configPath, configPathExists = true, config = {}
if (argv['cache-dir']) {
baseDir = path.isAbsolute(argv['cache-dir']) ? argv['cache-dir'] : path.resolve(process.cwd(), argv['cache-dir'])
} else {
- envPaths = require('env-paths')
baseDir = envPaths(infos.name, {
suffix: ''
}).config
@@ -111,9 +118,21 @@ if (configPathExists) {
} else {
configPath = path.join(baseDir, 'config.json')
}
- try {
- config = JSON.parse(fs.readFileSync(configPath,'utf-8'))
- } catch(e) {}
+ if (fs.existsSync(configPath)) {
+ try {
+ config = JSON.parse(fs.readFileSync(configPath,'utf-8'))
+ } catch(e) {
+ console.error('(ERROR) Could not read config from file:' + configPath)
+ console.error(e)
+ }
+ } else {
+ try {
+ fs.writeFileSync(configPath, '{}')
+ } catch(e) {
+ console.error('(ERROR) Could not create config file:' + configPath)
+ console.error(e)
+ }
+ }
if (cli) {
for (let k in config) {
if (k === 'options') continue
@@ -136,42 +155,57 @@ if (!configPath) {
/////////////////
+export {
+ options,
+ cli,
+ infos,
+ baseDir as configPath
+}
-module.exports = {
- options: options,
- read: function(key){
- return settings.options[key] !== undefined ? settings.options[key] : settings[key]
- },
- write:function(key, value, tmp) {
+export function read(key){
+ return settings.options[key] !== undefined ? settings.options[key] : settings[key]
+}
+export function write(key, value, tmp, sync) {
- settings[key] = value
+ settings[key] = value
- if (!tmp && configPathExists) {
+ if (!tmp && configPathExists) {
- if (process.send) {
- // server running as child process of launcher
- // -> just pass the modification to the launcher process
- process.send(['settings.write', [key, value]])
+ if (process.send) {
+ // server running as child process of launcher
+ // -> just pass the modification to the launcher process
+ process.send(['settings.write', [key, value]])
+ } else {
+ config[key] = value
+ if (config.options) {
+ // don't save cli-only options
+ for (var k in config.options) {
+ if (options[k] && options[k].launcher === false) {
+ delete config.options[k]
+ }
+ }
+ }
+ if (sync) {
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 4))
} else {
- config[key] = value
fs.writeFile(configPath, JSON.stringify(config, null, 4), function(err, data) {
if (err) throw err
})
-
}
}
- // we are in launcher process -> update server process' config
- if (global.serverProcess) {
- global.serverProcess.send(['settings.write', [key, value]])
- }
+ }
- },
- cli: cli,
- configPath: baseDir,
- infos: infos,
- appAddresses: ()=>address(module.exports.read('use-ssl') ? 'https://' : 'http://', settings.options.port || 8080)
+ // we are in launcher process -> update server process' config
+ if (global.serverProcess) {
+ global.serverProcess.send(['settings.write', [key, value]])
+ }
+
+}
+
+export function appAddresses() {
+ return address(read('use-ssl') ? 'https://' : 'http://', settings.options.port || 8080)
}
if (process.send) {
@@ -180,7 +214,7 @@ if (process.send) {
process.on('message', function(data) {
var [command, args] = data
if (command === 'settings.write') {
- module.exports.write(args[0], args[1], true)
+ write(args[0], args[1], true)
}
})
}
diff --git a/src/server/ssl.js b/src/server/node/ssl.mjs
similarity index 68%
rename from src/server/ssl.js
rename to src/server/node/ssl.mjs
index dbb4de22..468129d5 100644
--- a/src/server/ssl.js
+++ b/src/server/node/ssl.mjs
@@ -1,6 +1,7 @@
-var settings = require('./settings'),
- forge = require('node-forge'),
- pki = forge.pki,
+import forge from 'node-forge'
+import * as settings from './settings.mjs'
+
+var pki = forge.pki,
certificate = settings.read('ssl-certificate')
forge.options.usePureJavaScript = true
@@ -47,24 +48,27 @@ function createCertificate() {
}
-if (!certificate) {
+if (settings.read('use-ssl')){
- createCertificate()
+ if (!certificate) {
-} else {
-
- var cert = pki.certificateFromPem(certificate.cert)
-
- if (
- cert.serialNumber === '00' ||
- new Date() > new Date(cert.validity.notAfter) ||
- cert.subject.attributes[1].value !== settings.infos.productName
- ) {
- console.log('(INFO) Self-signed ssl certificate in cache has expired or is invalid')
createCertificate()
+
} else {
- console.log('(INFO) Using self-signed ssl certificate in cache')
+
+ var cert = pki.certificateFromPem(certificate.cert)
+
+ if (
+ cert.serialNumber === '00' ||
+ new Date() > new Date(cert.validity.notAfter) ||
+ cert.subject.attributes[1].value !== settings.infos.productName
+ ) {
+ console.log('(INFO) Self-signed ssl certificate in cache has expired or is invalid')
+ createCertificate()
+ } else {
+ console.log('(INFO) Using self-signed ssl certificate in cache')
+ }
+
}
-
}
diff --git a/src/server/node/theme.mjs b/src/server/node/theme.mjs
new file mode 100644
index 00000000..ec029c1e
--- /dev/null
+++ b/src/server/node/theme.mjs
@@ -0,0 +1,85 @@
+import fs from 'fs'
+import path from 'path'
+import chokidar from 'chokidar'
+import {EventEmitter} from 'events'
+import crypto from 'crypto'
+import * as settings from './settings.mjs'
+
+class Theme extends EventEmitter {
+
+ constructor() {
+
+ super()
+
+ this.defaultColor = '#151a24'
+ this.backgroundColor = this.defaultColor
+
+ this.css = []
+ this.watcher = null
+ this.themes = settings.read('theme') || []
+ this.files = []
+ this.hash = ''
+
+ if (!this.themes.length) return this
+
+ if (this.themes.length > 1 && fs.existsSync(this.themes.join(' '))) {
+
+ this.files.push(this.themes.join(' '))
+
+ } else {
+
+ for (let theme of this.themes) {
+
+ if (theme.includes('.css') && fs.existsSync(theme)) {
+ this.files.push(theme)
+ } else if (!theme.includes('.css') && fs.existsSync(path.resolve(__dirname + '/../../assets/themes/' + theme + '.css'))) {
+ this.files.push(path.resolve(__dirname + '/../../assets/themes/' + theme + '.css'))
+ } else {
+ console.error('(ERROR) Theme not found: "' + theme)
+ }
+ }
+
+ }
+
+ if (this.files.length) {
+
+ this.watcher = chokidar.watch(this.files, {awaitWriteFinish: {stabilityThreshold: 200}}).on('change', ()=>{
+ this.load()
+ this.emit('update')
+ })
+
+ }
+
+ this.load()
+
+ }
+
+ load() {
+
+ this.css = []
+
+ for (let i in this.files) {
+
+ try {
+ this.css.push(fs.readFileSync(this.files[i],'utf-8'))
+ } catch(err) {
+ console.error('(ERROR) Could not load theme "' + this.files[i])
+ }
+
+ }
+
+ this.hash = crypto.createHash('sha1').update(this.get()).digest('base64')
+
+ }
+
+ get() {
+
+ return this.css.join('\n')
+
+ }
+
+}
+
+var theme = new Theme()
+
+export default theme
diff --git a/src/server/node/utils.mjs b/src/server/node/utils.mjs
new file mode 100644
index 00000000..c73a4c30
--- /dev/null
+++ b/src/server/node/utils.mjs
@@ -0,0 +1,24 @@
+export function deepCopy(obj) {
+
+ var copy = obj
+
+ if (obj === null) {
+ return obj
+ }
+
+ if (typeof obj === 'object') {
+ copy = Array.isArray(obj) ? [] : {}
+ for (let key in obj) {
+ copy[key] = deepCopy(obj[key])
+ }
+ }
+
+ return copy
+
+}
+
+export function resolveHomeDir(p) {
+ // Resolve '~' to user's home directory
+ if (!p) return ''
+ return String(p).replace(/^(~|\/~)/, process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'])
+}
diff --git a/src/server/node/zeroconf.mjs b/src/server/node/zeroconf.mjs
new file mode 100644
index 00000000..8404aaaf
--- /dev/null
+++ b/src/server/node/zeroconf.mjs
@@ -0,0 +1,3 @@
+import zeroconf from 'bonjour'
+
+export default zeroconf()
diff --git a/src/server/osc/osc.js b/src/server/osc/osc.js
deleted file mode 100644
index 4da82ea9..00000000
--- a/src/server/osc/osc.js
+++ /dev/null
@@ -1,7 +0,0 @@
-var osc = require('osc/src/osc.js'),
- transports = require('osc/src/platforms/osc-node.js')
-
-osc.UDPPort = transports.UDPPort
-osc.TCPSocketPort = transports.TCPSocketPort
-
-module.exports = osc
diff --git a/src/server/osc/udp.js b/src/server/osc/udp.js
deleted file mode 100644
index f819ea5a..00000000
--- a/src/server/osc/udp.js
+++ /dev/null
@@ -1,28 +0,0 @@
-var osc = require('./osc'),
- settings = require('../settings'),
- zeroconf = require('../zeroconf'),
- oscInPort = settings.read('osc-port') || settings.read('port') || 8080
-
-var oscUDPServer = new osc.UDPPort({
- localAddress: '0.0.0.0',
- localPort: oscInPort,
- metadata: true,
- broadcast: true
-})
-
-oscUDPServer.on('error', function(e) {
- if (e.code === 'EADDRINUSE') {
- console.error(`(ERROR, UDP) could not open port ${oscInPort} (already in use) `)
- } else {
- console.error(`(ERROR, UDP) ${e.message}`)
- }
-})
-
-zeroconf.publish({
- name: settings.infos.productName + (settings.read('instance-name') ? ' (' + settings.read('instance-name') + ')' : ''),
- protocol: 'udp',
- type: 'osc',
- port: oscInPort
-})
-
-module.exports = oscUDPServer
diff --git a/src/server/python/head.py b/src/server/python/head.py
new file mode 100644
index 00000000..5f62ccf2
--- /dev/null
+++ b/src/server/python/head.py
@@ -0,0 +1,55 @@
+from sys import argv, stdin, stdout, version_info, version, exit, platform
+from binascii import hexlify, unhexlify
+import traceback
+import json as JSON
+import re
+
+def ipc_send(name, data):
+ print(JSON.dumps([name, data]))
+ stdout.flush()
+
+prebuilt_bin = 'osc-midi' in argv[0]
+
+try:
+ import rtmidi
+ from rtmidi.midiconstants import *
+
+ API = rtmidi.API_UNIX_JACK if 'jack' in argv else rtmidi.API_UNSPECIFIED
+ if API == rtmidi.API_UNIX_JACK and rtmidi.API_UNIX_JACK not in rtmidi.get_compiled_api():
+ API = rtmidi.API_UNSPECIFIED
+ ipc_send('log', '(ERROR, MIDI) python-rtmidi was not compiled with jack midi support, falling back to default API')
+
+ JACK = API == rtmidi.API_UNIX_JACK
+
+ in_dev = rtmidi.MidiIn(API, 'MIDI->OSC probe')
+ out_dev = rtmidi.MidiOut(API, 'OSC->MIDI probe')
+
+except Exception as e:
+ if prebuilt_bin:
+ ipc_send('log', '(ERROR, MIDI) error while loading MIDI bridge program:\n %s' % (e.message if hasattr(e, 'message') else e))
+ else:
+ ipc_send('log', '(ERROR, MIDI) error while loading python-rtmidi library (running with python %s):\n %s' % (".".join(map(str, version_info[:3])), e.message if hasattr(e, 'message') else e))
+ exit()
+
+if version_info.major == 3:
+ raw_input = input
+
+# option: print debug messages
+debug = 'debug' in argv
+# option: act as if displayed program is between 1-128 instead of 0-127
+program_change_offset = 'pc_offset' in argv
+# option: parse sysex
+ignore_sysex = 'sysex' not in argv
+# option: parse mtc
+ignore_mtc = 'mtc' not in argv
+# option: parse (n)rpn
+ignore_rpn = 'rpn' not in argv and 'nrpn' not in argv
+# option: parse active sensing
+ignore_active_sensing = 'active_sensing' not in argv
+# option: note off velocity (/note_on and /note_off instead of only /note and velocity 0 for note off)
+note_off_velocity = 'note_off_velocity' in argv
+# option: no auto note off (do not translate received note_on with velocity 0 to note off)
+no_auto_note_off = 'no_auto_note_off' in argv
+# option: list midi ports
+list_midi = 'list' in argv
+list_midi_exit = 'list-only' in argv
diff --git a/src/python/list.py b/src/server/python/list.py
similarity index 100%
rename from src/python/list.py
rename to src/server/python/list.py
diff --git a/src/python/midi.py b/src/server/python/main.py
similarity index 53%
rename from src/python/midi.py
rename to src/server/python/main.py
index 84af764a..76137c0a 100644
--- a/src/python/midi.py
+++ b/src/server/python/main.py
@@ -2,33 +2,21 @@ from head import *
from list import *
from utils import *
from mtc import *
+from rpn import *
-ipc_send('version', '1.7.2')
+argv = argv[argv.index('--params') + 1:]
-if 'list' in argv:
+if list_midi or list_midi_exit:
list()
-
-if 'list-only' in argv:
- list()
- exit()
-
-# option: act as if displayed program is between 1-128 instead of 0-127
-PROGRAM_CHANGE_OFFSET = 'pc_offset' in argv
-# option: parse sysex
-ignore_sysex = 'sysex' not in argv
-# option: parse mtc
-ignore_mtc = 'mtc' not in argv
+ if list_midi_exit:
+ exit()
inputs = {}
outputs = {}
for arg in argv:
- if 'python/midi.py' in arg:
-
- pass # in case we're using pre-compiled binaries
-
- elif type(arg) == str and ':' in arg:
+ if type(arg) == str and ':' in arg:
name, *ports = arg.split(':')
ports = ':'.join(ports) # port names may contain colons
@@ -37,18 +25,27 @@ for arg in argv:
outputs[name] = rtmidi.MidiOut(API, name if not JACK else name + '_out')
if debug:
- ipc_send('log','(DEBUG, MIDI) device "%s" created' % name)
+ ipc_send('debug','device "%s" created' % name)
if ports == 'virtual':
try:
- inputs[name].open_virtual_port('midi_in')
- outputs[name].open_virtual_port('midi_out')
+
+ if platform == 'darwin':
+ inputs[name].open_virtual_port('%s-in' % name)
+ outputs[name].open_virtual_port('%s-out' % name)
+ else:
+ inputs[name].open_virtual_port('midi_in')
+ outputs[name].open_virtual_port('midi_out')
+
if debug:
- ipc_send('log','(DEBUG, MIDI) virtual ports opened for device "%s"' % name)
+ ipc_send('debug','virtual ports opened for device "%s"' % name)
except:
- ipc_send('error', 'can\'t open virtual port "%s"' % name)
+ ipc_send('error', 'failed to open virtual ports for device "%s"' % name)
+ ipc_send('error', traceback.format_exc())
+ inputs[name] = None
+ outputs[name] = None
elif ',' in ports:
@@ -70,31 +67,33 @@ for arg in argv:
out_port = i
break
- if type(in_port) != int or in_port >= in_dev.get_port_count():
- ipc_send('error', 'can\'t connect to input port "%s"' % in_port)
- break
-
- if type(out_port) != int or out_port >= out_dev.get_port_count():
- ipc_send('error', 'can\'t connect to output port "%s"' % out_port)
- break
-
if in_port != -1:
try:
inputs[name].open_port(in_port, 'midi_in')
if debug:
- ipc_send('log','(DEBUG, MIDI) device "%s" connected to input port %s (%s)' % (name, in_port, in_dev.get_port_name(in_port)))
+ ipc_send('debug','device "%s" connected to input port %s (%s)' % (name, in_port, in_dev.get_port_name(in_port)))
except:
- ipc_send('error', 'can\'t connect input to port %i: %s' % (in_port, in_dev.get_port_name(in_port)))
+ if type(in_port) != int or in_port >= in_dev.get_port_count():
+ ipc_send('error', 'can\'t connect "%s" to input port "%s" (port not in list)' % (name, in_port))
+ else:
+ ipc_send('error', 'failed to connect "%s" to input port %s' % (name, in_port))
+ ipc_send('error', traceback.format_exc())
+ inputs[name] = None
if out_port != -1:
try:
outputs[name].open_port(out_port, 'midi_out')
if debug:
- ipc_send('log','(DEBUG, MIDI) device "%s" connected to output port %s (%s)' % (name, out_port, out_dev.get_port_name(out_port)))
+ ipc_send('debug','device "%s" connected to output port %s (%s)' % (name, out_port, out_dev.get_port_name(out_port)))
except:
- ipc_send('error', 'can\'t connect to output port %i: %s' % (out_port, out_dev.get_port_name(out_port)))
+ if type(out_port) != int or out_port >= out_dev.get_port_count():
+ ipc_send('error', 'can\'t connect "%s" to output port "%s" (port not in list)' % (name, out_port))
+ else:
+ ipc_send('error', 'failed to connect "%s" to output port %s' % (name, out_port))
+ ipc_send('error', traceback.format_exc())
+ outputs[name] = None
def create_callback(name):
@@ -116,7 +115,7 @@ def create_callback(name):
if not ignore_mtc and is_mtc(message):
mtc = mtc_decode(message, name)
- if mtc is None:
+ if mtc == None:
return
else:
osc['address'] = MIDI_TO_OSC[MIDI_TIME_CODE]
@@ -127,6 +126,22 @@ def create_callback(name):
v = ' '.join([hex(x).replace('0x', '').zfill(2) for x in message])
osc['args'].append({'type': 'string', 'value': v})
+
+ elif mtype == CONTROL_CHANGE and not ignore_rpn and is_rpn(message):
+ rpn = rpn_decode(message, name)
+ if rpn is not None:
+ osc['address'] = MIDI_TO_OSC[rpn[0]]
+ osc['args'].append({'type': 'i', 'value': rpn[1]})
+ osc['args'].append({'type': 'i', 'value': rpn[2]})
+ osc['args'].append({'type': 'i', 'value': rpn[3]})
+ ipc_send('osc', osc)
+ if debug:
+ t = 'NRPN' if rpn[0] == NRPN else 'RPN'
+ s = '%s: channel=%i, parameter=%i, value=%i'% (t, rpn[1], rpn[2], rpn[3])
+ ipc_send('debug','in: %s From: midi:%s' % (s, name))
+ # bypass (n)rpn CCs
+ return
+
else:
status = message[0]
@@ -135,12 +150,13 @@ def create_callback(name):
osc['args'].append({'type': 'i', 'value': channel})
if mtype == NOTE_OFF:
- message[2] = 0
+ if not note_off_velocity:
+ message[2] = 0
elif mtype == PITCH_BEND:
message = message[:1] + [message[1] + message[2] * 128] # convert 0-127 pair -> 0-16384 ->
- elif mtype == PROGRAM_CHANGE and PROGRAM_CHANGE_OFFSET:
+ elif mtype == PROGRAM_CHANGE and program_change_offset:
message[-1] = message[-1] + 1
for data in message[1:]:
@@ -148,7 +164,7 @@ def create_callback(name):
if debug:
- ipc_send('log','(DEBUG, MIDI) in: %s From: midi:%s' % (midi_str(message, name), name))
+ ipc_send('debug','in: %s From: midi:%s' % (midi_str(message, name), name))
ipc_send('osc', osc)
@@ -159,16 +175,18 @@ def create_callback(name):
try:
receive_midi(event, data)
except:
- ipc_send('log', '(ERROR, MIDI) %s' % traceback.format_exc())
+ ipc_send('error', traceback.format_exc())
return callback_error_wrapper
for name in inputs:
- inputs[name].set_callback(create_callback(name))
+ if inputs[name] != None:
- # sysex / mtc support
- inputs[name].ignore_types(ignore_sysex, ignore_mtc, True)
+ inputs[name].set_callback(create_callback(name))
+
+ # sysex / mtc / active sensing support
+ inputs[name].ignore_types(ignore_sysex, ignore_mtc, ignore_active_sensing)
def midi_message(status, channel, data1=None, data2=None):
@@ -189,11 +207,15 @@ sysexRegex = re.compile(r'([^0-9A-Fa-f])\1(\1\1)*')
def send_midi(name, event, *args):
if name not in outputs:
- ipc_send('log','(ERROR, MIDI) unknown output (%s)' % name)
+ ipc_send('error','unknown device "%s"' % name)
+ return
+
+ if outputs[name] == None:
+ ipc_send('error','device "%s" has no opened output port' % name)
return
if event not in OSC_TO_MIDI:
- ipc_send('log','(ERROR, MIDI) invalid address (%s)' % event)
+ ipc_send('error','invalid address (%s)' % event)
return
m = None
@@ -222,33 +244,42 @@ def send_midi(name, event, *args):
except:
pass
+ elif mtype == NRPN or mtype == RPN:
+ m = rpn_encode(mtype, args)
+ if m is not None:
+ for x in m:
+ outputs[name].send_message(x)
+ if debug:
+ t = 'NRPN' if mtype == NRPN else 'RPN'
+ s = '%s: channel=%i, parameter=%i, value=%i'% (t, args[0], args[1], args[2])
+ ipc_send('debug','out: %s To: midi:%s' % (s, name))
+ return
else:
args = [int(round(x)) for x in args]
m = [mtype, args[0]]
if mtype == NOTE_ON:
- if args[2] == 0:
+ if args[2] == 0 and not no_auto_note_off:
mtype = NOTE_OFF
elif mtype == PITCH_BEND:
- args = args[:1] + [args[1] & 0x7F, (args[1] >> 7) & 0x7F] # convert 0-16384 -> 0-127 pair
+ args = args[:1] + [args[1] & 0x7F, (args[1] >> 7) & 0x7F] # convert 0-16383 -> 0-127 pair
- elif mtype == PROGRAM_CHANGE and PROGRAM_CHANGE_OFFSET:
+ elif mtype == PROGRAM_CHANGE and program_change_offset:
args[-1] = args[-1] - 1
m = midi_message(mtype, *args)
if m == None:
- ipc_send('log','(ERROR, MIDI) could not convert osc to midi (%s %s)' % (event, " ".join([str(x) for x in args])))
+ ipc_send('error','could not convert osc to midi (%s %s)' % (event, " ".join([str(x) for x in args])))
else:
outputs[name].send_message(m)
-
if debug:
- ipc_send('log','(DEBUG, MIDI) out: %s To: midi:%s' % (midi_str(m, name), name))
+ ipc_send('debug','out: %s To: midi:%s' % (midi_str(m, name), name))
while True:
@@ -263,4 +294,4 @@ while True:
msg[1] = msg[1].lower()
send_midi(*msg)
except:
- ipc_send('log', '(ERROR, MIDI) %s' % traceback.format_exc())
+ ipc_send('error', traceback.format_exc())
diff --git a/src/server/python/midi.py b/src/server/python/midi.py
new file mode 100644
index 00000000..6152a218
--- /dev/null
+++ b/src/server/python/midi.py
@@ -0,0 +1,17 @@
+# python script for freezing dependencies but not the runtime code
+import os
+import importlib
+import sys
+
+# import all libs used at runtime
+# pyinstaller will freeze it
+import head
+
+if getattr(sys, 'frozen', False):
+ VAR_CWD = os.path.dirname(sys.executable)
+ sys.path.insert(1, VAR_CWD)
+
+sys.path.insert(1, os.getcwd())
+
+# dynamically import runtime code
+importlib.import_module('main')
diff --git a/src/python/mtc.py b/src/server/python/mtc.py
similarity index 100%
rename from src/python/mtc.py
rename to src/server/python/mtc.py
diff --git a/src/server/python/requirements.txt b/src/server/python/requirements.txt
new file mode 100644
index 00000000..a63392d8
--- /dev/null
+++ b/src/server/python/requirements.txt
@@ -0,0 +1,2 @@
+python-rtmidi == 1.5.8
+pyinstaller
diff --git a/src/server/python/rpn.py b/src/server/python/rpn.py
new file mode 100644
index 00000000..8e918ddb
--- /dev/null
+++ b/src/server/python/rpn.py
@@ -0,0 +1,109 @@
+from head import *
+
+NRPN = 256
+RPN = 257
+RPN_REGISTER = {}
+
+
+def is_rpn(message):
+
+ return (
+ message[1] == DATA_ENTRY_MSB or
+ message[1] == DATA_ENTRY_LSB or
+ message[1] == RPN_MSB or
+ message[1] == RPN_LSB or
+ message[1] == NRPN_MSB or
+ message[1] == NRPN_LSB
+ )
+
+def rpn_decode(message, port):
+ if port not in RPN_REGISTER:
+ RPN_REGISTER[port] = []
+ for i in range(16):
+ RPN_REGISTER[port].append({
+ 'type': '',
+ 'control_msb': -1,
+ 'control_lsb': -1,
+ 'value_msb': 0,
+ 'value_lsb': 0
+ })
+
+ status = message[0]
+ channel = (status & 0x0F)# + 1
+ send = False
+ check_reset = False
+
+ if message[1] == NRPN_MSB:
+ RPN_REGISTER[port][channel]['type'] = NRPN
+ RPN_REGISTER[port][channel]['control_msb'] = message[2]
+
+ elif message[1] == NRPN_LSB:
+ RPN_REGISTER[port][channel]['type'] = NRPN
+ RPN_REGISTER[port][channel]['control_lsb'] = message[2]
+ check_reset = True
+
+ elif message[1] == RPN_MSB:
+ RPN_REGISTER[port][channel]['type'] = RPN
+ RPN_REGISTER[port][channel]['control_msb'] = message[2]
+
+ elif message[1] == RPN_LSB:
+ RPN_REGISTER[port][channel]['type'] = RPN
+ RPN_REGISTER[port][channel]['control_lsb'] = message[2]
+ check_reset = True
+
+ elif message[1] == DATA_ENTRY_MSB:
+ RPN_REGISTER[port][channel]['value_msb'] = message[2]
+ RPN_REGISTER[port][channel]['value_lsb'] = 0
+ send = True
+
+ elif message[1] == DATA_ENTRY_LSB:
+ RPN_REGISTER[port][channel]['value_lsb'] = message[2]
+ send = True
+
+ if check_reset:
+ # (n)rpn null value
+ if (
+ RPN_REGISTER[port][channel]['control_msb'] == 127 and
+ RPN_REGISTER[port][channel]['control_lsb'] == 127
+ ):
+ RPN_REGISTER[port][channel]['control_msb'] = -1
+
+
+ if send and RPN_REGISTER[port][channel]['control_msb'] != -1:
+ return [
+ RPN_REGISTER[port][channel]['type'],
+ channel + 1,
+ RPN_REGISTER[port][channel]['control_msb'] * 128 + RPN_REGISTER[port][channel]['control_lsb'],
+ RPN_REGISTER[port][channel]['value_msb'] * 128 + RPN_REGISTER[port][channel]['value_lsb']
+ ]
+
+ return None
+
+
+def rpn_encode(mtype, args):
+
+ if len(args) != 3:
+ return None
+
+ channel, control, value = args
+ status = CONTROL_CHANGE | (channel - 1 & 0x0F)
+ return (
+ [status, 99 if mtype == NRPN else 101, control >> 7],
+ [status, 98 if mtype == NRPN else 100, control & 0x7F],
+ [status, 6, value >> 7],
+ [status, 38, value & 0x7F]
+ )
+
+ # rtmidi doesn't support running status
+ # return [
+ # 0xF0,0xF7,
+ # CONTROL_CHANGE | (channel - 1 & 0x0F),
+ # 99 if mtype == NRPN else 101,
+ # control >> 7,
+ # 98 if mtype == NRPN else 100,
+ # control & 0x7F,
+ # 6,
+ # value >> 7,
+ # 38,
+ # value & 0x7F
+ # ]
diff --git a/src/python/utils.py b/src/server/python/utils.py
similarity index 85%
rename from src/python/utils.py
rename to src/server/python/utils.py
index 8709034b..951f7d4c 100644
--- a/src/python/utils.py
+++ b/src/server/python/utils.py
@@ -1,5 +1,6 @@
from head import *
from mtc import *
+from rpn import *
MIDI_TO_OSC = {
NOTE_ON: '/note',
@@ -15,6 +16,7 @@ MIDI_TO_OSC = {
OSC_TO_MIDI = {
'/note': NOTE_ON,
+ '/note_off': NOTE_OFF,
'/control': CONTROL_CHANGE,
'/program': PROGRAM_CHANGE,
'/pitch': PITCH_BEND,
@@ -24,6 +26,16 @@ OSC_TO_MIDI = {
'/key_pressure': POLY_PRESSURE
}
+if note_off_velocity:
+ MIDI_TO_OSC[NOTE_OFF] = '/note_off'
+
+if not ignore_rpn:
+ MIDI_TO_OSC[NRPN] = '/nrpn'
+ MIDI_TO_OSC[RPN] = '/rpn'
+ OSC_TO_MIDI['/nrpn'] = NRPN
+ OSC_TO_MIDI['/rpn'] = RPN
+
+
def midi_str(message, port):
mtype = message[0] & 0xF0
@@ -48,7 +60,7 @@ def midi_str(message, port):
if mtype == NOTE_ON:
s = 'NOTE_ON: channel=%i, note=%i, velocity=%i' % (channel, message[1], message[2])
elif mtype == NOTE_OFF:
- s = 'NOTE_OFF: channel=%i, note=%i' % (channel, message[1])
+ s = 'NOTE_OFF: channel=%i, note=%i, velocity=%i' % (channel, message[1], message[2])
elif mtype == CONTROL_CHANGE:
s = 'CONTROL_CHANGE: channel=%i, cc=%i, value=%i'% (channel, message[1], message[2])
elif mtype == PROGRAM_CHANGE:
diff --git a/src/server/server.js b/src/server/server.js
deleted file mode 100644
index e05469f4..00000000
--- a/src/server/server.js
+++ /dev/null
@@ -1,191 +0,0 @@
-var settings = require('./settings'),
- http = require('http')
-
-function createServer(route) {
- if (settings.read('use-ssl')) {
- http = require('https')
- require('./ssl')
- return http.createServer(settings.read('ssl-certificate'), route)
-
- } else {
- return http.createServer(route)
- }
-}
-
-var urlparser = require('url'),
- path = require('path'),
- fs = require('fs'),
- send = require('send'),
- replaceStream = require('replacestream'),
- auth = require('./auth'),
- server = createServer(auth ? auth.check(httpRoute) : httpRoute),
- Ipc = require('./ipc/server'),
- ipc = new Ipc(server),
- theme = require('./theme').init(),
- zeroconf = require('./zeroconf'),
- prod = !process.argv[0].includes('node_modules'),
- osc = {},
- clients = {},
- httpCheckTimeout
-
-
-var clientOptions = {}
-if (settings.read('client-options')) {
- for (var o of settings.read('client-options')) {
- if (!o.includes('=')) continue
- var [k, v] = o.split('=')
- clientOptions[k] = v
- }
-}
-
-var resolveDirs = theme.files.map(x=>path.dirname(x))
-resolveDirs = resolveDirs.filter((x, index)=>{return resolveDirs.indexOf(x) === index})
-resolveDirs.push('') // absolute
-
-function httpRoute(req, res) {
-
- res.sendFile = (path)=>{
- var fpath = path.split('?')[0]
- if (!fs.existsSync(fpath)) throw `File "${fpath}" not found.`
- return send(req, fpath).pipe(res)
- }
-
- var url = req.url
-
- if (url === '/' || url.indexOf('/?') === 0) {
-
- var ip = req.connection.remoteAddress.replace('::ffff:', '')
-
- fs.createReadStream(path.resolve(__dirname + '/../client/index.html'))
- .pipe(replaceStream('