Compare commits

..

1 commit

Author SHA1 Message Date
jean-emmanuel
967fb3d549 build: fix build without github
script: remove infinite loop protection
2025-12-27 11:36:15 +01:00
243 changed files with 10783 additions and 9807 deletions

13
.babelrc Normal file
View file

@ -0,0 +1,13 @@
{
"presets": [
["@babel/env", {
"targets": {
"ios": "10.3",
"chrome": "60"
},
"useBuiltIns": "usage",
"corejs": 3
}]
],
"plugins": ["@babel/plugin-proposal-object-rest-spread"]
}

View file

@ -1,3 +0,0 @@
node_modules
app
sessions

View file

@ -1,18 +1,25 @@
{
"parser": "@babel/eslint-parser",
"env": {
"es2021": true,
"es6": true,
"browser": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"sourceType": "module"
"sourceType": "module",
"ecmaFeatures": {
"experimentalObjectRestSpread": true
}
},
"rules": {
"no-prototype-builtins": "off",
"no-console": "off",
"no-undef": "off",
"no-cond-assign": "off",
"no-useless-escape": "off",
"no-self-assign": "off",
"no-fallthrough": "off",
"no-empty": [
"error",
{
@ -53,5 +60,8 @@
"error",
"never"
]
},
"globals": {
"module": true
}
}

View file

@ -1,24 +0,0 @@
name: Build
on: [workflow_dispatch]
jobs:
Deploy:
runs-on: docker
container:
image: ghcr.io/catthehacker/ubuntu:act-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
lfs: 'true'
- name: Docker Login
run: |
docker login -u riksolo -p ${{secrets.CONTAINER_REGISTRY_TOKEN}} git.riksolo.com
- name: Build and push
run: |
docker build -t git.riksolo.com/riksolo/open-stage-control:latest -t git.riksolo.com/riksolo/open-stage-control:${{github.sha}} .
docker push git.riksolo.com/riksolo/open-stage-control:latest
docker push git.riksolo.com/riksolo/open-stage-control:${{github.sha}}

3
.github/FUNDING.yml vendored Normal file
View file

@ -0,0 +1,3 @@
# These are supported funding model platforms
patreon: openstagecontrol

23
.github/ISSUE_TEMPLATE/bug.md vendored Normal file
View file

@ -0,0 +1,23 @@
---
name: Bug report
about: Report a bug in Open Stage Control
title: '[Bug]'
---
<!--
/!\ Don't forget to add a title /!\
Please provide as much contextual informations as possible:
- Open Stage Control version (or commit if built from sources)
- Operating system
- Open Stage Control options
- Client type (built-in or external browser) and version
- Session file (can be uploaded after adding the .txt extension)
- Custom module
- Server logs (from the terminal or the launcher's console)
- Client logs (hit F12 in chromium/chrome to open the console)
- Screenshot
-->

5
.github/ISSUE_TEMPLATE/feature.md vendored Normal file
View file

@ -0,0 +1,5 @@
---
name: Feature request
about: Suggest an idea for Open Stage Control
title: '[Feature] '
---

5
.github/SUPPORT.md vendored Normal file
View file

@ -0,0 +1,5 @@
## How do I get help ?
- If you found a bug, open a bug report
- If you have a suggestion, open a feature request
- If you have a question or want to share your experience with other users, please use the dedicated forum at https://openstagecontrol.discourse.group/

31
.gitignore vendored
View file

@ -1,17 +1,14 @@
# npmg
node_modules/
# build
/app/
# python/midi build
src/server/python/*
!src/server/python/*.py
# docs build
src/docs/widgets-reference.js
properties-reference.md
# packaging
dist/
sessions/
node_modules
dist
app/LICENSE
app/assets/fonts/*
app/assets/*.css*
app/assets/*.png
app/client/*.js*
app/launcher/*.js*
app/server/*
app/docs/*
!app/docs/.htaccess
!app/server/.keep
app/package.json
*.pyc

57
.travis.yml Normal file
View file

@ -0,0 +1,57 @@
anHsudo: required
language: node_js
dist: jammy
node_js:
- "16"
before_install:
- sudo dpkg --add-architecture i386
- sudo apt-get update -qq
- sudo apt-get install -qq wine fakeroot xvfb python3.10 python3-pip python3-setuptools rpm
- python3 -m pip install mkdocs
- python3 -m pip install mkdocs-material
install: npm install
before_deploy:
deploy:
provider: releases
api-key: $API_KEY
file_glob: true
file: dist/packages/*
skip_cleanup: true
on:
tags: true
before_deploy:
- yes | gem update --system --force
- gem install bundler
- gem install faraday-net_http -v '3.3.0'
- gem install uri
- gem install logger
- export VERSION=$(sed -nE 's/^\s*"version":\ "(.*?)",$/\1/p' package.json)
- npm run build-docs
- npm run package -- --all
- PLATFORM=darwin;ARCH=arm64; npm run package
- npm run package-node
- cd $TRAVIS_BUILD_DIR/dist/open-stage-control-linux-x64/resources/app/server/
- wget https://github.com/jean-emmanuel/open-stage-control-midi/releases/latest/download/osc-midi-linux && chmod +x osc-midi-linux && echo "true" > osc-midi.json
- cd $TRAVIS_BUILD_DIR/dist/open-stage-control-win32-x64/resources/app/server/
- wget https://github.com/jean-emmanuel/open-stage-control-midi/releases/latest/download/osc-midi-windows.exe && chmod +x osc-midi-windows.exe && echo "true" > osc-midi.json
- cd $TRAVIS_BUILD_DIR/dist/open-stage-control-darwin-x64/open-stage-control.app/Contents/Resources/app/server
- wget https://github.com/jean-emmanuel/open-stage-control-midi/releases/latest/download/osc-midi-osx && chmod +x osc-midi-osx && echo "true" > osc-midi.json
- cd $TRAVIS_BUILD_DIR/dist/open-stage-control-darwin-arm64/open-stage-control.app/Contents/Resources/app/server
- wget https://github.com/jean-emmanuel/open-stage-control-midi/releases/latest/download/osc-midi-osx && chmod +x osc-midi-osx && echo "true" > osc-midi.json
- cd $TRAVIS_BUILD_DIR
- mkdir dist/packages
- npm run deb64
- mv dist/open-stage-control-linux-x64/*.deb dist/packages/
- npm run rpm64
- cd dist
- 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/*.rpm packages/
- mv open-stage-control-linux-x64 open-stage-control_${VERSION}_linux-x64
- 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
- ls packages
- cd ..

View file

@ -1,7 +0,0 @@
Anything AI-related is strictly prohibited from this project.
If you think this project could benefit from a smart use of AI, think harder.
Think harder about the (hundreds of) millions of data workers that make your AI "smart", not to mention the monumental ecological waste it represents.
If you still think this way, don't tell me.

View file

@ -1,135 +1,5 @@
# Changelog
## 1.31.2
- bug fixes
- editor: fix regression (1.30.0) causing errors when editing the value property
- widgets
- canvas: allow `onResize` to send and trigger widget synchronization and scripts
## 1.31.1
- bug fixes
- clone: regression causing error when some widgets have a non-string id
## 1.31.0
- widgets
- clone, fragment: add `scoped` property. This allows making the widget self-contained (independent from its original) by prefixing all widget ids automatically (and transparently resolving unprefixed ids in advanced syntaxes and scripts within the scope)
- bug fixes
- midi: unrecognized `no_auto_note_off` option
- MacOs: the app now quits when all windows are closed
- launcher: if the Tray icon is enabled, closing the launcher window won't quit the app if the server is running
- scrollbar widget: fix initial value in vertical mode
- console: fix copying using CmdOrCtrl+C when the editor is enabled
- custom module
- objects transmitted using `receive()` will be received as objects by the client app (instead of a json string)
## 1.30.4
- bug fixes
- remote control: add support for icon transform suffixes
- editor: fix moving/resing widgets inside folders when using percent units
- clone: `@{parent.propertyName}` blocks in target widget now update when clone's parent property updates
- widgets
- encoder: add `horizontal` mode
- knob: add `encoder` design
## 1.30.3
- bug fixes
- scrollbar: missing update upon target container resize
- server: regression breaking reception of osc message over tcp
- widgets
- file: remember last visited directy per widget if `directory` property is not set
- knob: add `horizontal` mode
- eq: filter responses are now only computed when needed; the widget's value is no longer exposed / sync'ed.
- plot, eq: unclip line drawing on y-axis
- scripting
- add `uploadFile` function for reading client-side files
- add `scrollIntoView` function
## 1.30.2
- bug fixes
- when using objects in properties, numbers-as-strings and booleans-as-strings values are now preserved instead of being converted to their litteral counterparts
- rgb: fix rendering issue
- patchbay: interaction and rendering issues
- `event.preventDefault` in `onTouch` now affect modal buttons
- menu: use click event instead of tap in `toggle` and `doubleTap-toggle` modes
- button: missing `move` events in `onTouch`
- error when logging `event` object in `onTouch`
- widgets
- modal/button/file: add `click` property
- editor
- preserve code editor undo history between consecutive edits of a same widget's property
- preserve fullscreen code editor focus when saving / submitting
- client
- add `noWarning` client option
## 1.30.1
- bug fixes
- regression breaking user asset loading from a root directory named "assets"
- regression breaking custom module's `nativeRequire()` for locally installed modules
## 1.30.0
- bug fixes
- server: fix resolving absolute file urls containing the remote-root path
- prevent editor zoom level from affecting drag events when the editor is disabled
- prevent changing editor zoom level when it's disabled
- fader: fix touchZone == knob for compact design
- separator labels missing in inspector
- make the client app more robust to restrictive browser settings (cookie must still be enabled for the app to fully work)
- widgets
- the html property is no longer restricted / sanitized
- input/textarea/select no longer have their appearance property reset in custom html
- canvas: added `contextType` property
- file: honor server's `remote-root` option (remove root path from displayed path and returned value)
- menu: changed default `layout` to `vertical`
- root/panel/modal/tab: support setting `scroll` to `hidden` (hides scrollbars and allows scrolling)
- add new `scrollbar` widget that connects to a scrolling container widget and acts as it scrollbar
- input: add `noCanvas` option to avoid blurry text under some circumstances
- xy: add `clipX` and `clipY` proprties (allows multixy to set per-pads anges limits)
- button: add `onTouch` script
- switch: make `values` property dynamic
- editor
- selecting a widget automatically shows it in the widget tree if it's not minimized
- submitting an unchanged value for the `value` property will now affect the value state of the widget even if the property content itself did not change
- scripting
- user scripts are longer protected against infinite loop and the main window object may be reached (it's not supported to break out of scripting context, but resources are no longer wasted to prevent it)
- `toolbar()` can now target menu actions by id instead of index
- `getToolbar()` function added (returns the state of a menu entry toggle)
- calling `setFocus()` without argument now unfocuses current active element
- midi
- add `no_auto_note_off` option
- add `Restart backend` action to the launcher's menu
- add `restartMidiBackend()` function to custom module context
- breaking change
- dropped support for iOS 10.3
- minimum chromium version requirement raised to 70
- macOS 11 (Big Sur) or above is now required (the node package will work on older system)
- scrollbars are no longer emulated on iOS
- scrollbar styling is now done using only the standard css scrollbar-* properties) to be more in line with system scrollbars in general
- panels no longer use their value to set/get their scrolling state, nor do they sync scrolling automatically. Instead there's now a dedicated scrollbar widget that can be used for this.
- misc
- now using electron v36.9.5
## 1.29.9
@ -1059,7 +929,7 @@
- advanced syntaxes
- new syntax for creating and using custom variables in properties: `VAR{name, default}`
- `JS{}` blocks don't require 2 brackets anymore (`JS\{\{}}` still works)
- `JS{}` blocks don't require 2 brackets anymore (`JS{{}}` still works)
- scripting
- add `getVar()` and `setVar()` for reading and modifying custom variables. This allows modifying properties directly from scripts (if they contain `VAR{}` blocks).
@ -1130,7 +1000,7 @@
- add option for receiving note off with velocity
- misc
- v0->v1 session conversion: remove `JS\{\{}}` in script property
- v0->v1 session conversion: remove `JS{{}}` in script property
## 1.9.0
@ -1732,14 +1602,14 @@ As of this version, packages except the `node` package are bundled with a midi b
- scripting (general)
- removed MathJS language
- reuse #{} syntax as as shorthand for JS\{\{}} (one liner, implicit return)
- reuse #{} syntax as as shorthand for JS{{}} (one liner, implicit return)
- added `locals` variable, a variable store scoped to the widget
- renamed `global` to `globals`
- expose environment variables in `globals`: `url`, `env` (query parameters), `platform`, `screen` (width/height)
- script widget
- always hidden except in project tree
- `script` property must not be wrapped in a JS\{\{}} block anymore
- `script` property must not be wrapped in a JS{{}} block anymore
- added `stateGet` and `stateSet` functions
- added `storage` object, proxy to the document's localStorage object (allows storing data that persist after refresh/close (cleared with the browser's cache)
- added `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` function proxies with an extra `id` argument (they clear automatically when called multiple times and upon widget removal. `id` is scoped to the widget)

View file

@ -1,29 +0,0 @@
FROM node:24-alpine
RUN apk --no-cache add git
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
RUN mkdir /sessions
RUN touch /sessions/session.json
EXPOSE 8080
ENV ELECTRON_RUN_AS_NODE=1
ENV SEND="127.0.0.1:8080"
ENV LOAD="/sessions/main.json"
ENV PORT=8080
ENV OSC_PORT=8080
ENV READ_ONLY=false
RUN chmod +x entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

View file

@ -11,11 +11,5 @@ Open Stage Control
----
Docker additions by Rik Berkelder.
mount `/sessions` directory. default session file is created and loaded there.
---
Copyleft © Jean-Emmanuel Doucet 2014-2025.
This program is a free software released under the [GNU/GPL3](https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/LICENSE) license.
This program is a free software released under the [GNU/GPL3](ttps://github.com/jean-emmanuel/open-stage-control/blob/master/LICENSE) license.

2
app/assets/themes/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

2
app/client/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

1
app/docs/.htaccess Normal file
View file

@ -0,0 +1 @@
ErrorDocument 404 /404.html

1
app/index.js Normal file
View file

@ -0,0 +1 @@
require('./server/open-stage-control-server')

2
app/launcher/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

0
app/server/.keep Normal file
View file

View file

@ -1,49 +0,0 @@
{
"createdWith": "Open Stage Control",
"version": "1.31.2",
"type": "session",
"content": {
"type": "root",
"lock": false,
"id": "root",
"visible": true,
"interaction": true,
"comments": "",
"width": "auto",
"height": "auto",
"colorText": "auto",
"colorWidget": "auto",
"alphaFillOn": "auto",
"borderRadius": "auto",
"padding": "auto",
"html": "",
"css": "",
"colorBg": "auto",
"layout": "default",
"justify": "start",
"gridTemplate": "",
"contain": true,
"scroll": true,
"innerPadding": true,
"tabsPosition": "top",
"hideMenu": false,
"variables": "@{parent.variables}",
"traversing": false,
"value": "",
"default": "",
"linkId": "",
"address": "auto",
"preArgs": "",
"typeTags": "",
"decimals": 2,
"target": "",
"ignoreDefaults": false,
"bypass": false,
"onCreate": "",
"onValue": "",
"onTouch": "",
"onPreload": "",
"widgets": [],
"tabs": []
}
}

View file

@ -1,8 +0,0 @@
services:
app:
build: .
volumes:
- ./sessions:/sessions
ports:
- 8080:8080

View file

@ -1,10 +0,0 @@
#!/bin/sh
test -f "$LOAD" || cp "basesession.json" "$LOAD"
exec node app/index.js \
--port $PORT \
--osc-port $OSC_PORT \
--send $SEND \
--load $LOAD \
--read-only=$READ_ONLY

9570
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
"name": "open-stage-control",
"productName": "Open Stage Control",
"description": "Libre and modular OSC / MIDI controller",
"version": "1.31.2",
"version": "1.29.9",
"author": {
"name": "Jean-Emmanuel Doucet",
"email": "jean-emmanuel@ammd.net"
@ -21,34 +21,36 @@
"license": "GPL-3.0",
"dependencies": {
"@babel/core": "7.18.0",
"@babel/eslint-parser": "7.17.0",
"@babel/plugin-proposal-object-rest-spread": "7.18.0",
"@babel/polyfill": "7.12.1",
"@babel/preset-env": "7.18.0",
"@electron/packager": "18.4.4",
"@electron/remote": "2.1.3",
"@rollup/plugin-babel": "^6.0.4",
"@rollup/plugin-commonjs": "^28.0.6",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.1",
"@rollup/plugin-terser": "^0.4.4",
"@electron/remote": "2.0.8",
"ace-builds": "1.39.0",
"ansi-html": "0.0.9",
"babelify": "10.0.0",
"balanced-match": "2.0.0",
"bonjour": "git+https://framagit.org/jean-emmanuel/bonjour.git",
"browserify": "17.0.0",
"chokidar": "3.5.3",
"chroma-js": "2.4.2",
"core-js": "3.22.5",
"cpr": "3.0.1",
"deep-extend": "0.6.0",
"electron-localshortcut": "3.2.1",
"electron-packager": "15.2.0",
"electron-packager-plugin-non-proprietary-codecs-ffmpeg": "1.0.2",
"env-paths": "2.2.1",
"eslint": "8.16.0",
"exorcist": "2.0.0",
"fastdom": "1.0.10",
"file-saver": "2.0.5",
"gyronorm": "2.0.6",
"http-auth": "4.1.9",
"json5": "2.2.1",
"jsondiffpatch": "0.4.1",
"keyboardjs": "2.6.4",
"licensify": "3.1.3",
"minimatch": "5.1.0",
"nanohtml": "1.10.0",
"nanoid": "3.3.4",
@ -62,10 +64,7 @@
"python-shell": "3.0.1",
"qrcode": "1.5.1",
"replacestream": "4.0.3",
"rollup": "4.50.1",
"rollup-plugin-copy": "3.5.0",
"rollup-plugin-license": "^3.6.0",
"rollup-plugin-node-externals": "^8.1.1",
"sanitize-html": "1.27.5",
"sass": "1.89.2",
"scope-css": "1.2.1",
"screenfull": "5.2.0",
@ -74,37 +73,42 @@
"sortablejs": "1.15.0",
"source-map-support": "0.5.21",
"stacktrace-js": "2.0.2",
"ua-parser-js": "2.0.7",
"through": "2.3.8",
"uglifyify": "5.0.2",
"webworkify": "1.5.0",
"ws": "8.6.0",
"yargs": "17.5.1"
},
"optionalDependencies": {
"electron": "36.9.5",
"electron": "15.1.0",
"electron-installer-debian": "3.1.0",
"electron-installer-redhat": "git+https://framagit.org/jean-emmanuel/electron-installer-redhat.git"
},
"scripts": {
"postinstall": "echo '\\033[36m=> Dependencies installed successfully. Run \"npm run build\" to build the assets.\\033[0m\n'",
"start": "electron app/",
"build": "npm run build-css && npm run build-js && echo '\\033[36m=> JS and CSS assets built successfully. Run \"npm run package\" to build an executable or \"npm start\" to run the app.\\033[0m\n'",
"build": "npm run build-css && npm run build-js && node scripts/copy-assets.js && echo '\\033[36m=> JS and CSS assets built successfully. Run \"npm run package\" to build an executable or \"npm start\" to run the app.\\033[0m\n'",
"package": "node scripts/package.js",
"package-node": "node scripts/package-node.js",
"deb64": "electron-installer-debian --src dist/open-stage-control-linux-x64/ --arch amd64 --dest dist/ --icon resources/images/logo.png",
"rpm64": "electron-installer-redhat --src dist/open-stage-control-linux-x64/ --arch x86_64 --dest dist/ --icon resources/images/logo.png",
"deb64": "electron-installer-debian --src dist/open-stage-control-linux-x64/ --arch amd64 --dest dist/open-stage-control-linux-x64/ --icon resources/images/logo.png",
"rpm64": "electron-installer-redhat --src dist/open-stage-control-linux-x64/ --arch x86_64 --dest dist/open-stage-control-linux-x64/ --icon resources/images/logo.png",
"build-css": "node scripts/build-css.js",
"watch-css": "nodemon --watch src/scss -e scss -x \"npm run build-css -- --reload\"",
"build-js": "npm run build-launcher-js && npm run build-client-js && npm run build-server-js",
"build-client-js": "rollup -c scripts/client.rollup.config.js",
"build-client-js": "node scripts/build-client.js",
"build-launcher-js": "node scripts/build-launcher.js",
"build-server-js": "node scripts/build-server.js",
"watch-client": "npm run build-client-js -- --watch",
"build-server-js": "rollup -c scripts/server.rollup.config.js",
"watch-server": "npm run build-server-js -- --watch",
"build-launcher-js": "rollup -c scripts/launcher.rollup.config.js",
"watch-launcher": "npm run build-launcher-js -- --watch",
"build-docs": "rollup -c scripts/docs.rollup.config.js && node src/docs/widgets-reference.js > resources/docs/docs/widgets/properties-reference.md && cd resources && python3 -m mkdocs build",
"lint": "eslint src --ext mjs",
"test": "npm run lint && npm run build"
"watch-browser": "npm run build-client-js -- --watch",
"watch-css": "nodemon --watch src/scss -e scss -x \"npm run build-css -- --reload\"",
"watch-server": "nodemon --watch src/server/ -e js -x \"npm run build-server-js\"",
"watch-launcher": "nodemon --watch src/launcher/ -e js -x \"npm run build-launcher-js\"",
"build-docs": "node scripts/build-widgets-reference.js > resources/docs/docs/widgets/properties-reference.md && cd resources && python3 -m mkdocs build",
"test": "eslint src && npm run build && node tests/test.js"
},
"engines": {
"node": ">=16"
"node": ">=16 <=20"
},
"devDependencies": {
"watchify": "4.0.0"
}
}

View file

@ -19,7 +19,6 @@ Client options can be set either with the server's `--client-options` option, or
| virtualKeyboard | 1 / 0 | 0 | (desktop only) set to 1 to enable the virtual keyboard by default |
| notifications | 1 / 0 | 1 | set to 0 to hide notifications by default |
| title | string | '' | replace window title |
| noWarning | 1 / 0 | 0 | set to 0 to disable unsaved session warnings |
Example:

View file

@ -1,17 +1,19 @@
## License
Copyleft © Jean-Emmanuel Doucet 2014-2025.
This program is a free software released under the [GNU/GPL3](https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/LICENSE) license.
This program is a free software released under the [GNU/GPL3](https://github.com/jean-emmanuel/open-stage-control/blob/master/LICENSE) license.
## Dependencies
Open Stage Control relies on several other free softwares listed in [package.json](https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/package.json).
Open Stage Control relies on several other free softwares:
The default theme was based on [Nord](https://www.nordtheme.com/), some UI components were inspired by the text editor formerly known as Atom (now [Pulsar](https://pulsar-edit.dev/)).
https://github.com/jean-emmanuel/open-stage-control/network/dependencies
The default theme is based on [Nord](https://www.nordtheme.com/), some UI components are inspired by the [Atom](https://atom.io/) text editor.
## Contributors
[Jean-Emmanuel](https://framagit.org/jean-emmanuel), [MartinHN](https://github.com/MartinHN), [Eric Theise](https://github.com/erictheise), [danielappelt](https://github.com/erictheise), [ritschwumm](https://github.com/ritschwumm), [matthijskooijman](https://github.com/matthijskooijman), [WillyKaze](https://github.com/WillyKaze), [stefanboca](https://github.com/stefanboca), [pixelnerve](https://github.com/pixelnerve), [AdamAdamsMusic](https://github.com/AdamAdamsMusic), [wicast](https://github.com/wicast), [kdallafior](https://github.com/kdallafior), [brunetton](https://github.com/brunetton), [cyberic99](https://github.com/cyberic99), [kdejaeger](https://github.com/kdejaeger), [trebmuh](https://github.com/trebmuh), [MagnusReichel](https://github.com/MagnusReichel), [jpcima](https://github.com/jpcima), [t1st3](https://github.com/t1st3")
https://github.com/jean-emmanuel/open-stage-control/graphs/contributors
## Infrastructure supports

View file

@ -76,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://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}`)
[`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}`)
----
@ -153,7 +153,7 @@ This function can be used to load native node modules or locally installed modul
#### `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:
Raw access to the server's [TCP backend](https://github.com/jean-emmanuel/open-stage-control/blob/master/src/server/osc/tcp.js). Can be used to monitor the state of TCP connections:
```js
for (var ip in tcpServer.clients) {
@ -167,10 +167,6 @@ for (var ip in tcpServer.clients) {
```
#### `restartMidiBackend()`
This function can be used to restart the midi backend (if already running) without restarting the server
#### Other javascript globals
- `console`

View file

@ -18,9 +18,9 @@ The **server** can run on all [platforms supported by Electron](https://www.elec
The **client** is compatible with the following browsers:
- Firefox: version `75` and higher
- Chromium / Chrome: version `75` and higher
- Chromium / Chrome: version `60` and higher
iOS devices must be of version `11` or higher.
iOS devices must be of version `10.3` or higher.
## Installation

View file

@ -2,7 +2,7 @@ Running the app from the sources slightly differs from using prebuilt binaries:
## Requirements
- [Node.js](https://nodejs.org/en/#download)
- [Node.js](https://nodejs.org/en/#download) (v16)
- [git](https://git-scm.com/downloads)
@ -12,7 +12,7 @@ Running the app from the sources slightly differs from using prebuilt binaries:
**Download**
```bash
git clone https://framagit.org/jean-emmanuel/open-stage-control.git
git clone https://github.com/jean-emmanuel/open-stage-control
cd open-stage-control/
# uncomment next line if you want the latest release
# instead of the current development version

View file

@ -94,11 +94,7 @@ Send program changes with a `-1` offset to match some software/hardware implemen
**`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.
Enable receiving noteOff messages with a velocity and on a different address than noteOn messages.
**`device_name:virtual`** (*Linux / Mac only*): creates a virtual midi device with one input port and one output port

View file

@ -7,9 +7,7 @@
- New window: open a new client window (hidden when stopped)
- Load: load server configuration from file
- Save / Save as: save server configuration to file
- MIDI
- List devices: list available MIDI devices in the console
- Restart backend: restart midi backend without restarting the server
- List MIDI devices: list available MIDI devices in the console
- Console:
- Clear: clear console
- Autoscroll: enable/disable console autoscroll

View file

@ -2,7 +2,7 @@
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.
It has two special properties, `touch` and `draw`, that work like the `script` 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.
@ -30,7 +30,7 @@ If this property is enabled, the widget will be redrawn at a fixed rate even if
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:
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
- `width`: canvas width in pixels
@ -59,7 +59,7 @@ This script has access to the same variables and functions as the `onValue` prop
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:
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
- `width`: canvas width in pixels
@ -67,13 +67,11 @@ This script has access to the same variables and functions as the `onValue` prop
- `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:
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
- `width`: canvas width in pixels

File diff suppressed because it is too large Load diff

View file

@ -123,8 +123,6 @@ The following variables are available in this context:
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.
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
The following variables and functions are accessible in this context.
@ -163,7 +161,7 @@ Returns the value of the first matching widget. If the returned value is an obje
- `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)
- `external: true`: simulates a value coming from an osc/midi message (implies `sync: false` automatically)
Sets the value of the first matching widget. If `ìd` contains wildcards, affects all matching widgets **except** the emitting widget.
@ -305,7 +303,7 @@ Reference:
- `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.
Gives focus to a widget (ie input widget).
*Built-in client only*: tells the operating system to give the focus to the client window
@ -330,6 +328,10 @@ Gives focus to a widget (ie input widget). If `id` is omitted or falsy, currentl
Returns the scroll position of a container as a `[x, y]` array.
**Deprecated**
Scrollable panels expose their scroll position normalized between 0 and 1 with their value.
----
#### `setScroll(id, x, y)`
@ -339,50 +341,26 @@ Returns the scroll position of a container as a `[x, y]` array.
Sets the scroll state of a container.
----
#### `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
Scroll containers to make widget(s) visible.
**Deprecated**
Scrollable panels expose their scroll position normalized between 0 and 1 with their value.
----
#### `toolbar(id)`
- `id` menu entry id (string)
#### `toolbar(i1, i2, ...)`
- `iX`: menu entry index
Triggers toobar action if currently available (ie accessible from the menu). `id` can be one of the following:
Triggers toolbar action at specified index.
- `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"
!!! example "Examples"
- `toolbar(0, 0)` -> Open a new session
- `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
@ -419,19 +397,10 @@ Returns the instance of [Navigator](https://developer.mozilla.org/en-US/docs/Web
#### `browseFile(options, callback)`
Opens the server file browser and pass selected file to a callback function (does not create nor read files by itself).
Opens the file 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)

View file

@ -3,20 +3,66 @@
!!! tip ""
[*Click here*](/docs/getting-started/introduction/#installation) to read the installation guide.
<a href="https://framagit.org/jean-emmanuel/open-stage-control/-/releases/v{{config.latest_release}}">
Open Stage Control v{{config.latest_release}}
</a>
<a href="https://github.com/jean-emmanuel/open-stage-control/releases/latest"> Open Stage Control <span id="osc-version"span></a>
<ul>
<li><a href="/packages/open-stage-control-{{config.latest_release}}-1.x86_64.rpm"><i class="fa fa-download"></i>GNU/Linux RPM (64-bit)</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_amd64.deb"><i class="fa fa-download"></i>GNU/Linux Debian (64-bit)</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_linux-x64.zip"><i class="fa fa-download"></i>GNU/Linux (64-bit)</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_node.zip"><i class="fa fa-download"></i>Node.js</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_osx-x64.zip"><i class="fa fa-download"></i>MacOS x64</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_osx-arm64.zip"><i class="fa fa-download"></i>MacOS arm64</a></li>
<li><a href="/packages/open-stage-control_{{config.latest_release}}_win32-x64.zip"><i class="fa fa-download"></i>Windows (64-bit)</a></li>
<div id="osc-assets">Loading assets...</div>
</ul>
<script>
var oReq = new XMLHttpRequest();
oReq.addEventListener('load', reqListener);
oReq.open('GET', 'https://api.github.com/repos/jean-emmanuel/open-stage-control/releases/latest')
oReq.send()
function text(id, str) {
var el = typeof id === 'string' ? document.getElementById(id) : id
el.textContent = str
}
var names = {
'x86_64.rpm': 'GNU/Linux RPM (64-bit)',
'amd64.deb': 'GNU/Linux Debian (64-bit)',
'linux-x64.zip': 'GNU/Linux (64-bit)',
'node.zip': 'Node.js',
'osx.zip': 'MacOS',
'win32-x64.zip': 'Windows (64-bit)'
}
function reqListener () {
var data = JSON.parse(this.responseText)
var date = new Date(data.published_at)
text('osc-version', data.tag_name + ' (' + date.toLocaleDateString() + ')')
var list = document.createElement('ul')
for (var i in data.assets) {
var item = document.createElement('li'),
link = document.createElement('a'),
name = data.assets[i].name
for (var k in names) {
if (name.includes(k)) {
name = names[k]
break
}
}
link.innerHTML = '<i class="fa fa-download"></i> ' + name + ' <span class="download-size">(' + (data.assets[i].size / 1024 / 1024).toFixed(0) + 'M)</span>'
link.href = data.assets[i].browser_download_url
item.appendChild(link)
list.appendChild(item)
}
var assets = document.getElementById('osc-assets')
assets.innerHTML = ''
assets.appendChild(list)
}
</script>
<style>
@ -52,7 +98,7 @@ li i {
<div>
<a
href="/docs/changelog/"
href="https://openstagecontrol.ammd.net/docs/changelog/"
class="md-button md-button-small"
>
Read the Changelog

View file

@ -11,7 +11,7 @@
font-style: normal;
font-weight: 900;
font-display: block;
src: url("./fa-solid-900.woff2") format("woff2"); }
src: url("./fa-solid-900.woff2?__OSC_ASSET__=1") format("woff2"); }
.fa,
.fas,

View file

@ -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?__OSC_ASSET__=1') 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?__OSC_ASSET__=1') 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?__OSC_ASSET__=1') 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?__OSC_ASSET__=1') 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?__OSC_ASSET__=1') format('woff');
}

View file

@ -1,11 +1,10 @@
site_name: Open Stage Control
repo_name: open-stage-control
repo_url: https://framagit.org/jean-emmanuel/open-stage-control
repo_url: https://github.com/jean-emmanuel/open-stage-control
edit_uri: tree/master/resources/docs/
copyright: "Copyleft © Jean-Emmanuel Doucet @ <a href='http://ammd.net'>AMMD</a> (<a href='https://framagit.org/jean-emmanuel/open-stage-control/-/blob/master/LICENSE'>GNU/GPLv3</a>)"
copyright: "Copyleft © Jean-Emmanuel Doucet @ <a href='http://ammd.net'>AMMD</a> (<a href='https://github.com/jean-emmanuel/open-stage-control/blob/master/LICENSE'>GNU/GPLv3</a>)"
site_description: "Libre and modular OSC / MIDI controller"
site_dir: '../app/docs/'
latest_release: 1.31.2
theme:
name: 'material'
@ -64,6 +63,9 @@ nav:
- Remote control: docs/remote-control.md
- Credits: docs/credits.md
- Changelog: docs/changelog.md
- Bug Tracker:
- 'Bug Tracker': 'https://github.com/jean-emmanuel/open-stage-control/issues'
- Community:
- 'Community forums': 'https://openstagecontrol.discourse.group'
@ -94,7 +96,3 @@ markdown_extensions:
- pymdownx.tabbed:
alternate_style: true
- pymdownx.details
plugins:
- macros

98
scripts/build-client.js Normal file
View file

@ -0,0 +1,98 @@
var build = require('./build'),
path = require('path'),
babelify = require('babelify'),
nanohtml = require('nanohtml'),
watch = process.argv.includes('--watch'),
through = require('through'),
minimatch = require('minimatch')
var ignores = ['**/*.min.js', '**/jquery.ui.js', 'gyronorm.complete.min.js'],
transformWrapper = function(transform){
return function(file, opts){
if (ignores.some(pattern => minimatch(file, pattern))) {
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,
ignore: [
'postcss' // only needed by sanitize-html if <style> is allowed; somehow fails at object spread syntax transpilation
]
})
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',
'<div class="error-stack">' +
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
) +
'</div>'
)
})
}
hotBundle()
} else {
bundle()
}

View file

@ -5,8 +5,6 @@ var sass = require('sass'),
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') {

16
scripts/build-launcher.js Normal file
View file

@ -0,0 +1,16 @@
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',
]
})()

27
scripts/build-server.js Normal file
View file

@ -0,0 +1,27 @@
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
]
})()

View file

@ -1,9 +1,9 @@
import './client-shim.mjs'
import baseClass from '../client/widgets/common/widget.mjs'
import * as widgets from '../client/widgets/index.mjs'
require('./client-shim')
// Here we go
var base = baseClass.defaults(),
var widgets = require('../src/client/widgets'),
baseClass = require('../src/client/widgets/common/widget'),
base = baseClass.defaults(),
doc = ['<!-- This file is generated automatically from the widget class declarations. See scripts/build-widget-reference.js -->']
@ -17,24 +17,24 @@ doc.push(`
`
)
for (let categoryName in base) {
for (var categoryName in base) {
doc.push(`\n
=== "${categoryName}"
=== "${categoryName}"
| property | type |default | description |
| --- | --- | --- | --- |`
| property | type |default | description |
| --- | --- | --- | --- |`
)
let notEmpty = false
var notEmpty = false
for (let propName in base[categoryName]) {
for (var propName in base[categoryName]) {
let prop = base[categoryName][propName],
var prop = base[categoryName][propName],
permalink = propName
if (propName === '_props' || propName[0] === '_') continue
if (propName === '_props' || propName[0] === '_') continue
let help = Array.isArray(prop.help) ? prop.help.join('<br/><br/>').replace(/<br\/>-/g, '-') : prop.help || '',
var help = Array.isArray(prop.help) ? prop.help.join('<br/><br/>').replace(/<br\/>-/g, '-') : prop.help || '',
dynamic = baseClass.dynamicProps.includes(propName) ? '<sup><i class="fas fa-bolt" title="dynamic"></i></sup>' : ''
if (prop.choices) {
@ -75,24 +75,24 @@ for (var k in widgets.categories) {
)
for (let categoryName in defaults) {
for (var categoryName in defaults) {
doc.push(`\n
=== "${categoryName == 'class_specific' ? type : categoryName}"
| property | type |default | description |
| --- | --- | --- | --- |`
)
let notEmpty = false
var notEmpty = false
for (let propName in defaults[categoryName]) {
for (var propName in defaults[categoryName]) {
let prop = defaults[categoryName][propName],
var 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
let help = Array.isArray(prop.help) ? prop.help.join('<br/><br/>').replace(/<br\/>-/g, '-') : prop.help || '',
var help = Array.isArray(prop.help) ? prop.help.join('<br/><br/>').replace(/<br\/>-/g, '-') : prop.help || '',
dynamic = widgets.widgets[type].dynamicProps.includes(propName) ? '<sup><i class="fas fa-bolt" title="dynamic"></i></sup>' : ''
if (prop.choices) {

49
scripts/build.js Normal file
View file

@ -0,0 +1,49 @@
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
}

View file

@ -1,12 +1,10 @@
// Dirty browser window shim
import * as DOM from '../client/dom.mjs'
// eslint-disable-next-line no-global-assign
document = {
createElement: x=>({
ownerDocument: document,
addEventListener: ()=>{},
style: {setProperty: ()=>{}},
style: {},
contentWindow: {},
nodeName: '',
childNodes: [],
setAttribute: ()=>{},
@ -14,16 +12,14 @@ document = {
lastChild: {},
toString: ()=>' ',
removeChild: ()=>{},
getPropertyValue: ()=>{},
contentWindow: {
document: {
open: ()=>{},
close: ()=>{},
write: ()=>{},
}
},
}
}),
getElementById: ()=>document.createElement(),
createTextNode: x=>({
nodeValue: '',
nodeName: '',
@ -49,17 +45,23 @@ document = {
appendChild: ()=>{},
addEventListener: ()=>{}
},
location: {search: ''},
location: {},
documentElement: {
appendChild: ()=>{},
removeChild: ()=>{}
}
}
document.documentElement = document.createElement()
// eslint-disable-next-line no-global-assign
window = {
screen: {width: 800, height: 600},
addEventListener: ()=>{},
location: {search: ''},
location: {},
Image: Function,
document: document,
navigator: {
platform:'',
userAgent: ''
},
NodeList: Array,
WebSocket: Object,
localStorage: {
@ -67,26 +69,20 @@ window = {
},
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: ''
}
MutationObserver: class MutationObserver{}
}
Object.assign(global, window)
console.debug = ()=>{}
// Required globals
DOM = require('../src/client/dom')
DOM.get = x=>[{addEventListener:()=>{}, style:{}}]
DOM.init()
ELECTRON_NOGPU = false
CANVAS_FRAMERATE = 1
LANG = 'en'
ENV = {id: ''}
IP = ''

View file

@ -1,40 +0,0 @@
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 = `<div class="error-stack">
${error.message.replace(path.resolve(__dirname + '/..'),'')} at line ${error.loc.line}\n${error.frame}
</div>`
send('errorPopup', msg.trim())
reloadClient = false
} else {
reloadClient = true
}
},
writeBundle() {
if (reloadClient) {
send('reload')
}
}
}
}

View file

@ -1,98 +0,0 @@
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()
]
};

65
scripts/copy-assets.js Normal file
View file

@ -0,0 +1,65 @@
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'],
['../resources/images/logo_tray.png', '../app/assets/logo_tray.png'],
['../resources/images/logo_tray@x2.png', '../app/assets/logo_tray@x2.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'],
['../node_modules/ace-builds/src-min/worker-css.js', '../app/client/workers/worker-css.js'],
['../node_modules/ace-builds/src-min/worker-html.js', '../app/client/workers/worker-html.js'],
['../node_modules/ace-builds/src-min/worker-javascript.js', '../app/client/workers/worker-javascript.js'],
]
if (process.platform === 'darwin') {
files.push(['../resources/images/logo_16x16.png', '../app/assets/logo_16x16.png'])
}
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(/\$\{([^\}]+)\}/g, (m, p1)=>{return appJson[p1]})
fs.writeFileSync(path.resolve(__dirname + '/../app/client/index.html'), clientHtml)

View file

@ -1,45 +0,0 @@
#!/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

View file

@ -1,25 +0,0 @@
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()
]
};

View file

@ -1,48 +0,0 @@
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'},
]
})
]
};

View file

@ -1,4 +1,8 @@
var cpr = require('cpr'),
var browserify = require('browserify'),
exorcist = require('exorcist'),
licensify = require('licensify'),
fs = require('fs'),
cpr = require('cpr'),
path = require('path'),
files = ['../app', '../dist/open-stage-control-node']

View file

@ -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.ELECTRON_VERSION || require('../package.json').optionalDependencies.electron,
electronVersion: process.env.ARCH === 'armv7l' ? '1.7.11' : require('../package.json').optionalDependencies.electron,
overwrite: true,
out: path.resolve(__dirname + '/../dist'),
icon: path.resolve(__dirname + '/../resources/images/logo'),

View file

@ -1,65 +0,0 @@
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/'},
]
})
]
};

65
src/client/backup.js Normal file
View file

@ -0,0 +1,65 @@
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,
saveMode: session.saveMode,
sessionPath: session.sessionPath,
fragments: session.fragments,
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)
for (let k in data.fragments) {
session.setFragment({path: k, fileContent: JSON.parse(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)
})
}
}
}

View file

@ -1,62 +0,0 @@
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)
})
}
}

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

@ -0,0 +1,107 @@
var readyCallbacks = [],
initState = false
module.exports = {
init: function() {
for (var i in readyCallbacks) {
readyCallbacks[i]()
}
initState = true
},
ready: function(callback) {
if (initState) {
callback()
} else {
readyCallbacks.push(callback)
}
},
dispatchEvent: function(element, name, data) {
var event = new CustomEvent(name, {
detail: data,
bubbles: true,
cancelable: true
})
element.dispatchEvent(event)
},
addEventListener: function(element, events, listener, capture) {
var eventsAsObject = typeof events == 'string' ? events.split(' ') : events
for (var i in eventsAsObject) {
element.addEventListener(eventsAsObject[i], listener, capture)
}
},
get: function(a, b) {
var context = b ? a : document,
selector = b || a,
nodes
if (selector.indexOf('>') === 0) selector = ':scope ' + selector
if (selector.indexOf(' ') === -1 && selector.indexOf(',') === -1 && 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]
},
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
}
}
}

View file

@ -1,82 +0,0 @@
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
}
}

View file

@ -1,19 +1,14 @@
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 {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(),
sessionManager
var contextMenu = new ContextMenu()
var multiSelectKey = (navigator.platform || '').match('Mac') ? 'metaKey' : 'ctrlKey'
@ -35,7 +30,7 @@ var handleClick = function(event) {
if (!targetWidget) return
while (targetWidget.meta.not_editable && targetWidget.parent) {
while (targetWidget._not_editable && targetWidget.parent) {
targetWidget = targetWidget.parent
}
@ -337,6 +332,7 @@ var handleClick = function(event) {
actions.push({
label: icon('file-download') + ' ' + locales('editor_fragment_export'),
action: ()=>{
sessionManager = sessionManager || require('../managers/session')
sessionManager.saveFragment(editor.selectedWidgets[0].props)
}
})

View file

@ -1,28 +1,29 @@
import widgetManager from '../managers/widgets.mjs'
import stateManager from '../managers/state.mjs'
import parser from '../parser.mjs'
import * as resize from '../events/resize.mjs'
var widgetManager = require('../managers/widgets'),
resize = require('../events/resize'),
stateManager = require('../managers/state'),
parser = require('../parser'),
Panel, Matrix,
editor,
scrollState = {}
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 = {}
setTimeout(()=>{
editor = require('./')
Panel = require('../widgets/containers/panel')
Matrix = require('../widgets/containers/matrix')
})
function updateWidget(widget, options={}) {
if (options.editedProps) {
if (options.changedProps) {
// alternate routine for small edits
var propNames = options.editedProps
var propNames = options.changedProps
if (
// if non dynamic props have changed, skip this and use rebuild routine
!propNames.some(n => !widget.isDynamicProp(n))
) {
var edited = widget.updateProps(options.editedProps, null, {fromEditor: true}) || widget
var edited = widget.updateProps(options.changedProps, null, {fromEditor: true}) || widget
editor.widgetTree.updateTree(editor.selectedWidgets)
@ -109,8 +110,7 @@ function updateWidget(widget, options={}) {
variables: widget.variables,
hash: widget.hash,
children: children,
index: index,
meta: widget.meta
index: index
})
newWidget.container.parentNode.replaceChild(newWidget.container, widget.container)
@ -235,7 +235,7 @@ var incrementWidget = function(data, root){
}
export {
updateWidget,
incrementWidget
module.exports = {
updateWidget:updateWidget,
incrementWidget:incrementWidget
}

32
src/client/editor/diff.js Normal file
View file

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

View file

@ -1,29 +0,0 @@
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]])
}

View file

@ -1,36 +1,31 @@
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'
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
var sessionManager
;(async()=>{
sessionManager = (await import('../managers/session/index.mjs')).default
await import('./context-menu.mjs')
})()
setTimeout(()=>{
sessionManager = require('../managers/session/')
})
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)=>{
@ -55,12 +50,12 @@ class Editor {
try {
newWidgets.push(updateWidget(w, {editedProps: [propName], preventSelect: this.selectedWidgets.length > 1}))
newWidgets.push(updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1}))
} catch (e) {
w.props[propName] = previousValue
updateWidget(w, {editedProps: [propName], preventSelect: this.selectedWidgets.length > 1})
updateWidget(w, {changedProps: [propName], preventSelect: this.selectedWidgets.length > 1})
if (uiConsole.minimized) notifications.add({
class: 'error',
@ -282,7 +277,7 @@ class Editor {
if (
this.inspector.helpModalOpened ||
e && e.target && e.target.tagName.match(/INPUT|TEXTAREA|SELECT|OSC-CONSOLE/)
e && e.target && e.target.tagName.match(/INPUT|TEXTAREA|SELECT/)
) return
if (e) e.preventDefault()
@ -401,7 +396,7 @@ class Editor {
} else if (e.key === 'ArrowRight') {
if (curWidget.children[0] && !curWidget.children[0].meta.not_editable) {
if (curWidget.children[0] && !curWidget.children[0]._not_editable) {
toSelect = curWidget.children[0]
}
@ -523,7 +518,7 @@ class Editor {
this.grid = !this.grid
setGRIDWIDTH(this.grid ? GRIDWIDTH_CSS : 1)
GRIDWIDTH = this.grid ? GRIDWIDTH_CSS : 1
document.body.style.setProperty('--grid-width', GRIDWIDTH)
document.body.classList.toggle('no-grid', GRIDWIDTH == 1)
@ -672,9 +667,6 @@ 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])
}
}
@ -905,17 +897,6 @@ class Editor {
}
/* 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
@ -927,7 +908,7 @@ class Editor {
var newWidgets = [],
area = this.widgetDragResize,
editedProps = []
changedProps = []
for (var i = 0; i < this.selectedWidgets.length; i++) {
@ -945,20 +926,20 @@ class Editor {
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 / this.getWidgetParentContainer(w).offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
w.props.width = (100 * PXSCALE * newWidth / w.container.parentNode.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.width = newWidth
}
editedProps.push('width')
changedProps.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+$/, '') + '%'
w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
} else if (w.props.left !== 'auto'){
w.props.left = newLeft
}
editedProps.push('left')
changedProps.push('left')
}
}
@ -966,24 +947,24 @@ class Editor {
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 / this.getWidgetParentContainer(w).offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
w.props.height = (100 * PXSCALE * newHeight / w.container.parentNode.offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.height = newHeight
}
editedProps.push('height')
changedProps.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+$/, '') + '%'
w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
} else if (w.props.top !== 'auto'){
w.props.top = newTop
}
editedProps.push('top')
changedProps.push('top')
}
}
if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {editedProps: editedProps, preventSelect: this.selectedWidgets.length > 1}))
if (w.props.width !== undefined || w.props.height !== undefined) newWidgets.push(updateWidget(w, {changedProps: changedProps, preventSelect: this.selectedWidgets.length > 1}))
}
@ -1009,18 +990,18 @@ class Editor {
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 / this.getWidgetParentContainer(w).offsetHeight).toFixed(2).replace(/\.?0+$/, '') + '%'
w.props.top = (100 * PXSCALE * newTop / w.container.parentNode.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 / this.getWidgetParentContainer(w).offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
w.props.left = (100 * PXSCALE * newLeft / w.container.parentNode.offsetWidth).toFixed(2).replace(/\.?0+$/, '') + '%'
} else {
w.props.left = newLeft
}
newWidgets.push(updateWidget(w, {editedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
newWidgets.push(updateWidget(w, {changedProps: ['top', 'left'], preventSelect: this.selectedWidgets.length > 1}))
}
@ -1035,9 +1016,7 @@ class Editor {
pushHistory(indexes) {
if (!ENV.noWarning) {
this.unsavedSession = true
}
this.unsavedSession = true
if (this.historyState > -1) {
this.history.splice(0, this.historyState + 1)
@ -1110,7 +1089,7 @@ class Editor {
if (indexes) {
options = {...indexes}
} else {
options.editedProps = Object.keys(subpatch)
options.changedProps = Object.keys(subpatch)
options.reuseChildren = false
}
@ -1133,4 +1112,6 @@ class Editor {
var editor = new Editor()
export default editor
module.exports = editor
require('./context-menu')

View file

@ -1,7 +1,5 @@
import iOS from '../ui/ios.mjs'
import editor from '../editor/index.mjs'
import {DOM, FOCUSABLE, ENV} from '../globals.mjs'
const iOS = require('../ui/ios')
const editor = require('../editor')
const macOs = (navigator.platform || '').match('Mac')
var longTouchTimer = false,

View file

@ -1,4 +1,4 @@
export default function(eventName, options={}){
module.exports = function(eventName, options={}){
var widget_storage_key = '_' + eventName + '_widget'
@ -19,9 +19,13 @@ export default function(eventName, options={}){
if (container) container[widget_storage_key].trigger(eventName, event)
}
document.addEventListener(eventName, (event)=>{
triggerWidgetEvent(event.target, event)
}, {passive: !!options.passive, capture: !!options.capture})
DOM.ready(()=>{
document.addEventListener(eventName, (event)=>{
triggerWidgetEvent(event.target, event)
}, {passive: !!options.passive, capture: !!options.capture})
})
return {

View file

@ -1,6 +1,4 @@
import {DOUBLE_TAP_TIME} from '../globals.mjs'
export default (element, callback, options={})=>{
module.exports = (element, callback, options={})=>{
var lastTapTime = 0,
lastTapX,

View file

@ -1,6 +1,5 @@
import {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} from './utils.mjs'
import iOS from '../ui/ios.mjs'
import {DOM} from '../globals.mjs'
const {normalizeDragEvent, resetEventOffset, TRAVERSING_SAMEWIDGET} = require('./utils')
const iOS = require('../ui/ios')
var targets = {},
previousPointers = {}
@ -330,97 +329,106 @@ function triggerWidgetEvent(target, name, event, containersOnly) {
}
// 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)
DOM.ready(()=>{
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
if (!iOS) {
document.addEventListener('pointermove', mouseMoveCapture, true)
if ('onwebkitmouseforcechanged' in document) document.addEventListener('webkitmouseforcechanged', mouseMoveCapture, true)
}
if (!iOS) document.addEventListener('pointerup', mouseUpCapture, true)
var {element, multitouch} = options
document.addEventListener('touchmove', touchMoveCapture, true)
element.addEventListener('touchstart', touchDownCapture, false)
element._drag_widget = this
element._drag_multitouch = multitouch
if ('ontouchforcechange' in document) document.addEventListener('touchforcechange', touchMoveCapture, true)
}
DOM.addEventListener(document, 'touchend touchcancel', touchUpCapture, true)
export function teardown(options) {
if (!iOS) document.addEventListener('pointerdown', mouseDownCapture)
if (
this._customBindings['drag'] !== 0 ||
this._customBindings['draginit'] !== 0 ||
this._customBindings['dragend'] !== 0 ||
!options || options.ignoreCustomBindings
) {
return
}
})
var {element} = options
module.exports = {
element.style.touchAction = ''
element.removeEventListener('touchstart', touchDownCapture, false)
delete element._drag_widget
delete element._drag_multitouch
setup: function(options) {
}
if (
this._customBindings['drag'] !== 0 ||
this._customBindings['draginit'] !== 0 ||
this._customBindings['dragend'] !== 0 ||
!options || options.ignoreCustomBindings
) {
return
}
export function enableTraversingGestures(element, options={}) {
var {element, multitouch} = options
if (element._traversing) return
element.addEventListener('touchstart', touchDownCapture, false)
element._drag_widget = this
element._drag_multitouch = multitouch
var traversing = options.type ? TRAVERSING_SAMEWIDGET : true,
traversingType = options.type === 'smart' || options.type === 'auto' ? '' : options.type
},
element._traversing = traversing
teardown: function(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
},
enableTraversingGestures: function(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)
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
})
},
disableTraversingGestures: function(element) {
if (!element._traversing) return
delete element._traversing
DOM.dispatchEvent(element, 'disableTraversingGestures')
}
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')
}

View file

@ -1,25 +1,20 @@
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')
}
var customEvents = {}
setTimeout(()=>{
customEvents['draginit'] = customEvents['drag'] = customEvents['dragend'] = require('./drag')
customEvents['resize'] = require('./resize')
customEvents['wheel'] = require('./dom-event')('wheel')
customEvents['scroll'] = require('./dom-event')('scroll', {capture: true})
customEvents['click'] = require('./dom-event')('click')
customEvents['fast-click'] = require('./dom-event')('fast-click')
customEvents['focus'] = require('./dom-event')('focus', {capture: true})
customEvents['blur'] = require('./dom-event')('blur', {capture: true})
customEvents['change'] = require('./dom-event')('change')
})
// micro optimisation from eventemitter3
var has = Object.prototype.hasOwnProperty
export default class EventEmitter {
module.exports = class EventEmitter {
constructor() {

View file

@ -1,8 +1,7 @@
import fastdom from 'fastdom'
var fastdom = require('fastdom')
var elements = []
export function check(context, force){
function checkResizes(context, force){
fastdom.measure(()=>{
// Iterate over all elements to which the 'resize' event is bound.
let resizedElems = [],
@ -39,25 +38,30 @@ export function check(context, force){
}
window.addEventListener('resize', ()=>{check(document)})
window.addEventListener('resize', ()=>{checkResizes(document)})
export function setup(options) {
module.exports = {
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
}
setup: function(options) {
if (!options) return
if (elements.indexOf(options.element) == -1) {
elements.push(options.element)
options.element._resize_widget = this
}
},
teardown: function(options) {
if (!options) return
if (elements.indexOf(options.element) != -1) {
elements.splice(elements.indexOf(options.element), 1)
delete options.element._resize_widget
}
},
check: checkResizes
}

View file

@ -4,12 +4,9 @@
Disabled for now
*/
/* global WebKitCSSMatrix */
var I = new WebKitCSSMatrix()
function Point(x, y, z) {
@ -48,7 +45,7 @@ function getTransformationMatrix(w) {
}
export default function cssTransformCoords(node, x, y) {
module.exports = function cssTransformCoords(node, x, y) {
return new Point(x, y, 0).transformBy(getTransformationMatrix(node).inverse())

118
src/client/events/utils.js Normal file
View file

@ -0,0 +1,118 @@
const Touch = window.Touch || class Touch {}
const zoom = require('../ui/zoom')
// const cssTransformCoords = require('./transform-coords')
module.exports = {
fix: function(e) {
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 / zoom.localZoom,
movementY: e.movementY === undefined ? undefined : e.movementY / zoom.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
}
},
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 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
},
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 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
// }
},
TRAVERSING_SAMEWIDGET: 1
}

View file

@ -1,123 +0,0 @@
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

46
src/client/globals.js Normal file
View file

@ -0,0 +1,46 @@
window.IP = window.IP || ''
window.ENV = window.ENV || {}
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, (s,k,v)=>{
ENV[k]=v
})
for (var k in ENV) {
ENV[k.toLowerCase()] = ENV[k]
}
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.KIOSK = window.KIOSK || false
window.GRIDWIDTH_CSS = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
window.GRIDWIDTH = GRIDWIDTH_CSS
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.CLIENT_SYNC = parseInt(ENV.clientSync) !== 0
window.TOGGLE_ALT_TRAVERSING = !!ENV.altTraversing
window.VIRTUAL_KEYBOARD = !!ENV.virtualKeyboard
window.FOCUSABLE = !ENV.noFocus
if (!FOCUSABLE) console.debug('ELECTRON.SETFOCUSABLE(0)')
else console.debug('ELECTRON.SETFOCUSABLE(1)')
window.JSON.parseFlex = require('json5').parse
window.DOM = require('./dom')
window.TITLE = ENV.title || (PACKAGE.productName + ' v' + PACKAGE.version)

View file

@ -1,61 +0,0 @@
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)

46
src/client/index.js Normal file
View file

@ -0,0 +1,46 @@
document.addEventListener('DOMContentLoaded', function(event) {
require('./globals')
require('./stacktrace')
var locales = require('./locales')
DOM.init()
var uiLoading = require('./ui/ui-loading')
uiLoading(locales('loading_server'))
function init() {
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)
}
if (document.requestStorageAccess) {
document.requestStorageAccess().then(init, init)
} else {
init()
}
})

View file

@ -1,25 +0,0 @@
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()
})

View file

@ -1,19 +1,18 @@
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'
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'),
{updateMobileThemeColor} = require('../ui/utils')
export default {
module.exports = {
bundle: function(data) {
for (let i in data) {
@ -86,7 +85,7 @@ export default {
},
error: function(data){
new UiModal({title: raw(icon('exclamation-triangle') + '&nbsp; ' + locales('error')), content: raw(data), closable:true})
new UiModal({title: raw(utils.icon('exclamation-triangle') + '&nbsp; ' + locales('error')), content: raw(data), closable:true})
},
errorLog: function(data) {
@ -115,7 +114,7 @@ export default {
var root = widgetManager.getWidgetById('root')[0]
if (root) root.onPropChanged('colorWidget')
fastdom.measure(()=>{
setGRIDWIDTH_CSS(parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width')))
GRIDWIDTH_CSS = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--grid-width'))
fastdom.mutate(()=>{
editor.toggleGrid()
editor.toggleGrid()

View file

@ -1,22 +1,10 @@
import {nanoid} from 'nanoid'
import EventEmitter from '../events/event-emitter.mjs'
import cache from '../managers/cache.mjs'
import {ENV} from '../globals.mjs'
var EventEmitter = require('../events/event-emitter'),
cache = require('../managers/cache'),
{nanoid} = require('nanoid'), uuid,
notifications,
locales
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)
var localUuid = ENV.id || cache.get('osc.uuid', false)
if (localUuid) {
uuid = localUuid
} else {
@ -24,6 +12,11 @@ if (localUuid) {
cache.set('uuid', uuid, false)
}
setTimeout(()=>{
notifications = require('../ui/notifications')
locales = require('../locales')
})
var reconnectTimeout = 500,
hearbeatInterval = 5000,
hearbeatTimeout = 3000,
@ -55,30 +48,26 @@ 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(callback) {
init() {
loadDeps.then(()=>{
var callbacks = require('./callbacks')
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()
})
for (let i in callbacks) {
let callback = callbacks[i]
this.on(i, (data)=>{
callback(data)
})
}
}
@ -203,4 +192,4 @@ class Ipc extends EventEmitter {
var ipc = new Ipc()
export default ipc
module.exports = ipc

View file

@ -1,4 +1,4 @@
export default {
module.exports = {
// console
console: 'Konsole',

View file

@ -1,4 +1,4 @@
export default {
module.exports = {
// console
console: 'Console',
@ -96,7 +96,7 @@ export default {
// notifications
notifications: 'Notifications',
// remote save
remotesave_open: 'Open (on the server)',
remotesave_save: 'Save (on the server)',

View file

@ -1,4 +1,4 @@
export default {
module.exports = {
// console
console: 'Console',

View file

@ -0,0 +1,14 @@
var locales = {
en: require('./en'),
fr: require('./fr'),
de: require('./de'),
ok: require('./pl'),
debug: {
/* empty */
keyboard_layout: require('./en').keyboard_layout
}
}
var lang = locales[LANG] ? LANG : 'en'
module.exports = key=>locales[lang][key] || `!${key}!`

View file

@ -1,17 +0,0 @@
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}!`

View file

@ -1,4 +1,4 @@
export default {
module.exports = {
// console
console: 'Terminal',

View file

@ -4,33 +4,17 @@ class Cache {
set(key, value, persistent = true) {
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)
}
var storage = persistent ? localStorage : sessionStorage
storage.setItem(keyPrefix + key, JSON.stringify(value))
}
get(key, persistent = true) {
try {
var storage = persistent ? localStorage : sessionStorage
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
}
return JSON.parse(storage.getItem(keyPrefix + key))
}
@ -68,4 +52,4 @@ class Cache {
}
export default new Cache()
module.exports = new Cache()

View file

@ -1,18 +1,18 @@
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 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'),
EventEmitter = require('../../events/event-emitter'),
{deepEqual} = require('../../utils')
var SessionManager = class SessionManager extends EventEmitter {
@ -167,7 +167,7 @@ var SessionManager = class SessionManager extends EventEmitter {
this.load(data.fileContent, ()=>{
this.setSessionPath(data.path)
ipc.send('sessionOpened', {path: data.path, sync: CLIENT_SYNC})
ipc.send('sessionOpened', {path: data.path})
})
}
@ -295,4 +295,4 @@ var SessionManager = class SessionManager extends EventEmitter {
var sessionManager = new SessionManager()
export default sessionManager
module.exports = sessionManager

View file

@ -1,7 +1,6 @@
import semver from 'semver'
import UiModal from '../../ui/ui-modal.mjs'
import locales from '../../locales/index.mjs'
import {PACKAGE} from '../../globals.mjs'
var semver = require('semver'),
UiModal = require('../../ui/ui-modal'),
locales = require('../../locales')
class Session {
@ -348,4 +347,4 @@ for (var i in converters) {
Session.converters[converters[i].version] = converters[i]
}
export default Session
module.exports = Session

View file

@ -1,12 +1,12 @@
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 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')
var StateManager = class StateManager {
@ -65,7 +65,7 @@ var StateManager = class StateManager {
if (widgets[j].setValue && !widgets[j].noValueState) {
widgets[j].setValue(value, {send:send, sync:true})
widgets[j].setValue(value, {send:send, sync:true, fromState:true})
}
@ -226,7 +226,7 @@ var StateManager = class StateManager {
if (this.valueStateQueue[id] !== undefined) {
for (let w of widgetManager.getWidgetById(id)) {
if (w.noValueState) continue
w.setValue(this.valueStateQueue[id], {sync: true, script: false})
w.setValue(this.valueStateQueue[id], {sync: true, fromState:true, fromEdit: true})
}
}
}
@ -235,7 +235,7 @@ var StateManager = class StateManager {
if (this.valueNewPropQueue[id] != this.valueOldPropQueue[id]) {
for (let w of widgetManager.getWidgetById(id)) {
if (w.noValueState) continue
w.setValue(w.getProp('value'), {sync: true})
w.setValue(w.getProp('value'), {sync: true, fromState:true})
}
}
}
@ -260,4 +260,4 @@ var StateManager = class StateManager {
var stateManager = new StateManager()
export default stateManager
module.exports = stateManager

View file

@ -1,5 +1,5 @@
import EventEmitter from '../events/event-emitter.mjs'
import ipc from '../ipc/index.mjs'
var EventEmitter = require('../events/event-emitter'),
ipc = require('../ipc/')
class WidgetManager extends EventEmitter {
@ -38,8 +38,6 @@ 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])
linkId = linkId.filter(x=>this.linkIdLock.indexOf(x)<0)
this.linkIdLock = this.linkIdLock.concat(linkId)
this.linkIdLockDepth++
@ -119,8 +117,6 @@ 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]] = []
@ -184,9 +180,7 @@ class WidgetManager extends EventEmitter {
if (address && this.addressRoute[address].indexOf(hash) != -1) this.addressRoute[address].splice(this.addressRoute[address].indexOf(hash), 1)
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.map(x=>String(x))
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)
}
@ -266,22 +260,7 @@ class WidgetManager extends EventEmitter {
}
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 []
}
getWidgetById(id) {
return this.getWidgetBy(id, this.idRoute)
@ -347,4 +326,4 @@ class WidgetManager extends EventEmitter {
var widgetManager = new WidgetManager()
export default widgetManager
module.exports = widgetManager

View file

@ -1,8 +1,7 @@
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 widgetManager = require('./managers/widgets'),
EventEmitter = require('./events/event-emitter'),
ipc = require('./ipc/'),
{deepEqual} = require('./utils')
var Osc = class Osc extends EventEmitter {
@ -14,9 +13,9 @@ var Osc = class Osc extends EventEmitter {
this.remoteControl = {}
this.serverTargets = []
;(async()=>{
this.remoteControl = (await import('./remote-control.mjs')).default
})()
setTimeout(()=>{
osc.remoteControl = require('./remote-control')
})
}
@ -91,4 +90,4 @@ var Osc = class Osc extends EventEmitter {
var osc = new Osc()
export default osc
module.exports = osc

View file

@ -1,6 +1,6 @@
import widgetManager from './managers/widgets.mjs'
import stateManager from './managers/state.mjs'
import {deepCopy} from './utils.mjs'
var widgetManager = require('./managers/widgets'),
stateManager = require('./managers/state'),
{deepCopy} = require('./utils')
var Parser = class Parser {
@ -10,13 +10,6 @@ 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) {
@ -45,8 +38,7 @@ var Parser = class Parser {
index,
hash,
locals,
variables,
meta
variables
} = options
var props = data
@ -90,8 +82,7 @@ var Parser = class Parser {
children,
hash,
locals,
variables,
meta
variables
})
widgetManager.addWidget(widget)
@ -125,4 +116,9 @@ var Parser = class Parser {
var parser = new Parser()
export default parser
module.exports = parser
parser.widgets = require('./widgets/').widgets
for (var k in parser.widgets) {
parser.defaults[k] = parser.widgets[k].defaults()._props()
}

View file

@ -1,12 +1,11 @@
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 {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'),
uiConsole = require('./ui/ui-console')
var callbacks = {
'/EDIT': function(args, custom_module) {
@ -14,8 +13,8 @@ var callbacks = {
if (READ_ONLY && !custom_module) return
var [id, json, opts] = args,
newdata = typeof json == 'string' ? JSON5.parse(json) : json,
options = typeof opts == 'string' ? JSON5.parse(opts) : {},
newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
@ -31,7 +30,7 @@ var callbacks = {
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs),
editedProps: Object.keys(newdata)
changedProps: Object.keys(newdata)
})
}
@ -46,8 +45,8 @@ var callbacks = {
if (READ_ONLY && !custom_module) return
var [id, json, opts] = args,
newdata = typeof json == 'string' ? JSON5.parse(json) : json,
options = typeof opts == 'string' ? JSON5.parse(opts) : {},
newdata = typeof json == 'string' ? JSON.parseFlex(json) : json,
options = typeof opts == 'string' ? JSON.parseFlex(opts) : {},
widgets = widgetManager.getWidgetById(id)
if (!widgets.length) return
@ -61,7 +60,7 @@ var callbacks = {
updateWidget(widget, {
reuseChildren: !(newdata.widgets || newdata.tabs),
editedProps: Object.keys(newdata)
changedProps: Object.keys(newdata)
})
}
@ -210,7 +209,7 @@ var callbacks = {
if (!Array.isArray(args)) args = [args]
var json = args[0],
data = typeof json == 'string' ? JSON5.parse(json) : json,
data = typeof json == 'string' ? JSON.parseFlex(json) : json,
send = !(args[1] === 0 || args[1] === false)
stateManager.set(data, send)
@ -314,7 +313,7 @@ var callbacks = {
}
}
export default {
module.exports = {
exec: function(name, args, custom_module){
if (callbacks[name]) {
callbacks[name](args, custom_module)

33
src/client/stacktrace.js Normal file
View file

@ -0,0 +1,33 @@
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)`)
})
}

View file

@ -1,21 +0,0 @@
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)`)
})
}

View file

@ -1,12 +1,11 @@
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',
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
class ContextMenu extends UiWidget {
constructor(options={}){
@ -218,4 +217,4 @@ class ContextMenu extends UiWidget {
}
export default ContextMenu
module.exports = ContextMenu

View file

@ -1,7 +1,7 @@
import screenfull from 'screenfull'
import UiModal from './ui-modal.mjs'
import locales from '../locales/index.mjs'
import iOS from './ios.mjs'
var screenfull = require('screenfull'),
UiModal = require('./ui-modal'),
locales = require('../locales'),
iOS = require('./ios')
var fullscreen
@ -40,4 +40,4 @@ if (screenfull.isEnabled && !iOS) {
window.ELECTRON_FULLSCREEN = ()=>{fullscreen.toggle()}
export default fullscreen
module.exports = fullscreen

7
src/client/ui/index.js Normal file
View file

@ -0,0 +1,7 @@
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')})
}

View file

@ -1,5 +0,0 @@
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')})

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

@ -0,0 +1,12 @@
require('./zoom')
require('../events/click')
require('./ios')
require('./notifications')
require('./ui-workspace')
require('./main-menu')
require('./ui-console')
require('./utils').updateMobileThemeColor()
if (!navigator.userAgent.match(/Android|iPhone|iPad|iPod/i)) {
require('./ui-keyboard')
}

Some files were not shown because too many files have changed in this diff Show more