commit b8558549d1ca4ff74a0d131dfd5ca3806e29751b Author: zhongjin Date: Sun Nov 11 10:48:33 2018 +0800 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df61494 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +.idea +# dependencies +/node_modules + +# testing +/coverage + +# production +/www +/src/build +/src/src/icons/icons.js +/src/public/vendor.js +/src/public/vendor.js.map +/src/src/version.js +/src/.idea +/src/node_modules + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +node_modules +iob_npm.done +package-lock.json +/src/public/_socket/info.js +/src/src/i18n/flat diff --git a/.npmignore b/.npmignore new file mode 100644 index 0000000..6dd1822 --- /dev/null +++ b/.npmignore @@ -0,0 +1,12 @@ +gulpfile.js +tasks +node_modules +nativeDroid2-master +.idea +.git +.travis.yml +appveyor.yml +test +src +iob_npm.done +package-lock.json diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ce33bba --- /dev/null +++ b/.travis.yml @@ -0,0 +1,7 @@ +os: + - linux +language: node_js +node_js: + - '6' + - '8' + - '10' diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0bd1517 --- /dev/null +++ b/LICENSE @@ -0,0 +1,91 @@ +Creative Commons Attribution-NonCommercial 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + +Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. +Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. +Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. +Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. +Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. +Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. +Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. +Licensor means the individual(s) or entity(ies) granting rights under this Public License. +NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. +Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. +Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. +You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. +Section 2 – Scope. + +License grant. +Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: +reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and +produce, reproduce, and Share Adapted Material for NonCommercial purposes only. +Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. +Term. The term of this Public License is specified in Section 6(a). +Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. +Downstream recipients. +Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. +No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. +No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). +Other rights. + +Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. +Patent and trademark rights are not licensed under this Public License. +To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +Attribution. + +If You Share the Licensed Material (including in modified form), You must: + +retain the following if it is supplied by the Licensor with the Licensed Material: +identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); +a copyright notice; +a notice that refers to this Public License; +a notice that refers to the disclaimer of warranties; +a URI or hyperlink to the Licensed Material to the extent reasonably practicable; +indicate if You modified the Licensed Material and retain an indication of any previous modifications; and +indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. +You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. +If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. +If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; +if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and +You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. +To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. +The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. +Section 6 – Term and Termination. + +This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. +Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + +automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or +upon express reinstatement by the Licensor. +For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. +For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. +Sections 1, 5, 6, 7, and 8 survive termination of this Public License. +Section 7 – Other Terms and Conditions. + +The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. +Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. +Section 8 – Interpretation. + +For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. +To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. +No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. +Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..cca932f --- /dev/null +++ b/README.md @@ -0,0 +1,117 @@ +![Logo](admin/material.png) +# yunkong2.material +================= + +[![NPM version](http://img.shields.io/npm/v/yunkong2.material.svg)](https://www.npmjs.com/package/yunkong2.material) +[![Downloads](https://img.shields.io/npm/dm/yunkong2.material.svg)](https://www.npmjs.com/package/yunkong2.material) + +[![NPM](https://nodei.co/npm/yunkong2.material.png?downloads=true)](https://nodei.co/npm/yunkong2.material/) + +React and Material UI interface. + +![Screenshots](img/screenshot1.png) + +## Installation +**Important!** +This adapter cannot be installed directly from github. Only from npm. + +## Usage +It is very important to know, that adapter shows only devices that added to some categories, like *rooms* or *function*. +Better if every device belongs to both categories. Because every device has the type and place. + + +## Supported types +### Switch +### Dimmer +### Media player +### Volume +### Group volume + +## ToDO +* Cams (over extra Adapter) +* events (over extra Adapter) +* Main screen +* Charts +* Narrow menu +* vacuum cleaner +* show bar for sliders to indicate position +* support of quality codes +* Maps (OpensStreetMap) +* Switch to default screen after X seconds +* Order states in info +* Use icons in weather and not text + +## Credits +- Used icons from flaticon +- Volume knob from [here](https://codepen.io/blucube/pen/cudAz) By [Ed Hicks](https://twitter.com/blucube) - Inspired by a [dribbble shot](https://dribbble.com/shots/753124-Volume-Knob) by [Ricardo Salazar](https://twitter.com/rickss) + +## Changelog +### 0.10.5 (2018.10.15) +* (bluefox) fix error with settings + +### 0.10.3 (2018.09.02) +* (bluefox) implement color temperature +* (bluefox) implement cache of objects + +### 0.10.1 (2018.09.02) +* (bluefox) GUI corrections +### 0.10.0 (2018.08.30) +* (bluefox) RGB was corrected + +### 0.9.12 (2018.08.19) +* (bluefox) RGB was implemented + +### 0.9.11 (2018.08.14) +* (bluefox) Fixed error with empty page + +### 0.9.10 (2018.08.08) +* (bluefox) Crop of images was implemented +* (bluefox) Background of tiles is possible +* (bluefox) Double width of every tile is possible +* (bluefox) Group light control +* (bluefox) Custom URLs implemented + +### 0.9.9 (2018.08.03) +* (bluefox) Order of tiles is implemented +* (bluefox) Support of dwd data + +### 0.9.7 (2018.07.30) +* (bluefox) Implemented the weather widget + +### 0.9.4 (2018.07.26) +* (bluefox) Bug-fixes + +### 0.9.3 (2018.07.25) +* (bluefox) Many changes + +### 0.9.2 (2018.07.21) +* (bluefox) Update logic was implemented (only with web 2.4.1) + +### 0.9.1 (2018.07.20) +* (bluefox) Volume control was implemented + +### 0.8.9 (2018.07.17) +* (bluefox) React app + +### 0.5.7 (2018.01.24) +* (bluefox) Ready for cloud services + +### 0.5.6 (2017.10.11) +* (bluefox) fix undefined names +* (bluefox) fix detection of switches + +### 0.5.3 (2017.08.11) +* (bluefox) fix dimmer + +### 0.5.2 (2017.07.30) +* (bluefox) fix action icons + +### 0.5.1 +* (bluefox) edit of visibility + +## License +CC-BY-NC + +Copyright (c) 2017-2018 bluefox + +Commercial use is not allowed without permission. diff --git a/admin/material.png b/admin/material.png new file mode 100644 index 0000000..6c07aa9 Binary files /dev/null and b/admin/material.png differ diff --git a/admin/material.svg b/admin/material.svg new file mode 100644 index 0000000..29acdf9 --- /dev/null +++ b/admin/material.svg @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..fe06ff0 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,18 @@ +version: 'test-{build}' +environment: + matrix: + - nodejs_version: '6' + - nodejs_version: '8' + - nodejs_version: '10' +platform: + - x86 +clone_folder: 'c:\projects\%APPVEYOR_PROJECT_NAME%' +install: + - ps: 'Install-Product node $env:nodejs_version $env:platform' + - npm install +test_script: + - echo %cd% + - node --version + - npm --version + - npm test +build: 'off' diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..d42b294 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,283 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +const gulp = require('gulp'); +const exec = require('gulp-exec'); +const fs = require('fs'); +const copy = require('gulp-copy'); +const connect = require('gulp-connect'); +const watch = require('gulp-watch'); +const del = require('del'); +const uglify = require('gulp-uglify'); +const concat = require('gulp-concat'); +const sourcemaps = require('gulp-sourcemaps'); +const crypto = require('crypto'); + +const dir = __dirname + '/src/src/i18n/'; +gulp.task('i18n=>flat', done => { + const files = fs.readdirSync(dir).filter(name => name.match(/\.json$/)); + const index = {}; + const langs = []; + files.forEach(file => { + const lang = file.replace(/\.json$/, ''); + langs.push(lang); + let text = require(dir + file); + + for (const id in text) { + if (text.hasOwnProperty(id)) { + index[id] = index[id] || {}; + index[id][lang] = text[id] === undefined ? id : text[id]; + } + } + }); + + const keys = Object.keys(index); + keys.sort(); + + if (!fs.existsSync(dir + '/flat/')) { + fs.mkdirSync(dir + '/flat/'); + } + + langs.forEach(lang => { + const words = []; + keys.forEach(key => { + words.push(index[key][lang]); + }); + fs.writeFileSync(dir + '/flat/' + lang + '.txt', words.join('\n')); + }); + fs.writeFileSync(dir + '/flat/index.txt', keys.join('\n')); + done(); +}); + +gulp.task('flat=>i18n', done => { + if (!fs.existsSync(dir + '/flat/')) { + console.error(dir + '/flat/ directory not found'); + return done(); + } + const keys = fs.readFileSync(dir + '/flat/index.txt').toString().split(/[\r\n]/); + + const files = fs.readdirSync(dir + '/flat/').filter(name => name.match(/\.txt$/) && name !== 'index.txt'); + const index = {}; + const langs = []; + files.forEach(file => { + const lang = file.replace(/\.txt$/, ''); + langs.push(lang); + let lines = fs.readFileSync(dir + '/flat/' + file).toString().split(/[\r\n]/); + lines.forEach((word, i) => { + index[keys[i]] = index[keys[i]] || {}; + index[keys[i]][lang] = word; + }); + }); + langs.forEach(lang => { + const words = {}; + keys.forEach(key => { + words[key] = index[key][lang]; + }); + fs.writeFileSync(dir + '/' + lang + '.json', JSON.stringify(words, null, 2)); + }); +}); + +gulp.task('clean', () => { + return del([ + 'src/node_modules/**/*', + 'src/build/**/*', + 'src/src/version.js', + 'src/package-lock.json' + ]).then(del([ + 'src/node_modules', + 'src/build' + ])); +}); + +function npmInstall() { + return new Promise((resolve, reject) => { + // Install node modules + const cwd = __dirname.replace(/\\/g, '/') + '/src/'; + + const cmd = `npm install`; + console.log(`"${cmd} in ${cwd}`); + + // System call used for update of js-controller itself, + // because during installation npm packet will be deleted too, but some files must be loaded even during the install process. + const exec = require('child_process').exec; + const child = exec(cmd, {cwd}); + + child.stderr.pipe(process.stderr); + child.stdout.pipe(process.stdout); + + child.on('exit', (code /* , signal */) => { + // code 1 is strange error that cannot be explained. Everything is installed but error :( + if (code && code !== 1) { + reject('Cannot install: ' + code); + } else { + console.log(`"${cmd} in ${cwd} finished.`); + // command succeeded + resolve(); + } + }); + }); +} + +gulp.task('2-npm', () => { + if (fs.existsSync(__dirname + '/src/node_modules')) { + return Promise.resolve(); + } else { + return npmInstall(); + } +}); + +gulp.task('2-npm-dep', ['clean'], () => { + if (fs.existsSync(__dirname + '/src/node_modules')) { + return Promise.resolve(); + } else { + return npmInstall(); + } +}); + +function build() { + const options = { + continueOnError: false, // default = false, true means don't emit error event + pipeStdout: false, // default = false, true means stdout is written to file.contents + customTemplatingThing: 'build', // content passed to gutil.template() + cwd: __dirname + '/src/' + }; + const reportOptions = { + err: true, // default = true, false means don't write err + stderr: true, // default = true, false means don't write stderr + stdout: true // default = true, false means don't write stdout + }; + + console.log(options.cwd); + + if (fs.existsSync(__dirname + '/src/node_modules/react-scripts/scripts/build.js')) { + return gulp.src(__dirname + '/src/node_modules/react-scripts/scripts/build.js') + .pipe(exec('node <%= file.path %>', options)) + .pipe(exec.reporter(reportOptions)).pipe(connect.reload()); + } else { + return gulp.src(__dirname + '/node_modules/react-scripts/scripts/build.js') + .pipe(exec('node <%= file.path %>', options)) + .pipe(exec.reporter(reportOptions)).pipe(connect.reload()); + + } +} + +gulp.task('3-build', () => build()); + +gulp.task('3-build-dep', ['2-npm', 'icons', 'version', 'vendorJS'], () => build()); + +gulp.task('version', done => { + const pack = require('./package'); + fs.writeFileSync(__dirname + '/src/src/version.js', 'export default \'' + pack.version + '\';'); + done(); +}); + +const ignoreSvgs = ['fireOff.svg']; + +gulp.task('icons', done => { + const dir = __dirname + '/src/src/icons'; + const files = fs.readdirSync(__dirname + '/src/src/icons').filter(e => e.match(/\.svg$/) && ignoreSvgs.indexOf(e) === -1); + const texts = files.map(file => fs.readFileSync(dir + '/' + file)); + let text = ['import {Component} from "react";']; + text.push('class IconList extends Component {'); + text.push(' static List = ['); + texts.forEach(file => text.push(' ' + '"data:image/svg+xml;base64,' + Buffer.from(file).toString('base64') + '",')); + text.push(' ];'); + text.push('}'); + text.push('export default IconList;'); + fs.writeFileSync(dir + '/icons.js', text.join('\n')); + done(); +}); + +gulp.task('vendorJS', () => { + return gulp.src([ + 'src/public/vendor/*.js', + '!src/public/vendor/conn.js', + '!src/public/vendor/socket.io.js' + ]) + .pipe(sourcemaps.init()) + .pipe(concat('vendor.js')) + .pipe(uglify()) + .pipe(sourcemaps.write('.')) + .pipe(gulp.dest('src/public')); +}); + +function getHash(data) { + const md5 = crypto.createHash('md5'); + md5.update(data); + + return md5.digest('hex'); +} + +function modifyServiceWorker() { + return new Promise(resolve => { + try { + let text = fs.readFileSync(__dirname + '/src/build/service-worker.js'); + if (text.toString().indexOf('vendor.js') === -1) { + const hash = getHash(text); + text = text.toString().replace('precacheConfig=[["./index.html"', 'precacheConfig=[["./vendor.js","' + hash + '"],["./index.html"'); + fs.writeFileSync(__dirname + '/src/build/service-worker.js', text); + } + } catch (e) { + console.error('Cannot modify service-worker.js' + e); + } + resolve(); + }); +} + +gulp.task('4-modifyServiceWorker-dep', ['3-build-dep'], () => { + return modifyServiceWorker(); +}); + +gulp.task('4-modifyServiceWorker', () => { + return modifyServiceWorker(); +}); + +function copyFiles() { + return del([ + 'www/**/*' + ]).then(() => { + gulp.src([ + 'src/build/*/**', + 'src/build/*', + '!src/build/vendor/conn.js', + '!src/build/vendor/detector.js', + '!src/build/_socket', + '!src/build/_socket/info.js' + ]) + .pipe(gulp.dest('www/')); + }); +} + +gulp.task('5-copy', ['vendorJS', '4-modifyServiceWorker'], () => { + return copyFiles(); +}); + +gulp.task('5-copy-dep', ['vendorJS', '4-modifyServiceWorker-dep'], () => { + return copyFiles(); +}); + +gulp.task('webserver', () => { + connect.server({ + root: 'src/build', + livereload: true + }); +}); + +gulp.task('watch', ['webserver'], () => { + // Callback mode, useful if any plugin in the pipeline depends on the `end`/`flush` event + return watch(['src/src/*/**', 'src/src/*'], { ignoreInitial: true }, ['build']); +}); + +gulp.task('default', ['5-copy-dep']); \ No newline at end of file diff --git a/img/screenshot1.png b/img/screenshot1.png new file mode 100644 index 0000000..238252a Binary files /dev/null and b/img/screenshot1.png differ diff --git a/io-package.json b/io-package.json new file mode 100644 index 0000000..afe4a3f --- /dev/null +++ b/io-package.json @@ -0,0 +1,232 @@ +{ + "common": { + "name": "material", + "version": "0.10.5", + "news": { + "0.10.5": { + "en": "The error with settings was fixed", + "de": "Der Fehler bei den Einstellungen wurde behoben", + "ru": "Исправлена ​​ошибка с настройками", + "pt": "O erro com as configurações foi corrigido", + "nl": "De fout met de instellingen was verholpen", + "fr": "L'erreur avec les paramètres a été corrigée", + "it": "L'errore con le impostazioni è stato corretto", + "es": "El error con la configuración fue arreglado", + "pl": "Naprawiono błąd związany z ustawieniami" + }, + "0.10.3": { + "en": "Color temperature was implemented\nCache of objects was implemented", + "de": "Farbtemperatur wurde implementiert\nCache von Objekten wurde implementiert", + "ru": "Цветовая температура была реализована\nБыл реализован кеш объектов", + "pt": "Temperatura de cor foi implementada\nCache de objetos foi implementado", + "nl": "Kleurtemperatuur is geïmplementeerd\nCache met objecten is geïmplementeerd", + "fr": "La température de couleur a été mise en œuvre\nLe cache des objets a été implémenté", + "it": "La temperatura del colore è stata implementata\nLa cache degli oggetti è stata implementata", + "es": "La temperatura del color fue implementada\nSe implementó el caché de objetos", + "pl": "Wprowadzono temperaturę kolorów\nPamięć podręczna obiektów została zaimplementowana" + }, + "0.10.1": { + "en": "GUI corrections", + "de": "GUI-Korrekturen", + "ru": "Исправления GUI", + "pt": "Correções da GUI", + "nl": "GUI-correcties", + "fr": "Corrections GUI", + "it": "Correzioni della GUI", + "es": "Correcciones GUI", + "pl": "Poprawki GUI" + }, + "0.10.0": { + "en": "RGB was corrected", + "de": "RGB wurde korrigiert", + "ru": "RGB был исправлен", + "pt": "RGB foi corrigido", + "nl": "RGB is gecorrigeerd", + "fr": "RVB a été corrigé", + "it": "RGB è stato corretto", + "es": "RGB fue corregido", + "pl": "RGB zostało poprawione" + }, + "0.9.12": { + "en": "RGB was implemented", + "de": "RGB wurde implementiert", + "ru": "RGB был реализован", + "pt": "RGB foi implementado", + "nl": "RGB is geïmplementeerd", + "fr": "RVB a été implémenté", + "it": "RGB è stato implementato", + "es": "RGB fue implementado", + "pl": "Zaimplementowano RGB" + }, + "0.9.11": { + "en": "Fixed error with empty page", + "de": "Fehler bei leerer Seite behoben", + "ru": "Исправлена ​​ошибка с пустой страницей", + "pt": "Corrigido erro com página vazia", + "nl": "Vaste fout met lege pagina", + "fr": "Erreur fixe avec page vide", + "it": "Risolto errore con la pagina vuota", + "es": "Se arregló el error con la página vacía", + "pl": "Naprawiono błąd z pustą stroną" + }, + "0.9.9": { + "en": "Order of tiles is implemented\nSupport of dwd data", + "de": "Reihenfolge der Kacheln ist implementiert\nUnterstützung von DWD-Daten", + "ru": "Выполняется заказ плитки\nПоддержка данных dwd", + "pt": "Ordem de telhas é implementada\nSuporte de dados do dwd", + "nl": "Orde van tegels is geïmplementeerd\nOndersteuning van dwd-gegevens", + "fr": "L'ordre des carreaux est implémenté\nPrise en charge des données DWD", + "it": "L'ordine delle piastrelle è implementato\nSupporto di dati DWD", + "es": "Se implementa el orden de las fichas\nSoporte de datos dwd", + "pl": "Kolejność płytek jest zaimplementowana\nObsługa danych DWD" + }, + "0.9.7": { + "en": "Implemented the weather widget", + "de": "Implementiert das Wetter Widget", + "ru": "Реализован погодный виджет", + "pt": "Implementou o widget do tempo", + "nl": "De weerwidget geïmplementeerd", + "fr": "Implémenté le widget météo", + "it": "Implementato il widget meteo", + "es": "Implementado el widget del clima", + "pl": "Wdrożyłem widget pogody" + }, + "0.9.4": { + "en": "Bug-fixes", + "de": "Fehlerbehebung", + "ru": "Исправление ошибок", + "pt": "Correções de bugs", + "nl": "Bugfixes", + "fr": "Corrections de bogues", + "it": "Bug-fix", + "es": "Corrección de errores", + "pl": "Poprawki błędów" + }, + "0.9.3": { + "en": "Many changes", + "de": "Viele Veränderungen", + "ru": "Много изменений", + "pt": "Muitas mudanças", + "nl": "Veel veranderingen", + "fr": "Beaucoup de changements", + "it": "Molti cambiamenti", + "es": "Muchos cambios", + "pl": "Wiele zmian" + }, + "0.9.2": { + "en": "Update logic was implemented", + "de": "Update-Logik wurde implementiert", + "ru": "Была реализована логика обновления", + "pt": "A lógica de atualização foi implementada", + "nl": "Update logica is geïmplementeerd", + "fr": "La mise à jour a été implémentée", + "it": "La logica di aggiornamento è stata implementata", + "es": "Se implementó la lógica de actualización", + "pl": "Zaktualizowana logika została zaimplementowana" + }, + "0.9.1": { + "en": "Volume control was implemented", + "de": "Lautstärkeregelung wurde implementiert", + "ru": "Регулятор громкости был реализован", + "pt": "Controle de volume foi implementado", + "nl": "Volumeregeling is geïmplementeerd", + "fr": "Le contrôle du volume a été implémenté", + "it": "Il controllo del volume è stato implementato", + "es": "Control de volumen fue implementado", + "pl": "Kontrola głośności została wdrożona" + }, + "0.8.9": { + "en": "React app" + }, + "0.5.7": { + "en": "Ready for cloud services", + "de": "Bereit für Cloud-Dienste", + "ru": "Готов к облачным сервисам", + "pt": "Pronto para serviços em nuvem", + "nl": "Klaar voor cloudservices", + "fr": "Prêt pour les services cloud", + "it": "Pronto per i servizi cloud", + "es": "Listo para servicios en la nube", + "pl": "Gotowy do usług w chmurze" + }, + "0.5.6": { + "en": "fix undefined names", + "de": "Korrigiere undefinierte Namen", + "ru": "Поправлены неопределённые имена" + }, + "0.5.3": { + "en": "fix dimmer", + "de": "Korrigiere Dimmer", + "ru": "Поправлены диммеры" + }, + "0.5.2": { + "en": "fix action icons", + "de": "Korrigiere Zustandsbldchen", + "ru": "Поправлены иконки" + }, + "0.5.1": { + "en": "initial commit", + "de": "initial commit", + "ru": "initial commit" + } + }, + "title": "Material UI", + "desc": { + "en": "Material UI based yunkong2 user interface", + "de": "yunkong2 GUI für mobile Geräte auf dem Basis von Material UI", + "ru": "yunkong2 визуализация для мобильных устройств на Material UI", + "pt": "Interface de usuário yunkong2 baseada em UI de material", + "nl": "Materiaal UI gebaseerde gebruikersinterface van yunkong2", + "fr": "Interface utilisateur yunkong2 basée sur l'interface utilisateur matérielle", + "it": "Interfaccia utente yunkong2 basata su UI materiale", + "es": "Interfaz de usuario yunkong2 basada en IU de material", + "pl": "Interfejs użytkownika yunkong2 oparty na interfejsie użytkownika" + }, + "platform": "javascript/Node.js", + "onlyWWW": "true", + "loglevel": "info", + "icon": "material.png", + "enabled": true, + "extIcon": "https://git.spacen.net/yunkong2/yunkong2.material/master/admin/material.png", + "keywords": ["user", "interface", "webapp", "jquerymobile", "ui"], + "readme": "https://git.spacen.net/yunkong2/yunkong2.material/blob/master/README.md", + "singleton": true, + "preserveSettings": "material", + "nogit": true, + "webPreSettings": { + "materialBackground": "native.loadingBackground" + }, + "authors": [ + "bluefox " + ], + "dependencies": [ + { + "web": ">=2.4.1" + } + ], + "localLink": "%web_protocol%://%ip%:%web_port%/material/index.html", + "type": "visualization", + "license": "CC-BY-NC", + "noConfig": true, + "eraseOnUpload": true, + "webByVersion": true, + "welcomeScreen": {"link": "material/index.html", "name": "material", "img": "material.admin/material.png", "color": "black", "order": 2} + }, + "native": { + "loadingBackground": "" + }, + "objects": [ + ], + "instanceObjects": [ + { + "_id": "", + "type": "meta", + "common": { + "name": "user files and images for material", + "type": "meta.user", + "expert": true + }, + "native": {} + } + ] +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..ba7ce4d --- /dev/null +++ b/package.json @@ -0,0 +1,54 @@ +{ + "name": "yunkong2.material", + "description": "React Material based yunkong2 user interface", + "version": "0.10.5", + "author": { + "name": "bluefox", + "email": "dogafox@gmail.com" + }, + "contributors": [ + "bluefox " + ], + "homepage": "https://git.spacen.net/yunkong2/yunkong2.material", + "repository": { + "type": "git", + "url": "https://git.spacen.net/yunkong2/yunkong2.material" + }, + "licenses": [ + { + "type": "CC-BY-NC-4.0", + "url": "https://git.spacen.net/yunkong2/yunkong2.material/blob/master/LICENSE" + } + ], + "keywords": [ + "yunkong2", + "GUI", + "web interface", + "home automation", + "material" + ], + "devDependencies": { + "del": "^3.0.0", + "gulp": "^3.9.1", + "gulp-concat": "^2.6.1", + "gulp-connect": "^5.6.1", + "gulp-copy": "^1.1.0", + "gulp-exec": "^3.0.2", + "gulp-sourcemaps": "^2.6.4", + "gulp-uglify": "^3.0.1", + "gulp-watch": "^5.0.1" + }, + "bugs": { + "url": "https://git.spacen.net/yunkong2/yunkong2.material/issues" + }, + "main": "www/index.html", + "scripts": { + "test": "node node_modules/gulp/bin/gulp.js", + "build": "node node_modules/gulp/bin/gulp.js", + "prepare": "node node_modules/gulp/bin/gulp.js" + }, + "license": "CC-BY-NC-4.0", + "dependencies": { + "react-beautiful-dnd": "^9.0.2" + } +} diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..8477d14 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,21 @@ +# See https://help.git.spacen.net/ignore-files/ for more about ignoring files. + +# dependencies +/node_modules + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/src/README.md b/src/README.md new file mode 100644 index 0000000..29e3f81 --- /dev/null +++ b/src/README.md @@ -0,0 +1,1901 @@ +This project was bootstrapped with [Create React App](https://git.spacen.net/facebookincubator/create-react-app). + +Below you will find some information on how to perform common tasks.
+You can find the most recent version of this guide [here](https://git.spacen.net/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). + +## Table of Contents + +- [Updating to New Releases](#updating-to-new-releases) +- [Sending Feedback](#sending-feedback) +- [Folder Structure](#folder-structure) +- [Available Scripts](#available-scripts) + - [npm start](#npm-start) + - [npm test](#npm-test) + - [npm run build](#npm-run-build) + - [npm run eject](#npm-run-eject) +- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) +- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) +- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) +- [Debugging in the Editor](#debugging-in-the-editor) +- [Changing the Page ``](#changing-the-page-title) +- [Installing a Dependency](#installing-a-dependency) +- [Importing a Component](#importing-a-component) +- [Code Splitting](#code-splitting) +- [Adding a Stylesheet](#adding-a-stylesheet) +- [Post-Processing CSS](#post-processing-css) +- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) +- [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) +- [Using the `public` Folder](#using-the-public-folder) + - [Changing the HTML](#changing-the-html) + - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + - [When to Use the `public` Folder](#when-to-use-the-public-folder) +- [Using Global Variables](#using-global-variables) +- [Adding Bootstrap](#adding-bootstrap) + - [Using a Custom Theme](#using-a-custom-theme) +- [Adding Flow](#adding-flow) +- [Adding Custom Environment Variables](#adding-custom-environment-variables) + - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) + - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) + - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) +- [Can I Use Decorators?](#can-i-use-decorators) +- [Integrating with an API Backend](#integrating-with-an-api-backend) + - [Node](#node) + - [Ruby on Rails](#ruby-on-rails) +- [Proxying API Requests in Development](#proxying-api-requests-in-development) + - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) + - [Configuring the Proxy Manually](#configuring-the-proxy-manually) +- [Using HTTPS in Development](#using-https-in-development) +- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) +- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) +- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) +- [Running Tests](#running-tests) + - [Filename Conventions](#filename-conventions) + - [Command Line Interface](#command-line-interface) + - [Version Control Integration](#version-control-integration) + - [Writing Tests](#writing-tests) + - [Testing Components](#testing-components) + - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) + - [Initializing Test Environment](#initializing-test-environment) + - [Focusing and Excluding Tests](#focusing-and-excluding-tests) + - [Coverage Reporting](#coverage-reporting) + - [Continuous Integration](#continuous-integration) + - [Disabling jsdom](#disabling-jsdom) + - [Snapshot Testing](#snapshot-testing) + - [Editor Integration](#editor-integration) +- [Making a Progressive Web App](#making-a-progressive-web-app) + - [Offline-First Considerations](#offline-first-considerations) + - [Progressive Web App Metadata](#progressive-web-app-metadata) +- [Deployment](#deployment) + - [Static Server](#static-server) + - [Other Solutions](#other-solutions) + - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) + - [Building for Relative Paths](#building-for-relative-paths) + - [Azure](#azure) + - [Firebase](#firebase) + - [GitHub Pages](#github-pages) + - [Heroku](#heroku) + - [Modulus](#modulus) + - [Netlify](#netlify) + - [Now](#now) + - [S3 and CloudFront](#s3-and-cloudfront) + - [Surge](#surge) +- [Advanced Configuration](#advanced-configuration) +- [Troubleshooting](#troubleshooting) + - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) + - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) + - [`npm run build` silently fails](#npm-run-build-silently-fails) + - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) + - [Moment.js locales are missing](#momentjs-locales-are-missing) +- [Something Missing?](#something-missing) + +## Updating to New Releases + +Create React App is divided into two packages: + +* `create-react-app` is a global command-line utility that you use to create new projects. +* `react-scripts` is a development dependency in the generated projects (including this one). + +You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. + +When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. + +To update an existing project to a new version of `react-scripts`, [open the changelog](https://git.spacen.net/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. + +In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://git.spacen.net/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. + +We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. + +## Sending Feedback + +We are always open to [your feedback](https://git.spacen.net/facebookincubator/create-react-app/issues). + +## Folder Structure + +After creation, your project should look like this: + +``` +my-app/ + README.md + node_modules/ + package.json + public/ + index.html + favicon.ico + src/ + App.css + App.js + App.test.js + index.css + index.js + logo.svg +``` + +For the project to build, **these files must exist with exact filenames**: + +* `public/index.html` is the page template; +* `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> +You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. + +Only files inside `public` can be used from `public/index.html`.<br> +Read instructions below for using assets from JavaScript and HTML. + +You can, however, create more top-level directories.<br> +They will not be included in the production build so you can use them for things like documentation. + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.<br> +See the section about [running tests](#running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.<br> +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.<br> +Your app is ready to be deployed! + +See the section about [deployment](#deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Supported Language Features and Polyfills + +This project supports a superset of the latest JavaScript standard.<br> +In addition to [ES6](https://git.spacen.net/lukehoban/es6features) syntax features, it also supports: + +* [Exponentiation Operator](https://git.spacen.net/rwaldron/exponentiation-operator) (ES2016). +* [Async/await](https://git.spacen.net/tc39/ecmascript-asyncawait) (ES2017). +* [Object Rest/Spread Properties](https://git.spacen.net/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). +* [Dynamic import()](https://git.spacen.net/tc39/proposal-dynamic-import) (stage 3 proposal) +* [Class Fields and Static Properties](https://git.spacen.net/tc39/proposal-class-public-fields) (stage 2 proposal). +* [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. + +Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). + +While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. + +Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: + +* [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://git.spacen.net/sindresorhus/object-assign). +* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://git.spacen.net/then/promise). +* [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://git.spacen.net/github/fetch). + +If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. + +## Syntax Highlighting in the Editor + +To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. + +## Displaying Lint Output in the Editor + +>Note: this feature is available with `react-scripts@0.2.0` and higher.<br> +>It also only works with npm 3 or higher. + +Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. + +They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. + +You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: + +```js +{ + "extends": "react-app" +} +``` + +Now your editor should report the linting warnings. + +Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. + +If you want to enforce a coding style for your project, consider using [Prettier](https://git.spacen.net/jlongster/prettier) instead of ESLint style rules. + +## Debugging in the Editor + +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** + +Visual Studio Code supports debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. + +You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. + +Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. + +```json +{ + "version": "0.2.0", + "configurations": [{ + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceRoot}/src", + "userDataDir": "${workspaceRoot}/.vscode/chrome", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + }] +} +``` + +Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://git.spacen.net/nfl/react-helmet), a third party library. + +If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). + +## Installing a Dependency + +The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: + +``` +npm install --save <library-name> +``` + +## Importing a Component + +This project setup supports ES6 modules thanks to Babel.<br> +While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. + +For example: + +### `Button.js` + +```js +import React, { Component } from 'react'; + +class Button extends Component { + render() { + // ... + } +} + +export default Button; // Don’t forget to use export default! +``` + +### `DangerButton.js` + + +```js +import React, { Component } from 'react'; +import Button from './Button'; // Import a component from another file + +class DangerButton extends Component { + render() { + return <Button color="red" />; + } +} + +export default DangerButton; +``` + +Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. + +We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. + +Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. + +Learn more about ES6 modules: + +* [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) +* [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) +* [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) + +## Code Splitting + +Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. + +This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://git.spacen.net/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. + +Here is an example: + +### `moduleA.js` + +```js +const moduleA = 'Hello'; + +export { moduleA }; +``` +### `App.js` + +```js +import React, { Component } from 'react'; + +class App extends Component { + handleClick = () => { + import('./moduleA') + .then(({ moduleA }) => { + // Use moduleA + }) + .catch(err => { + // Handle failure + }); + }; + + render() { + return ( + <div> + <button onClick={this.handleClick}>Load</button> + </div> + ); + } +} + +export default App; +``` + +This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. + +You can also use it with `async` / `await` syntax if you prefer it. + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `Button.css` + +```css +.Button { + padding: 20px; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import './Button.css'; // Tell Webpack that Button.js uses these styles + +class Button extends Component { + render() { + // You can use them as regular CSS styles + return <div className="Button" />; + } +} +``` + +**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://git.spacen.net/postcss/autoprefixer) so you don’t need to worry about it. + +For example, this: + +```css +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +becomes this: + +```css +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +If you need to disable autoprefixing for some reason, [follow this section](https://git.spacen.net/postcss/autoprefixer#disabling). + +## Adding a CSS Preprocessor (Sass, Less etc.) + +Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). + +Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. + +First, let’s install the command-line interface for Sass: + +``` +npm install node-sass-chokidar --save-dev +``` +Then in `package.json`, add the following lines to `scripts`: + +```diff + "scripts": { ++ "build-css": "node-sass-chokidar src/ -o src/", ++ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", +``` + +>Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. + +Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. + +To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. + +``` +"build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", +"watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", +``` + +This will allow you to do imports like + +```scss +@import 'styles/_colors.scss'; // assuming a styles directory under src/ +@import 'nprogress/nprogress'; // importing a css file from the nprogress node module +``` + +At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. + +As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: + +``` +npm install --save-dev npm-run-all +``` + +Then we can change `start` and `build` scripts to include the CSS preprocessor commands: + +```diff + "scripts": { + "build-css": "node-sass-chokidar src/ -o src/", + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", +- "start": "react-scripts start", +- "build": "react-scripts build", ++ "start-js": "react-scripts start", ++ "start": "npm-run-all -p watch-css start-js", ++ "build": "npm run build-css && react-scripts build", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +``` + +Now running `npm start` and `npm run build` also builds Sass files. + +**Why `node-sass-chokidar`?** + +`node-sass` has been reported as having the following issues: + +- `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. + +- Infinite styles compiling [#1939](https://git.spacen.net/facebookincubator/create-react-app/issues/1939) + +- `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://git.spacen.net/sass/node-sass/issues/1891) + + `node-sass-chokidar` is used here as it addresses these issues. + +## Adding Images, Fonts, and Files + +With Webpack, using static assets like images and fonts works similarly to CSS. + +You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. + +To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://git.spacen.net/facebookincubator/create-react-app/issues/1153). + +Here is an example: + +```js +import React from 'react'; +import logo from './logo.png'; // Tell Webpack this JS file uses this image + +console.log(logo); // /logo.84287d09.png + +function Header() { + // Import result is the URL of your image + return <img src={logo} alt="Logo" />; +} + +export default Header; +``` + +This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. + +This works in CSS too: + +```css +.Logo { + background-image: url(./logo.png); +} +``` + +Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. + +Please be advised that this is also a custom feature of Webpack. + +**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> +An alternative way of handling static assets is described in the next section. + +## Using the `public` Folder + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). +This mechanism provides a number of benefits: + +* Scripts and stylesheets get minified and bundled together to avoid extra network requests. +* Missing files cause compilation errors instead of 404 errors for your users. +* Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. + +However there is an **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally we recommend using `import` for getting asset URLs + // as described in “Adding Images and Fonts” above this section. + return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; +} +``` + +Keep in mind the downsides of this approach: + +* None of the files in `public` folder get post-processed or minified. +* Missing files will not be called at compilation time, and will cause 404 errors for your users. +* Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. +The `public` folder is useful as a workaround for a number of less common cases: + +* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +* You have thousands of images and need to dynamically reference their paths. +* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using Global Variables + +When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. + +You can avoid this by reading the global variable explicitly from the `window` object, for example: + +```js +const $ = window.$; +``` + +This makes it obvious you are using a global variable intentionally rather than because of a typo. + +Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. + +## Adding Bootstrap + +You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: + +Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: + +``` +npm install react-bootstrap --save +npm install bootstrap@3 --save +``` + +Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: + +```js +import 'bootstrap/dist/css/bootstrap.css'; +import 'bootstrap/dist/css/bootstrap-theme.css'; +// Put any other imports below so that CSS from your +// components takes precedence over default styles. +``` + +Import required React Bootstrap components within ```src/App.js``` file or your custom component files: + +```js +import { Navbar, Jumbotron, Button } from 'react-bootstrap'; +``` + +Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. + +### Using a Custom Theme + +Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> +We suggest the following approach: + +* Create a new package that depends on the package you wish to customize, e.g. Bootstrap. +* Add the necessary build steps to tweak the theme, and publish your package on npm. +* Install your own theme npm package as a dependency of your app. + +Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. + +## Adding Flow + +Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. + +Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. + +To add Flow to a Create React App project, follow these steps: + +1. Run `npm install --save-dev flow-bin` (or `yarn add --dev flow-bin`). +2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. +3. Run `npm run flow -- init` (or `yarn flow -- init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. +4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). + +Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. +You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. +In the future we plan to integrate it into Create React App even more closely. + +To learn more about Flow, check out [its documentation](https://flowtype.org/). + +## Adding Custom Environment Variables + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +Your project can consume variables declared in your environment as if they were declared locally in your JS files. By +default you will have `NODE_ENV` defined for you, and any other environment variables starting with +`REACT_APP_`. + +**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. + +>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://git.spacen.net/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +These environment variables will be defined for you on `process.env`. For example, having an environment +variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. + +There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. + +These environment variables can be useful for displaying information conditionally based on where the project is +deployed or consuming sensitive data that lives outside of version control. + +First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined +in the environment inside a `<form>`: + +```jsx +render() { + return ( + <div> + <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> + <form> + <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> + </form> + </div> + ); +} +``` + +During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. + +When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: + +```html +<div> + <small>You are running this application in <b>development</b> mode.</small> + <form> + <input type="hidden" value="abcdef" /> + </form> +</div> +``` + +The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this +value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in +a `.env` file. Both of these ways are described in the next few sections. + +Having access to the `NODE_ENV` is also useful for performing actions conditionally: + +```js +if (process.env.NODE_ENV !== 'production') { + analytics.disable(); +} +``` + +When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. + +### Referencing Environment Variables in the HTML + +>Note: this feature is available with `react-scripts@0.9.0` and higher. + +You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: + +```html +<title>%REACT_APP_WEBSITE_NAME% +``` + +Note that the caveats from the above section apply: + +* Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. +* The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). + +### Adding Temporary Environment Variables In Your Shell + +Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the +life of the shell session. + +#### Windows (cmd.exe) + +```cmd +set REACT_APP_SECRET_CODE=abcdef&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Linux, macOS (Bash) + +```bash +REACT_APP_SECRET_CODE=abcdef npm start +``` + +### Adding Development Environment Variables In `.env` + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +To define permanent environment variables, create a file called `.env` in the root of your project: + +``` +REACT_APP_SECRET_CODE=abcdef +``` + +`.env` files **should be** checked into source control (with the exclusion of `.env*.local`). + +#### What other `.env` files are can be used? + +>Note: this feature is **available with `react-scripts@1.0.0` and higher**. + +* `.env`: Default. +* `.env.local`: Local overrides. **This file is loaded for all environments except test.** +* `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. +* `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. + +Files on the left have more priority than files on the right: + +* `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` +* `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` +* `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) + +These variables will act as the defaults if the machine does not explicitly set them.
+Please refer to the [dotenv documentation](https://git.spacen.net/motdotla/dotenv) for more details. + +>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need +these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). + +## Can I Use Decorators? + +Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
+Create React App doesn’t support decorator syntax at the moment because: + +* It is an experimental proposal and is subject to change. +* The current specification version is not officially supported by Babel. +* If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. + +However in many cases you can rewrite decorator-based code without decorators just as fine.
+Please refer to these two threads for reference: + +* [#214](https://git.spacen.net/facebookincubator/create-react-app/issues/214) +* [#411](https://git.spacen.net/facebookincubator/create-react-app/issues/411) + +Create React App will add decorator support when the specification advances to a stable stage. + +## Integrating with an API Backend + +These tutorials will help you to integrate your app with an API backend running on another port, +using `fetch()` to access it. + +### Node +Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). +You can find the companion GitHub repository [here](https://git.spacen.net/fullstackreact/food-lookup-demo). + +### Ruby on Rails + +Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). +You can find the companion GitHub repository [here](https://git.spacen.net/fullstackreact/food-lookup-demo-rails). + +## Proxying API Requests in Development + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +People often serve the front-end React app from the same host and port as their backend implementation.
+For example, a production setup might look like this after the app is deployed: + +``` +/ - static server returns index.html with React app +/todos - static server returns index.html with React app +/api/todos - server handles any /api/* requests using the backend implementation +``` + +Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. + +To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: + +```js + "proxy": "http://localhost:4000", +``` + +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. + +Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: + +``` +Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. +``` + +Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. + +The `proxy` option supports HTTP, HTTPS and WebSocket connections.
+If the `proxy` option is **not** flexible enough for you, alternatively you can: + +* [Configure the proxy yourself](#configuring-the-proxy-manually) +* Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). +* Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. + +### "Invalid Host Header" Errors After Configuring Proxy + +When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://git.spacen.net/webpack/webpack-dev-server/issues/887). + +This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://git.spacen.net/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: + +>Invalid Host header + +To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: + +``` +HOST=mypublicdevhost.com +``` + +If you restart the development server now and load the app from the specified host, it should work. + +If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** + +``` +# NOTE: THIS IS DANGEROUS! +# It exposes your machine to attacks from the websites you visit. +DANGEROUSLY_DISABLE_HOST_CHECK=true +``` + +We don’t recommend this approach. + +### Configuring the Proxy Manually + +>Note: this feature is available with `react-scripts@1.0.0` and higher. + +If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
+You may also specify any configuration value [`http-proxy-middleware`](https://git.spacen.net/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://git.spacen.net/nodejitsu/node-http-proxy#options) supports. +```js +{ + // ... + "proxy": { + "/api": { + "target": "", + "ws": true + // ... + } + } + // ... +} +``` + +All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. + +If you need to specify multiple proxies, you may do so by specifying additional entries. +You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. +```js +{ + // ... + "proxy": { + // Matches any request starting with /api + "/api": { + "target": "", + "ws": true + // ... + }, + // Matches any request starting with /foo + "/foo": { + "target": "", + "ssl": true, + "pathRewrite": { + "^/foo": "/foo/beta" + } + // ... + }, + // Matches /bar/abc.html but not /bar/sub/def.html + "/bar/*.html": { + "target": "", + // ... + }, + // Matches /bar/abc.html and /bar/sub/def.html + "/baz/**/*.html": { + "target": "" + // ... + } + } + // ... +} +``` + +## Using HTTPS in Development + +>Note: this feature is available with `react-scripts@0.4.0` and higher. + +You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. + +To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: + +#### Windows (cmd.exe) + +```cmd +set HTTPS=true&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Linux, macOS (Bash) + +```bash +HTTPS=true npm start +``` + +Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. + +## Generating Dynamic `` Tags on the Server + +Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: + +```html + + + + + +``` + +Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! + +If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. + +## Pre-Rendering into Static HTML Files + +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. + +There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. + +The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. + +You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). + +## Injecting Data from the Server into the Page + +Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: + +```js + + + + +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +>Note: this feature is available with `react-scripts@0.3.0` and higher.
+>[Read the migration guide to learn how to enable it in older projects!](https://git.spacen.net/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://git.spacen.net/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +* Files with `.js` suffix in `__tests__` folders. +* Files with `.test.js` suffix. +* Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: + +```sh +npm install --save-dev enzyme react-test-renderer +``` + +```js +import React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `); + } else { + return ( this.onUpdateVersion()}>{VERSION}); + } + } + + logout() { + if (this.isCloud) { + window.location.href = '/logout'; + } else { + this.conn.logout(() => window.location.reload()); + } + } + + getEditButton(useBright) { + if (!this.state.connected) return null; + + let style; + if (this.state.editMode) { + style = {color: Theme.palette.editActive}; + } else if (this.state.actualVersion && (this.state.actualVersion !== VERSION || (this.urlVersion && this.state.actualVersion !== this.urlVersion))) { + style = {color: Theme.palette.updateAvailable}; + } else { + style = {color: useBright ? Theme.palette.textColorBright : Theme.palette.textColorDark}; + } + + return ( + + + + ); + } + + onMenuClose() { + this.setState({open: false}); + } + + getMenu(useBright) { + return ( this.onMenuClose()} + classes={{paper: this.props.classes.menuBackground}} + style={{ + width: Theme.menu.width, + background: (this.state.appSettings && this.state.appSettings.menuBackground) || 'white' + }}> + + + + + + {this.state.connected && this.state.editMode ? () : null} + +
+ + {this.state.width > 500 && !this.state.menuFixed ? + ( + + ) + : null + } + + + ); + } + + getButtonFullScreen(useBright) { + if (App.isFullScreenSupported() && !this.initialFullScreenMode) { + return ( + + {this.state.fullScreen ? + : + + } + ); + } else { + return null; + } + } + + getButtonSpeech(useBright) { + if (!this.state.editMode && this.state.connected && this.state.appSettings && + (this.state.appSettings.text2command || this.state.appSettings.text2command === 0) && + SpeechDialog.isSpeechRecognitionSupported()) { + return ( + this.onSpeech(true)}> + + ); + } else { + return null; + } + } + + getButtonEditSettings(useBright) { + if (this.state.connected && this.state.editMode) { + return ( + + + ); + } else { + return null; + } + } + + getButtonSync(useBright) { + if (this.state.connected && this.state.editMode && (!this.state.appSettings || !this.state.appSettings.noCache)) { + return ( + + + ); + } else { + return null; + } + } + + getButtonLogout(useBright) { + if (this.isCloud || this.auth) { + return ( + + + ); + } else { + return null; + } + } + + getButtonSignal(useBright) { + if (this.state.connected) return null; + return ( + + + + ); + } + + getAppBar() { + const toolbarBackground = this.state.settings ? this.state.settings.color : undefined; + const useBright = !toolbarBackground || Utils.isUseBright(toolbarBackground); + + return ( + + {!this.state.menuFixed && + ( + + )} + {Utils.getIcon(this.state.settings, Theme.appBarIcon)} +

+ {this.getTitle()} +

+
+ {this.getVersionControl(useBright)} + {this.getButtonSignal(useBright)} + {this.getButtonEditSettings(useBright)} + {this.getButtonSync(useBright)} + {this.getEditButton(useBright)} + {this.getButtonSpeech(useBright)} + {this.getButtonLogout(useBright)} + {this.getButtonFullScreen(useBright)} +
+ {this.state.editEnumSettings ? (): null} + {this.state.editAppSettings ? (): null} +
+
); + } + + getStateList() { + return ( + ); + } + + getErrorDialog() { + return ( this.setState({errorShow: false})} + open={this.state.errorShow} + > + {I18n.t('Error')} + + + {this.state.errorText} + + + + + + ); + } + + getSpeechDialog() { + if (this.state.appSettings && (this.state.appSettings.text2command || this.state.appSettings.text2command === 0)) { + return (SpeechDialog.isSpeechRecognitionSupported() ? + this.onSpeech(false)} + /> : null); + } else { + return null; + } + } + + getLoadingScreen() { + const background = window.materialBackground; + const useBright = background && Utils.isUseBright(background); + + return ( +
+ +
+ ); + } + + render() { + if (this.state.loading) { + return this.getLoadingScreen(); + } else { + const useBright = this.state.appSettings && this.state.appSettings.menuBackground && Utils.isUseBright(this.state.appSettings.menuBackground); + return ( +
+ {this.getAppBar(useBright)} + {this.getMenu(useBright)} + {this.getStateList(useBright)} + {this.getErrorDialog(useBright)} + {this.getSpeechDialog(useBright)} +
+ ); + } + } +} + +export default withStyles(styles)(App); diff --git a/src/src/App.test.js b/src/src/App.test.js new file mode 100644 index 0000000..b84af98 --- /dev/null +++ b/src/src/App.test.js @@ -0,0 +1,8 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); diff --git a/src/src/Connection.js b/src/src/Connection.js new file mode 100644 index 0000000..4998ace --- /dev/null +++ b/src/src/Connection.js @@ -0,0 +1,1523 @@ +/** + * Copyright 2018 bluefox + * + * The MIT License (MIT) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + **/ + +////// ----------------------- Connection "class" ---------------------- //////////// +/* jshint browser: true */ +/* global document */ +/* global console */ +/* global window */ +/* global location */ +/* global setTimeout */ +/* global clearTimeout */ +/* jshint -W097 */ +/* jshint strict: true */ + +// The idea of servConn is to use this class later in every addon. +// The addon just must say, what must be loaded (values, objects, indexes) and +// the class loads it for addon. Authentication will be done automatically, so addon does not care about it. +// It will be .js file with localData and servConn + +class ServerConnection { + // Expected options: { + // namespace: //default 'vis.0' + // connOptions: { + // connLink: 'http://blabla:5000' // default + // socketForceWebSockets: false + // socketSession: '' + // } + // connCallbacks: { + // onConnChange: null, + // onUpdate: null, + // onRefresh: null, + // onAuth: null, + // onCommand: null, + // onError: null + // }, + // objectsRequired: false + // autoSubscribe: true + + constructor(options) { + if (typeof options === 'string') { + options = {namespace: options}; + } + options = options || {}; + + this._socket = null; + this._isConnected = false; + this._disconnectedSince = null; + this._connCallbacks = { + onConnChange: null, + onUpdate: null, + onRefresh: null, + onAuth: null, + onCommand: null, + onError: null + }; + this._authInfo = null; + this._isAuthDone = false; + this._isAuthRequired = false; + this._authRunning = false; + this._cmdQueue = []; + this._type = options.type || 'socket.io'; // [socket.io | local] + this._timeout = options.timeout || 0; // 0 - use transport default timeout to detect disconnect + this._reconnectInterval = options.reconnectInterval || 10000; // reconnect interval + this._reloadInterval = options.reloadInterval || 30; // if connection was absent longer than 30 seconds + this._cmdData = null; + this._cmdInstance = null; + this._isSecure = false; + this._defaultMode = options.defaultMode || 0x644; + this._useStorage = options.useStorage || false; + this._objects = null; // used if _useStorage === true + this._enums = null; // used if _useStorage === true + this._autoSubscribe = options.autoSubscribe === undefined ? true : options.autoSubscribe; + + this.namespace = options.namespace || 'vis.0'; + this.$ = (typeof window.$ !== 'undefined') ? window.$ : null; + this.storage = (typeof window.storage !== 'undefined') ? window.storage : null; + + this._init(options.connOptions, options.connCallbacks, options.objectsRequired, options.autoSubscribe); + } + + getType() { + return this._type; + } + + getIsConnected() { + return this._isConnected; + } + + getIsLoginRequired() { + return this._isSecure; + } + + getUser() { + return this._user; + } + + setReloadTimeout(timeout) { + this._reloadInterval = parseInt(timeout, 10); + } + + setReconnectInterval(interval) { + this._reconnectInterval = parseInt(interval, 10); + } + + _checkConnection(func, _arguments) { + if (!this._isConnected) { + console.log('No connection!'); + return false; + } + + if (this._queueCmdIfRequired(func, _arguments)) { + return false; + } + + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return false; + } + return true; + } + + _monitor() { + if (this._timer) { + return; + } + const ts = Date.now(); + if (this._reloadInterval && ts - this._lastTimer > this._reloadInterval * 1000) { + // It seems, that PC was in a sleep => Reload page to request authentication anew + this.reload(); + } else { + this._lastTimer = ts; + } + this._timer = setTimeout(() => { + this._timer = null; + this._monitor(); + }, 10000); + } + + _onAuth(objectsRequired, isSecure) { + this._isSecure = isSecure; + + if (this._isSecure) { + this._lastTimer = Date.now(); + this._monitor(); + } + + this._autoSubscribe && this._socket.emit('subscribe', '*'); + objectsRequired && this._socket.emit('subscribeObjects', '*'); + + if (this._isConnected === true) { + // This seems to be a reconnect because we're already connected! + // -> prevent firing onConnChange twice + return; + } + + this._isConnected = true; + + if (this._connCallbacks.onConnChange) { + setTimeout(() => + this._socket.emit('authEnabled', (auth, user) => { + this._user = user; + this._connCallbacks.onConnChange(this._isConnected); + if (typeof window.app !== 'undefined') { + window.app.onConnChange(this._isConnected); + } + }), 0); + } + } + + reconnect(connOptions) { + // reconnect + if ((!connOptions.mayReconnect || connOptions.mayReconnect()) && !this._connectInterval) { + this._connectInterval = setInterval(() => { + console.log('Trying connect...'); + this._socket.connect(); + this._countDown = Math.floor(this._reconnectInterval / 1000); + + // Custom load indicator + this.$ && this.$('.splash-screen-text').html(this._countDown + '...').css('color', 'red'); + }, this._reconnectInterval); + + this._countDown = Math.floor(this._reconnectInterval / 1000); + + // Custom load indicator + if (this.$) { + this.$('.splash-screen-text').html(this._countDown + '...'); + + // Custom load indicator + this._countInterval = setInterval(() => { + this._countDown--; + this.$('.splash-screen-text').html(this._countDown + '...'); + }, 1000); + } + } + } + + reload() { + if (window.location.host === 'yunkong2.pro' || + window.location.host === 'yunkong2.net' || + window.location.host === 'yunkong2.biz') { + window.location = '/'; + } else { + window.location.reload(); + } + } + + _init(connOptions, connCallbacks, objectsRequired, autoSubscribe) { + // init namespace + if (typeof window.socketNamespace !== 'undefined') { + this.namespace = window.socketNamespace; + } + + connOptions = connOptions || {}; + connOptions.name = connOptions.name || this.namespace; + + if (autoSubscribe !== undefined) { + this._autoSubscribe = autoSubscribe; + } + + // To start vis as local use one of: + // - start vis from directory with name local, e.g. c:/blbla/local/yunkong2.vis/www/index.html + // - do not create "_socket/info.js" file in "www" directory + // - create "_socket/info.js" file with + // const socketUrl = "local"; const socketSession = ""; sysLang="en"; + // in this case you can overwrite browser language settings + if (window.document.URL.split('/local/')[1] || + (typeof window.socketUrl === 'undefined' && !connOptions.connLink) || + (typeof window.socketUrl !== 'undefined' && window.socketUrl === 'local')) { + this._type = 'local'; + } + + if (typeof window.session !== 'undefined') { + const user = window.session.get('user'); + if (user) { + this._authInfo = { + user: user, + hash: window.session.get('hash'), + salt: window.session.get('salt') + }; + } + } + + this._connCallbacks = connCallbacks; + + let connLink = connOptions.connLink || window.localStorage.getItem('connLink'); + + // Connection data from "/_socket/info.js" + if (!connLink && typeof window.socketUrl !== 'undefined') { + connLink = window.socketUrl; + } + if (!connOptions.socketSession && typeof window.socketSession !== 'undefined') { + connOptions.socketSession = window.socketSession; + } + if (connOptions.socketForceWebSockets === undefined && typeof socketForceWebSockets !== 'undefined') { + connOptions.socketForceWebSockets = window.socketForceWebSockets; + } + + // if no remote data + if (this._type === 'local') { + // report connected state + this._isConnected = true; + if (this._connCallbacks.onConnChange) { + this._connCallbacks.onConnChange(this._isConnected); + } + if (typeof window.app !== 'undefined') { + window.app.onConnChange(this._isConnected); + } + } else if (typeof window.io !== 'undefined') { + connOptions.socketSession = connOptions.socketSession || 'nokey'; + + let url; + if (connLink) { + url = connLink; + /*if (typeof connLink !== 'undefined' && connLink[0] === ':') { + connLink = window.location.protocol + '//' + window.location.hostname + connLink; + }*/ + } else { + url = window.location.protocol + '//' + window.location.host; + } + + if (this._socket) { + try { + this._socket.close(); + this._socket = null; + } catch (e) { + console.log('Cannot close connection: ' + e); + } + } + this._socket = window.io.connect(url, { + query: 'key=' + connOptions.socketSession, + 'reconnection limit': 10000, + 'max reconnection attempts': Infinity, + reconnection: false, + upgrade: !connOptions.socketForceWebSockets, + rememberUpgrade: connOptions.socketForceWebSockets, + transports: connOptions.socketForceWebSockets ? ['websocket'] : undefined + }); + + this._socket.on('connect', () => { + if (this._disconnectedSince) { + const offlineTime = Date.now() - this._disconnectedSince; + console.log('was offline for ' + (offlineTime / 1000) + 's'); + + // reload whole page if no connection longer than some period + if (this._reloadInterval && offlineTime > this._reloadInterval * 1000 && !this.authError) { + this.reload(); + } + + this._disconnectedSince = null; + } + + if (this._connectInterval) { + clearInterval(this._connectInterval); + this._connectInterval = null; + } + if (this._countInterval) { + clearInterval(this._countInterval); + this._countInterval = null; + } + + // trim custom load-indicator + const elem = document.getElementById('server-disconnect'); + if (elem) { + elem.style.display = 'none'; + } + + this._socket.emit('name', connOptions.name); + console.log(new Date().toISOString() + ' Connected => authenticate'); + setTimeout(() => { + this.waitConnect = setTimeout(() => { + console.error('No answer from server'); + !this.authError && this.reload(); + }, 6000); + + this._socket.emit('authenticate', (isOk, isSecure) => { + if (this.waitConnect) { + clearTimeout(this.waitConnect); + this.waitConnect = null; + } + + console.log(new Date().toISOString() + ' Authenticated: ' + isOk); + if (isOk) { + this._onAuth(objectsRequired, isSecure); + } else { + console.log('permissionError'); + } + }); + }, 50); + }); + + this._socket.on('reauthenticate', err => { + if (this._connCallbacks.onConnChange) { + this._connCallbacks.onConnChange(false); + if (typeof window.app !== 'undefined' && !this.authError) { + window.app.onConnChange(false); + } + } + console.warn('reauthenticate'); + if (this.waitConnect) { + clearTimeout(this.waitConnect); + this.waitConnect = null; + } + + if (connCallbacks.onAuthError) { + if (!this.authError) { + this.authError = true; + connCallbacks.onAuthError(err); + } + } else { + this.reload(); + } + }); + + this._socket.on('connect_error', () => { + // Custom load indicator + this.$ && this.$('.splash-screen-text').css('color', '#002951'); + + this.reconnect(connOptions); + }); + + this._socket.on('disconnect', () => { + this._disconnectedSince = Date.now(); + + // called only once when connection lost (and it was here before) + this._isConnected = false; + if (this._connCallbacks.onConnChange) { + setTimeout(() => { + // Custom load indicator + const elem = document.getElementById('server-disconnect'); + if (elem) { + elem.style.display = ''; + } + this._connCallbacks.onConnChange(this._isConnected); + + if (typeof window.app !== 'undefined') { + window.app.onConnChange(this._isConnected); + } + }, 5000); + } else { + // Custom load indicator + const elem = document.getElementById('server-disconnect'); + if (elem) { + elem.style.display = ''; + } + } + + // reconnect + this.reconnect(connOptions); + }); + + // after reconnect the "connect" event will be called + this._socket.on('reconnect', () => { + const offlineTime = Date.now() - this._disconnectedSince; + console.log('was offline for ' + (offlineTime / 1000) + 's'); + + // reload whole page if no connection longer than one minute + if (this._reloadInterval && offlineTime > this._reloadInterval * 1000) { + this.reload(); + } + // anyway "on connect" is called + }); + + this._socket.on('objectChange', (id, obj) => { + // If cache used + if (this._useStorage && this.storage) { + const objects = this._objects || this.storage.get('objects'); + if (objects) { + if (obj) { + objects[id] = obj; + } else { + if (objects[id]) delete objects[id]; + } + this.storage.set('objects', objects); + } + } + + this._connCallbacks.onObjectChange && this._connCallbacks.onObjectChange(id, obj); + }); + + this._socket.on('stateChange', (id, state) => { + if (!id || state === null || typeof state !== 'object') return; + + if (this._connCallbacks.onCommand && id === this.namespace + '.control.command') { + if (state.ack) return; + + if (state.val && + typeof state.val === 'string' && + state.val[0] === '{' && + state.val[state.val.length - 1] === '}') { + try { + state.val = JSON.parse(state.val); + } catch (e) { + console.log('Command seems to be an object, but cannot parse it: ' + state.val); + } + } + + // if command is an object {instance: 'iii', command: 'cmd', data: 'ddd'} + if (state.val && state.val.instance) { + if (this._connCallbacks.onCommand(state.val.instance, state.val.command, state.val.data)) { + // clear state + this.setState(id, {val: '', ack: true}); + } + } else { + if (this._connCallbacks.onCommand(this._cmdInstance, state.val, this._cmdData)) { + // clear state + this.setState(id, {val: '', ack: true}); + } + } + } else if (id === this.namespace + '.control.data') { + this._cmdData = state.val; + } else if (id === this.namespace + '.control.instance') { + this._cmdInstance = state.val; + } else if (this._connCallbacks.onUpdate) { + this._connCallbacks.onUpdate(id, state); + } + }); + + this._socket.on('permissionError', err => { + if (this._connCallbacks.onError) { + /* { + command: + type: + operation: + arg: + }*/ + this._connCallbacks.onError(err); + } else { + console.log('permissionError'); + } + }); + + this._socket.on('error', err => { + if (err === 'Invalid password or user name') { + console.warn('reauthenticate'); + if (this.waitConnect) { + clearTimeout(this.waitConnect); + this.waitConnect = null; + } + + if (connCallbacks.onAuthError) { + if (!this.authError) { + this.authError = true; + connCallbacks.onAuthError(err); + } + } else { + this.reload(); + } + } else { + console.error('Socket error: ' + err); + // Custom load indicator + this.$ && this.$('.splash-screen-text').css('color', '#002951'); + + this.reconnect(connOptions); + } + }); + } + } + + logout(callback) { + if (!this._isConnected) { + console.log('No connection!'); + return; + } + + this._socket.emit('logout', callback); + } + + getVersion(callback) { + if (!this._checkConnection('getVersion', arguments)) return; + + this._socket.emit('getVersion', version => callback && callback(version)); + } + + subscribe(idOrArray, callback) { + if (!this._checkConnection('subscribe', arguments)) return; + + this._socket.emit('subscribe', idOrArray, callback); + } + + unsubscribe(idOrArray, callback) { + if (!this._checkConnection('unsubscribe', arguments)) return; + + this._socket.emit('unsubscribe', idOrArray, callback); + } + + _checkAuth(callback) { + if (!this._isConnected) { + console.log('No connection!'); + return; + } + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + this._socket.emit('getVersion', version => callback && callback(version)); + } + + readFile(filename, callback, isRemote) { + if (!callback) { + throw new Error('No callback set'); + } + + if (this._type === 'local' && this.storage) { + try { + const data = this.storage.get(filename); + callback(null, data ? JSON.parse(data) : null); + } catch (err) { + callback(err, null); + } + } else { + if (!this._checkConnection('readFile', arguments)) { + return; + } + + if (!isRemote && typeof window.app !== 'undefined') { + window.app.readLocalFile(filename.replace(/^\/vis\.0\//, ''), callback); + } else { + let adapter = this.namespace; + if (filename[0] === '/') { + const p = filename.split('/'); + adapter = p[1]; + p.splice(0, 2); + filename = p.join('/'); + } + + this._socket.emit('readFile', adapter, filename, (err, data, mimeType) => + setTimeout(() => callback(err, data, filename, mimeType), 0)); + } + } + } + + getMimeType(ext) { + if (ext.indexOf('.') !== -1) ext = ext.toLowerCase().match(/\.[^.]+$/); + let _mimeType; + if (ext === '.css') { + _mimeType = 'text/css'; + } else if (ext === '.bmp') { + _mimeType = 'image/bmp'; + } else if (ext === '.png') { + _mimeType = 'image/png'; + } else if (ext === '.jpg') { + _mimeType = 'image/jpeg'; + } else if (ext === '.jpeg') { + _mimeType = 'image/jpeg'; + } else if (ext === '.gif') { + _mimeType = 'image/gif'; + } else if (ext === '.tif') { + _mimeType = 'image/tiff'; + } else if (ext === '.js') { + _mimeType = 'application/javascript'; + } else if (ext === '.html') { + _mimeType = 'text/html'; + } else if (ext === '.htm') { + _mimeType = 'text/html'; + } else if (ext === '.json') { + _mimeType = 'application/json'; + } else if (ext === '.xml') { + _mimeType = 'text/xml'; + } else if (ext === '.svg') { + _mimeType = 'image/svg+xml'; + } else if (ext === '.eot') { + _mimeType = 'application/vnd.ms-fontobject'; + } else if (ext === '.ttf') { + _mimeType = 'application/font-sfnt'; + } else if (ext === '.woff') { + _mimeType = 'application/font-woff'; + } else if (ext === '.wav') { + _mimeType = 'audio/wav'; + } else if (ext === '.mp3') { + _mimeType = 'audio/mpeg3'; + } else { + _mimeType = 'text/javascript'; + } + return _mimeType; + } + + readFile64(filename, callback, isRemote) { + if (!callback) { + throw new Error('No callback set'); + } + + if (!this._checkConnection('readFile', arguments)) return; + + if (!isRemote && typeof window.app !== 'undefined') { + window.app.readLocalFile(filename.replace(/^\/vis\.0\//, ''), (err, data, mimeType) => + setTimeout(() => { + if (data) { + callback(err, {mime: mimeType || this.getMimeType(filename), data: btoa(data)}, filename); + } else { + callback(err, filename); + } + }, 0)); + } else { + let adapter = this.namespace; + if (filename[0] === '/') { + const p = filename.split('/'); + adapter = p[1]; + p.splice(0, 2); + filename = p.join('/'); + } + + this._socket.emit('readFile64', adapter, filename, (err, data, mimeType) => + setTimeout(() => { + if (data) { + callback(err, {mime: mimeType || this.getMimeType(filename), data: data}, filename); + } else { + callback(err, {mime: mimeType || this.getMimeType(filename)}, filename); + } + }, 0)); + } + } + + writeFile(filename, data, mode, callback) { + if (typeof mode === 'function') { + callback = mode; + mode = null; + } + if (this._type === 'local') { + this.storage.set(filename, JSON.stringify(data)); + if (callback) callback(); + } else { + if (!this._checkConnection('writeFile', arguments)) return; + + if (typeof data === 'object') data = JSON.stringify(data, null, 2); + + const parts = filename.split('/'); + const adapter = parts[1]; + parts.splice(0, 2); + if (adapter === 'vis') { + this._socket.emit('writeFile', adapter, parts.join('/'), data, mode ? {mode: this._defaultMode} : {}, callback); + } else { + this._socket.emit('writeFile', this.namespace, filename, data, mode ? {mode: this._defaultMode} : {}, callback); + } + } + } + + // Write file base 64 + writeFile64(filename, data, callback) { + if (!this._checkConnection('writeFile64', arguments)) return; + + const parts = filename.split('/'); + const adapter = parts[1]; + parts.splice(0, 2); + + this._socket.emit('writeFile', adapter, parts.join('/'), atob(data), {mode: this._defaultMode}, callback); + } + + readDir(dirname, callback) { + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + if (!dirname) dirname = '/'; + const parts = dirname.split('/'); + const adapter = parts[1]; + parts.splice(0, 2); + + this._socket.emit('readDir', adapter, parts.join('/'), {filter: true}, (err, data) => { + if (callback) callback(err, data); + }); + } + + mkdir(dirname, callback) { + const parts = dirname.split('/'); + const adapter = parts[1]; + parts.splice(0, 2); + + this._socket.emit('mkdir', adapter, parts.join('/'), err => callback && callback(err)); + } + + unlink(name, callback) { + const parts = name.split('/'); + const adapter = parts[1]; + parts.splice(0, 2); + + this._socket.emit('unlink', adapter, parts.join('/'), err => callback && callback(err)); + } + + renameFile(oldname, newname, callback) { + const parts1 = oldname.split('/'); + const adapter = parts1[1]; + parts1.splice(0, 2); + const parts2 = newname.split('/'); + parts2.splice(0, 2); + this._socket.emit('rename', adapter, parts1.join('/'), parts2.join('/'), err => callback && callback(err)); + } + + setState(pointId, value, callback) { + //socket.io + if (this._socket === null) { + //console.log('socket.io not initialized'); + return; + } + this._socket.emit('setState', pointId, value, callback); + } + + // callback(err, data) + getStates(IDs, callback) { + if (typeof IDs === 'function') { + callback = IDs; + IDs = null; + } + + if (this._type === 'local') { + return callback(null, []); + } else { + if (!this._checkConnection('getStates', arguments)) return; + + this.gettingStates = this.gettingStates || 0; + this.gettingStates++; + if (this.gettingStates > 1) { + // fix for slow devices + console.log('Trying to get empty list, because the whole list could not be loaded'); + IDs = []; + } + this._socket.emit('getStates', IDs, (err, data) => { + this.gettingStates--; + if (err || !data) { + if (callback) { + callback(err || 'Authentication required'); + } + } else if (callback) { + callback(null, data); + } + }); + } + } + + _fillChildren(objects) { + const items = []; + + for (const id in objects) { + if (!objects.hasOwnProperty(id)) continue; + items.push(id); + } + items.sort(); + + for (let i = 0; i < items.length; i++) { + if (objects[items[i]].common) { + let j = i + 1; + const children = []; + const len = items[i].length + 1; + const name = items[i] + '.'; + while (j < items.length && items[j].substring(0, len) === name) { + children.push(items[j++]); + } + + objects[items[i]].children = children; + } + } + } + + // callback(err, data) + getObjects(useCache, callback) { + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + // If cache used + if (this._useStorage && useCache) { + if (this.storage) { + const objects = this._objects || this.storage.get('objects'); + if (objects) return callback(null, objects); + } else if (this._objects) { + return callback(null, this._objects); + } + } + + if (!this._checkConnection('getObjects', arguments)) return; + this._socket.emit('getObjects', (err, data) => { + // Read all enums + this._socket.emit('getObjectView', 'system', 'enum', { + startkey: 'enum.', + endkey: 'enum.\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + const enums = {}; + for (let i = 0; i < res.rows.length; i++) { + data[res.rows[i].id] = res.rows[i].value; + enums[res.rows[i].id] = res.rows[i].value; + } + + // Read all adapters for images + this._socket.emit('getObjectView', 'system', 'instance', { + startkey: 'system.adapter.', + endkey: 'system.adapter.\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + for (let i = 0; i < res.rows.length; i++) { + data[res.rows[i].id] = res.rows[i].value; + } + // find out default file mode + if (data['system.adapter.' + this.namespace] && + data['system.adapter.' + this.namespace].native && + data['system.adapter.' + this.namespace].native.defaultFileMode) { + this._defaultMode = data['system.adapter.' + this.namespace].native.defaultFileMode; + } + + // Read all channels for images + this._socket.emit('getObjectView', 'system', 'channel', { + startkey: '', + endkey: '\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + for (let i = 0; i < res.rows.length; i++) { + data[res.rows[i].id] = res.rows[i].value; + } + + // Read all devices for images + this._socket.emit('getObjectView', 'system', 'device', { + startkey: '', + endkey: '\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + for (let i = 0; i < res.rows.length; i++) { + data[res.rows[i].id] = res.rows[i].value; + } + + if (this._useStorage) { + this._fillChildren(data); + this._objects = data; + this._enums = enums; + + if (this.storage) { + this.storage.set('objects', data); + this.storage.set('enums', enums); + this.storage.set('timeSync', Date.now()); + } + } + + if (callback) callback(err, data); + }); + }); + }); + }); + }); + } + + getChildren(id, useCache, callback) { + if (!this._checkConnection('getChildren', arguments)) return; + + if (typeof id === 'function') { + callback = id; + id = null; + useCache = false; + } + if (typeof id === 'boolean') { + callback = useCache; + useCache = id; + id = null; + } + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + + if (!id) return callback('getChildren: no id given'); + + const data = []; + + if (this._useStorage && useCache) { + if (this.storage) { + const objects = this.storage.get('objects'); + if (objects && objects[id] && objects[id].children) { + return callback(null, objects[id].children); + } + } else if (this._objects && this._objects[id] && this._objects[id].children) { + return callback(null, this._objects[id].children); + } + } + + // Read all devices + this._socket.emit('getObjectView', 'system', 'device', { + startkey: id + '.', + endkey: id + '.\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + res.rows.forEach(row => data[row.id] = row.value); + + this._socket.emit('getObjectView', 'system', 'channel', { + startkey: id + '.', + endkey: id + '.\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + res.rows.forEach(row => data[row.id] = row.value); + + // Read all adapters for images + this._socket.emit('getObjectView', 'system', 'state', { + startkey: id + '.', + endkey: id + '.\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + res.rows.forEach(row => data[row.id] = row.value); + + const list = []; + + const count = id.split('.').length; + + // find direct children + for (const _id in data) { + const parts = _id.split('.'); + if (count + 1 === parts.length) { + list.push(_id); + } + } + list.sort(); + + if (this._useStorage && this.storage) { + const objects = this.storage.get('objects') || {}; + + for (const id_ in data) { + if (data.hasOwnProperty(id_)) { + objects[id_] = data[id_]; + } + } + if (objects[id] && objects[id].common) { + objects[id].children = list; + } + // Store for every element theirs children + const items = []; + for (const __id in data) { + if (data.hasOwnProperty(__id)) { + items.push(__id); + } + } + items.sort(); + + for (let k = 0; k < items.length; k++) { + if (objects[items[k]].common) { + let j = k + 1; + const children = []; + const len = items[k].length + 1; + const name = items[k] + '.'; + while (j < items.length && items[j].substring(0, len) === name) { + children.push(items[j++]); + } + + objects[items[k]].children = children; + } + } + + window.storage.set('objects', objects); + } + + callback && callback(err, list); + }); + }); + }); + } + + getObject(id, useCache, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + useCache = false; + } + if (typeof id === 'boolean') { + callback = useCache; + useCache = id; + id = null; + } + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + if (!id) { + return callback('no id given'); + } + + // If cache used + if (this._useStorage && useCache) { + if (this.storage) { + const objects = this._objects || this.storage.get('objects'); + if (objects && objects[id]) { + return callback(null, objects[id]); + } + } else if (this._enums) { + return callback(null, this._enums); + } + } + + this._socket.emit('getObject', id, (err, obj) => { + if (err) { + callback(err); + return; + } + if (this._useStorage && this.storage) { + const objects = this.storage.get('objects') || {}; + objects[id] = obj; + this.storage.set('objects', objects); + } + return callback(null, obj); + }); + } + + getGroups(groupName, useCache, callback) { + if (typeof groupName === 'function') { + callback = groupName; + groupName = null; + useCache = false; + } + if (typeof groupName === 'boolean') { + callback = useCache; + useCache = groupName; + groupName = null; + } + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + groupName = groupName || ''; + + // If cache used + if (this._useStorage && useCache) { + if (this.storage) { + const groups = this._groups || this.storage.get('groups'); + if (groups) { + return callback(null, groups); + } + } else if (this._groups) { + return callback(null, this._groups); + } + } + if (this._type === 'local') { + return callback(null, []); + } else { + // Read all enums + this._socket.emit('getObjectView', 'system', 'group', { + startkey: 'system.group.' + groupName, + endkey: 'system.group.' + groupName + '\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + const groups = {}; + for (let i = 0; i < res.rows.length; i++) { + const obj = res.rows[i].value; + groups[obj._id] = obj; + } + if (this._useStorage) { + this._groups = groups; + + this.storage && this.storage.set('groups', groups); + } + + callback(null, groups); + }); + } + } + + getEnums(enumName, useCache, callback) { + if (typeof enumName === 'function') { + callback = enumName; + enumName = null; + useCache = false; + } + if (typeof enumName === 'boolean') { + callback = useCache; + useCache = enumName; + enumName = null; + } + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + + // If cache used + if (this._useStorage && useCache) { + if (this.storage) { + const enums = this._enums || this.storage.get('enums'); + if (enums) { + return callback(null, enums); + } + } else if (this._enums) { + return callback(null, this._enums); + } + } + + if (this._type === 'local') { + return callback(null, []); + } else { + + enumName = enumName ? enumName + '.' : ''; + // Read all enums + this._socket.emit('getObjectView', 'system', 'enum', { + startkey: 'enum.' + enumName, + endkey: 'enum.' + enumName + '\u9999' + }, (err, res) => { + if (err) { + callback(err); + return; + } + const enums = {}; + for (let i = 0; i < res.rows.length; i++) { + const obj = res.rows[i].value; + enums[obj._id] = obj; + } + if (this._useStorage && typeof this.storage !== 'undefined') { + this.storage.set('enums', enums); + } + callback(null, enums); + }); + } + } + + // return time when the objects were synchronized + getSyncTime() { + if (this._useStorage && this.storage) { + const timeSync = this.storage.get('timeSync'); + if (timeSync) { + return new Date(timeSync); + } + } + return null; + } + + addObject(objId, obj, callback) { + if (!this._isConnected) { + console.log('No connection!'); + } else + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + } + } + + delObject(objId) { + if (!this._checkConnection('delObject', arguments)) return; + + this._socket.emit('delObject', objId); + } + + httpGet(url, callback) { + if (!this._isConnected) { + console.log('No connection!'); + return; + } + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + this._socket.emit('httpGet', url, data => callback && callback(data)); + } + + logError(errorText) { + console.log("Error: " + errorText); + if (!this._isConnected) { + //console.log('No connection!'); + return; + } + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + this._socket.emit('log', 'error', 'Addon DashUI ' + errorText); + } + + _queueCmdIfRequired(func, args) { + if (!this._isAuthDone) { + // Queue command + this._cmdQueue.push({func: func, args: args}); + + if (!this._authRunning) { + this._authRunning = true; + // Try to read version + this._checkAuth(version => { + // If we have got version string, so there is no authentication, or we are authenticated + this._authRunning = false; + if (version) { + this._isAuthDone = true; + // Repeat all stored requests + const __cmdQueue = this._cmdQueue; + // Trigger GC + this._cmdQueue = null; + this._cmdQueue = []; + for (let t = 0, len = __cmdQueue.length; t < len; t++) { + this[__cmdQueue[t].func].apply(this, __cmdQueue[t].args); + } + } else { + // Auth required + this._isAuthRequired = true; + // What for AuthRequest from server + } + }); + } + + return true; + } else { + return false; + } + } + + authenticate(user, password, salt) { + this._authRunning = true; + + if (user !== undefined) { + this._authInfo = { + user: user, + hash: password + salt, + salt: salt + }; + } + + if (!this._isConnected) { + console.log('No connection!'); + return; + } + + if (!this._authInfo) { + console.log("No credentials!"); + } + } + + getConfig(useCache, callback) { + if (!this._checkConnection('getConfig', arguments)) return; + + if (typeof useCache === 'function') { + callback = useCache; + useCache = false; + } + if (this._useStorage && useCache) { + if (this.storage) { + const objects = this.storage.get('objects'); + if (objects && objects['system.config']) { + return callback(null, objects['system.config'].common); + } + } else if (this._objects && this._objects['system.config']) { + return callback(null, this._objects['system.config'].common); + } + } + this._socket.emit('getObject', 'system.config', (err, obj) => { + if (callback && obj && obj.common) { + + if (this._useStorage && this.storage) { + const objects = this.storage.get('objects') || {}; + objects['system.config'] = obj; + this.storage.set('objects', objects); + } + + callback(null, obj.common); + } else { + callback('Cannot read language'); + } + }); + } + + sendCommand(instance, command, data, ack) { + this.setState(this.namespace + '.control.instance', {val: instance || 'notdefined', ack: true}); + this.setState(this.namespace + '.control.data', {val: data, ack: true}); + this.setState(this.namespace + '.control.command', {val: command, ack: ack === undefined ? true : ack}); + } + + _detectViews(projectDir, callback) { + this.readDir('/' + this.namespace + '/' + projectDir, (err, dirs) => { + // find vis-views.json + for (let f = 0; f < dirs.length; f++) { + if (dirs[f].file === 'vis-views.json' && (!dirs[f].acl || dirs[f].acl.read)) { + return callback(err, { + name: projectDir, + readOnly: (dirs[f].acl && !dirs[f].acl.write), + mode: dirs[f].acl ? dirs[f].acl.permissions : 0 + }); + } + } + callback(err); + }); + } + + _readProjects(dirs, callback, err, result) { + result = result || []; + + if (!dirs || !dirs.length) { + callback && callback(err, result); + } else { + const dir = dirs.shift(); + this._detectViews(dir.file, (subErr, project) => { + project && result.push(project); + err = err || subErr; + setTimeout(() => this._readProjects(dirs, callback, err, result), 0); + }); + } + } + + readProjects(callback) { + this.readDir('/' + this.namespace, (err, dirs) => this._readProjects(dirs, callback)); + } + + chmodProject(projectDir, mode, callback) { + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + + this._socket.emit('chmodFile', this.namespace, projectDir + '*', {mode: mode}, (err, data) => + callback && callback(err, data)); + } + + clearCache() { + this.storage && this.storage.empty(); + } + + getHistory(id, options, callback) { + if (!this._checkConnection('getHistory', arguments)) return; + + if (!options) options = {}; + if (!options.timeout) options.timeout = 2000; + + let timeout = setTimeout(() => { + timeout = null; + callback('timeout'); + }, options.timeout); + + this._socket.emit('getHistory', id, options, (err, result) => { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + callback(err, result); + }); + } + + getLiveHost(cb) { + this._socket.emit('getObjectView', 'system', 'host', { + startkey: 'system.host.', + endkey: 'system.host.\u9999' + }, (err, res) => { + const _hosts = []; + for (let h = 0; h < res.rows.length; h++) { + _hosts.push(res.rows[h].id + '.alive'); + } + if (!_hosts.length) { + cb(''); + return; + } + this.getStates(_hosts, (err, states) => { + for (const h in states) { + if (states.hasOwnProperty(h) && (states[h].val === 'true' || states[h].val === true)) { + cb(h.substring(0, h.length - '.alive'.length)); + return; + } + } + cb(''); + }); + }); + } + + readDirAsZip(project, useConvert, callback) { + if (!callback) { + callback = useConvert; + useConvert = undefined; + } + if (!this._isConnected) { + console.log('No connection!'); + return; + } + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + if (project.match(/\/$/)) { + project = project.substring(0, project.length - 1); + } + this.getLiveHost(host => { + if (!host) { + window.alert('No active host found'); + return; + } + // to do find active host + this._socket.emit('sendToHost', host, 'readDirAsZip', { + id: this.namespace, + name: project || 'main', + options: { + settings: useConvert + } + }, data => { + if (data.error) console.error(data.error); + if (callback) callback(data.error, data.data); + }); + + }); + } + + writeDirAsZip(project, base64, callback) { + if (!this._isConnected) { + console.log('No connection!'); + return; + } + //socket.io + if (this._socket === null) { + console.log('socket.io not initialized'); + return; + } + if (project.match(/\/$/)) { + project = project.substring(0, project.length - 1); + } + this.getLiveHost(host => { + if (!host) { + window.alert('No active host found'); + return; + } + this._socket.emit('sendToHost', host, 'writeDirAsZip', { + id: this.namespace, + name: project || 'main', + data: base64 + }, data => { + data.error && console.error(data.error); + callback && callback(data.error); + }); + }); + } +} + +export default ServerConnection; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogColor.js b/src/src/Dialogs/SmartDialogColor.js new file mode 100644 index 0000000..88caba7 --- /dev/null +++ b/src/src/Dialogs/SmartDialogColor.js @@ -0,0 +1,575 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import {decomposeColor} from '@material-ui/core/styles/colorManipulator'; +import PropTypes from 'prop-types'; +import Button from '@material-ui/core/Button'; + +import ColorsTempImg from '../assets/tempColor.png'; +import ColorsImg from '../assets/rgb.png'; +import SmartDialogGeneric from './SmartDialogGeneric'; +import UtilsColors from '../UtilsColors'; +import ColorSaturation from '../basic-controls/react-color-saturation/ColorSaturation'; +import {TiLightbulb as IconLight} from 'react-icons/ti'; +import {TiThermometer as IconTemp} from 'react-icons/ti'; +import {MdColorLens as IconRGB} from 'react-icons/md'; +import I18n from '../i18n'; +import {withStyles} from '@material-ui/core/styles/index'; + +const HANDLER_SIZE = 32; +const styles = { + buttonColorStyle: { + position: 'absolute', + left: 'calc(50% + 7rem)', + bottom: '4rem', + height: '2.5rem', + width: '2.5rem', + cursor: 'pointer' + }, + dimmerSlider: { + width: 'calc(100% - 3rem)', + position: 'absolute', + top: '25rem', + left: 16 + }, + buttonOnOff: { + position: 'absolute', + left: 5, + top: 5, + height: 24, + width: 36, + background: '-webkit-gradient(linear, left bottom, left top, color-stop(0, #1d1d1d), color-stop(1, #131313))', + boxShadow: '0 0.2em 0.1em 0.05em rgba(255, 255, 255, 0.1) inset, 0 -0.2em 0.1em 0.05em rgba(0, 0, 0, 0.5) inset, 0 0.5em 0.65em 0 rgba(0, 0, 0, 0.3)', + color: 'rgb(99, 99, 99)', + textShadow: '0 0 0.3em rgba(23,23,23)' + }, + buttonOn: { + color: '#3f3f3f', + background: '#F8E900' + }, + buttonOff: { + color: '#ffffff', + background: '#c0bdbe' + }, + buttonColor: { + position: 'absolute', + left: 50, + top: 5, + height: 24, + width: 36, + background: '-webkit-gradient(linear, left bottom, left top, color-stop(0, #1d1d1d), color-stop(1, #131313))', + boxShadow: '0 0.2em 0.1em 0.05em rgba(255, 255, 255, 0.1) inset, 0 -0.2em 0.1em 0.05em rgba(0, 0, 0, 0.5) inset, 0 0.5em 0.65em 0 rgba(0, 0, 0, 0.3)', + color: 'rgb(99, 99, 99)', + textShadow: '0 0 0.3em rgba(23,23,23)' + }, + buttonRgb: { + color: '#ffffff', + background: '#ff6a5b' + }, + buttonTemp: { + color: '#ffffff', + background: '#c0bdbe' + }, + cursor: { + position: 'absolute', + cursor: 'pointer', + zIndex: 12, + pointerEvents: 'none', + width: HANDLER_SIZE, + height: HANDLER_SIZE, + borderRadius: HANDLER_SIZE, + boxSizing: 'border-box', + border: '2px solid dimgrey' + }, + colorCircle: { + position: 'absolute', + zIndex: 11, + width: '100%', + height: 'auto', + top: '3rem', + left: 0 + }, + div: { + width: '20rem', + position: 'absolute', + height: '100%', + } +}; + +const HEIGHT_HEADER = 64; +const HEIGHT_COLOR = 320; +const HEIGHT_DIMMER = 64; + +class SmartDialogColor extends SmartDialogGeneric { + // expected: + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + windowWidth: PropTypes.number, + onClose: PropTypes.func.isRequired, + onRgbChange: PropTypes.func, + onDimmerChange: PropTypes.func, + onToggle: PropTypes.func, + ids: PropTypes.object, + startRGB: PropTypes.string, + startTemp: PropTypes.number, + startModeTemp: PropTypes.bool, + + modeRGB: PropTypes.bool, + modeTemperature: PropTypes.bool, + + startDimmer: PropTypes.number, + useDimmer: PropTypes.bool, + startOn: PropTypes.bool, + useOn: PropTypes.bool, + }; + + constructor(props) { + super(props); + this.tMin = this.props.temperatureMin || 2200; + this.tMax = this.props.temperatureMax || 6500; + this.stateRx.color = (this.props.startRGB || '#00FF00').toString(); + this.stateRx.temperature = this.props.startTemp || UtilsColors.rgb2temperature(this.stateRx.color); + this.stateRx.dimmer = this.props.useDimmer ? (this.props.startDimmer === null ? 100 : parseFloat(this.props.startDimmer) || 0) : 0; + this.stateRx.on = this.props.useOn ? (this.props.startOn === null ? true : !!this.props.startOn) : true; + this.stateRx.tempMode = (this.props.startModeTemp && this.props.modeTemperature) || (!this.props.modeRGB && this.props.modeTemperature); + + this.onMouseMoveBind = this.onMouseMove.bind(this); + this.onMouseUpBind = this.onMouseUp.bind(this); + + this.refColor = React.createRef(); + this.refColorCursor = React.createRef(); + this.refColorImage = React.createRef(); + + this.colorWidth = 0; + this.colorTop = 0; + this.colorLeft = 0; + this.button = { + time: 0, + name: '', + timer: null + }; + if (this.stateRx.tempMode) { + this.dialogStyle = {background: 'rgba(154, 154, 154, 0.8)'}; + } + + this.setMaxHeight(); + this.componentReady(); + } + + componentWillReceiveProps(nextProps) { + const newState = {}; + let changed = false; + if (nextProps.startOn !== this.state.on) { + newState.on = nextProps.startOn; + changed = true; + } + /*if (nextProps.startDimmer !== this.state.dimmer) { + newState.dimmer = nextProps.startDimmer; + changed = true; + } + if (nextProps.startRGB !== this.state.color) { + newState.color = nextProps.startRGB; + changed = true; + }*/ + if (changed) { + this.setState(newState); + } + } + + setMaxHeight() { + let maxHeight = 0; + + this.divs = { + header: {height: HEIGHT_HEADER, visible: true}, + color: {height: HEIGHT_COLOR, visible: true}, + dimmer: {height: HEIGHT_DIMMER, visible: this.props.useDimmer} + }; + + // calculate positions + for (const name in this.divs) { + if (this.divs.hasOwnProperty(name) && this.divs[name].visible) { + maxHeight += this.divs[name].height + 16; + } + } + + if (this.dialogStyle.maxHeight !== maxHeight) { + this.dialogStyle.maxHeight = maxHeight; + } + } + + static createRgb(size) { + size = size || 300; + let rad; + let oldRad; + const d2r = Math.PI / 180; + let c = document.createElement('canvas'); + c.width = c.height = size; + let ctx = c.getContext('2d'); + let s; + let t; + + for (let hr = size; hr > 1; hr--) { + oldRad = 0; + for(let i = 0; i < 360; i += 1) { + rad = (i + 1) * d2r; + s = hr / size; + if (s > 0.5) { + t = (1 + Math.sin(Math.PI * (s + 0.5) * 2 - Math.PI / 2)) / 2; + } else { + t = 0; + } + + ctx.strokeStyle = 'hsl(' + (-i) + ', 100%, '+ (50 + (50 - t * 50)) + '%)'; + ctx.beginPath(); + ctx.arc(size / 2, size / 2, hr / 2, oldRad, rad + 0.01); + ctx.stroke(); + oldRad = rad; + } + } + return c.toDataURL(); + } + + createCT(size) { + size = size || 300; + let rad; + let oldRad; + const d2r = Math.PI / 180; + let c = document.createElement('canvas'); + c.width = c.height = size; + let ctx = c.getContext('2d'); + + for (let hr = size; hr > size * 0.8; hr--) { + oldRad = 120 * d2r; + for (let i = 0; i < 300; i += 1) { + rad = (i + 120 + 1) * d2r; + //s = 100 - Math.round(hr / size * 100); + + const rgb = UtilsColors.temperatureToRGB((i / 300) * (this.tMax - this.tMin) + this.tMin); + ctx.strokeStyle = UtilsColors.rgb2string(rgb); + ctx.beginPath(); + ctx.arc(size / 2, size / 2, hr / 2 * 0.99, oldRad, rad + 0.01); + ctx.stroke(); + oldRad = rad; + } + + } + return c.toDataURL(); + } + + tempToPos(temp, size) { + let ratio = (temp - this.tMin) / (this.tMax - this.tMin); + let h = (300 * ratio + 120) / 360; + const R = (size / 2); + let x = R + Math.cos(Math.PI * 2 * h) * R; + let y = R + Math.sin(Math.PI * 2 * h) * R; + return {x, y}; + } + + posToTemp(x, y) { + let h; + if (x < 0) { + h = Math.atan2(y, -x) * 180 / Math.PI; + h = 180 - h; + } else { + h = Math.atan2(y, x) * 180 / Math.PI; + } + if (h < 0) h += 360; + if (h > 90) { + h -= 120; + } else { + h += 360 - 120; + } + + if (h < 0) h = 0; + if (h > 300) h = 300; + h = h / 300; // => 0-1 + return h * (this.tMax - this.tMin) + this.tMin; + } + + static colorToPos(color, size) { + let c = decomposeColor(color); + let hsl = UtilsColors.rgbToHsl(c.values[0], c.values[1], c.values[2]); + let h = -hsl[0]; + if (isNaN(h)) h = 0; + const R = (size / 2); + let x = R + Math.cos(Math.PI * 2 * h) * R; + let y = R + Math.sin(Math.PI * 2 * h) * R; + return {x, y}; + } + + static posToColor(x, y) { + let h; + if (x < 0) { + h = Math.atan2(y, -x) * 180 / Math.PI; + if (y > 0) { + h = 180 - h; + } else{ + h = 180 - h; + } + } else { + h = Math.atan2(y, x) * 180 / Math.PI; + } + h = h * -1; + if (h < 0) h += 360; + h = h / 360; + const rgb = UtilsColors.hslToRgb(h, 1, 0.5); + let r = Math.round(rgb[0]).toString(16); + let g = Math.round(rgb[1]).toString(16); + let b = Math.round(rgb[2]).toString(16); + if (r.length < 2) r = '0' + r; + if (g.length < 2) g = '0' + g; + if (b.length < 2) b = '0' + b; + return '#' + r + g + b; + } + + componentDidUpdate() { + if (!this.colorWidth) { + /*const h = this.refColor.current.offsetHeight - 6 * 16; + if (h < this.refColor.current.offsetWidth) { + this.colorWidth = h; + this.refColor.current.style.width = this.colorWidth + 'px'; + this.refColor.current.style.left = 'calc(50% - ' + (this.colorWidth / 2) + 'px)'; + }*/ + this.colorWidth = this.refColorImage.current.offsetWidth; + this.colorLeft = this.refColorImage.current.offsetLeft; + this.colorTop = this.refColorImage.current.offsetTop; + let pos = this.state.tempMode ? this.tempToPos(this.state.temperature, this.colorWidth - HANDLER_SIZE) : SmartDialogColor.colorToPos(this.state.color, this.colorWidth - HANDLER_SIZE); + this.refColorCursor.current.style.top = this.colorTop + pos.y + (pos.y > 0 ? 0 : -HANDLER_SIZE) + 'px'; + this.refColorCursor.current.style.left = this.colorLeft + pos.x + (pos.x > 0 ? 0 : -HANDLER_SIZE) + 'px'; + this.rect = this.refColorImage.current.getBoundingClientRect(); + } + } + + sendRGB() { + if (this.props.useOn && !this.state.on) { + this.setState({on: true}); + this.props.onToggle(true); + } + if (this.props.useDimmer) { + if (!this.state.dimmer) { + this.setState({dimmer: 100}); + this.props.onDimmerChange(100); + } + } + + if (this.state.tempMode) { + this.props.onRgbChange(UtilsColors.rgb2string(UtilsColors.temperatureToRGB(this.state.temperature)), Math.round(this.state.temperature), SmartDialogColor.COLOR_MODES.TEMPERATURE); + } else { + this.props.onRgbChange(this.state.color, 0, SmartDialogColor.COLOR_MODES.RGB); + } + } + + onSwitchColorMode() { + const newState = {tempMode: !this.state.tempMode}; + if (newState.tempMode) { + // Temperature mode + const rgb = UtilsColors.hex2array(this.state.color); + newState.temperature = UtilsColors.rgb2temperature(rgb[0], rgb[1], rgb[2]); + this.setDialogStyle({background: 'rgba(154, 154, 154, 0.8)', maxHeight: this.dialogStyle.maxHeight}); + } else { + // Color mode + newState.color = UtilsColors.rgb2string(UtilsColors.temperatureToRGB(this.state.temperature)); + this.setDialogStyle({maxHeight: this.dialogStyle.maxHeight}); + } + this.setState(newState); + } + + eventToValue(e) { + let pageY = e.touches ? e.touches[e.touches.length - 1].clientY : e.pageY; + let pageX = e.touches ? e.touches[e.touches.length - 1].clientX : e.pageX; + const halfSize = this.colorWidth / 2; + if (this.state.tempMode) { + const temperature = this.posToTemp(pageX - this.rect.left - halfSize, pageY - this.rect.top - halfSize); + this.setState({temperature}); + } else { + const color = SmartDialogColor.posToColor(pageX - this.rect.left - halfSize, pageY - this.rect.top - halfSize); + this.setState({color}); + } + + if (this.changeTimer) { + clearTimeout(this.changeTimer); + } + if (this.props.onRgbChange) { + this.changeTimer = setTimeout(() => { + this.changeTimer = null; + this.sendRGB(); + }, 1000); + } + } + + onMouseMove(e) { + e.preventDefault(); + e.stopPropagation(); + this.eventToValue(e); + } + + onMouseDown(e) { + e.preventDefault(); + e.stopPropagation(); + + this.eventToValue(e); + + document.addEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.addEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + } + + onMouseUp(e) { + e.preventDefault(); + e.stopPropagation(); + this.click = Date.now(); + + if (this.changeTimer) { + clearTimeout(this.changeTimer); + this.changeTimer = null; + } + + document.removeEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.removeEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + + this.sendRGB(); + } + + onClick() { + this.click = Date.now(); + } + + getHue() { + if (this.state.tempMode) { + return '#FFFFFF'; + } + let color = this.state.color; + if (!color) { + return '#FFFFFF'; + } + const [r,g,b] = UtilsColors.hex2array(color); + const [h/*,s,l*/] = UtilsColors.rgbToHsl(r, g, b); + return h * 360; + } + + onDimmerChanged(dimmer) { + this.click = Date.now(); + this.setState({dimmer}); + if (this.changeTimer) { + clearTimeout(this.changeTimer); + } + if (this.props.onRgbChange) { + this.changeTimer = setTimeout(dimmer => { + this.changeTimer = null; + this.props.onDimmerChange(dimmer); + if (dimmer && this.props.useOn && !this.state.on) { + this.setState({on: true}); + this.props.onToggle(true); + } + }, 1000, dimmer); + } + } + + getOnOffButton() { + if (!this.props.useOn) return null; + const style = Object.assign( + {}, + styles.buttonOnOff, + this.state.on ? styles.buttonOn : styles.buttonOff); + return ( + ); + } + + getColorModeButton() { + if (!this.props.modeTemperature || !this.props.modeRGB) return null; + const style = Object.assign( + {}, + styles.buttonColor, + this.state.tempMode ? styles.buttonRgb : styles.buttonTemp); + return ( + ); + } + + onToggle() { + this.onClick(); + this.props.onToggle && this.props.onToggle(!this.state.on); + this.setState({on: !this.state.on}); + } + + generateContent() { + let pos = this.state.tempMode ? + this.tempToPos(this.state.temperature, this.colorWidth - HANDLER_SIZE) : + SmartDialogColor.colorToPos(this.state.color, this.colorWidth - HANDLER_SIZE); + + if (this.state.tempMode) { + this.imageCT = ColorsTempImg;// this.imageCT || this.createCT(600); + } + + return [( +
+ color +
0 ? 0 : -HANDLER_SIZE), + left: pos.x + this.colorLeft + (pos.x > 0 ? 0 : -HANDLER_SIZE), + }}> +
+
), + this.props.useDimmer ? (
+ +
) : null, + this.getOnOffButton(), + this.getColorModeButton() + ]; + } +} + +export default withStyles(styles)(SmartDialogColor); \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogGeneric.js b/src/src/Dialogs/SmartDialogGeneric.js new file mode 100644 index 0000000..c846f31 --- /dev/null +++ b/src/src/Dialogs/SmartDialogGeneric.js @@ -0,0 +1,195 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React, {Component} from 'react'; +import PropTypes from 'prop-types'; +import Theme from '../theme'; +import Paper from '@material-ui/core/Paper'; +import Snackbar from '@material-ui/core/Snackbar'; +import {MdClose as CloseIcon} from 'react-icons/md'; +import Button from '@material-ui/core/Button'; +import I18n from '../i18n'; + +class SmartDialogGeneric extends Component { + + static COLOR_MODES = { + RGB: 0, + HUE: 1, + R_G_B: 2, + TEMPERATURE: 3 + }; + + // expected: + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string, + windowWidth: PropTypes.string, + + onClose: PropTypes.func, + onCollectIds: PropTypes.func + }; + + constructor(props) { + super(props); + this.stateRx = { + toast: '' + }; + + // disable context menu after long click + window.addEventListener('contextmenu', SmartDialogGeneric.onContextMenu, false); + this.refModal = React.createRef(); + this.dialogStyle = {}; + this.closeOnPaperClick = false; + this.savedParent = null; + + this.subscribes = null; + this.subscribed = false; + this.editMode = this.props.editMode; + this.positionTuned = false; + + } + + componentReady () { + // ↓ ignore error here + // eslint-disable-next-line react/no-direct-mutation-state + this.state = this.stateRx; + delete this.stateRx; + } + + static onContextMenu(e) { + if (!e.shiftKey && !e.ctrlKey) { + e.preventDefault(); + console.log('Ignore context menu' + e); + return false; + } + } + + componentDidMount() { + // move this element to the top of body + if (this.refModal) { + this.savedParent = this.refModal.current.parentElement; + document.body.appendChild(this.refModal.current); + } + + if (this.subscribes && !this.subscribed) { + this.subscribed = true; + this.props.onCollectIds(this, this.subscribes, true); + } + + if (!this.positionTuned) { + Object.assign(this.dialogStyle, {left: 'calc(50% - ' + (this.refModal.current.firstChild.offsetWidth / 2) + 'px)'}); + this.forceUpdate(); + } + } + + componentWillUnmount() { + this.refModal && this.savedParent.appendChild(this.refModal.current); + + if (this.props.onCollectIds && this.subscribed) { + this.props.onCollectIds(this, this.subscribes, false); + this.subscribed = null; + } + } + + // default handler + updateState(id, state) { + const newState = {}; + if (state) { + newState[id] = {val: state.val, ts: state.ts, lc: state.lc}; + } else { + newState[id] = null; + } + this.setState(newState); + } + + mayClose() { + return !(this.click && Date.now() - this.click < 50); + } + + onClose(forceClose) { + if (forceClose || this.mayClose()) { + window.removeEventListener('contextmenu', SmartDialogGeneric.onContextMenu, false); + this.props.onClose && this.props.onClose(); + } + } + + handleToastClose() { + this.setState({toast: ''}); + } + + generateContent() { + return null; + } + + onClick(e) { + if (!this.closeOnPaperClick) { + e && e.stopPropagation(); + this.click = Date.now(); + } + } + + showCloseButton() { + if (this.props.windowWidth < 500) { + return () + } else { + return null; + } + } + + setDialogStyle(style) { + this.dialogStyle = style || {}; + this.forceUpdate(); + } + + render() { + return (
this.onClose()} + style={Theme.dialog.back}> + + {this.generateContent()} + {this.state.toast}} + /> + {this.showCloseButton()} + + + {this.getAdditionalElements && this.getAdditionalElements()} + +
); + } +} + +//export default withStyles(styles)(SmartDialogGeneric); +export default SmartDialogGeneric; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogInfo.js b/src/src/Dialogs/SmartDialogInfo.js new file mode 100644 index 0000000..3756354 --- /dev/null +++ b/src/src/Dialogs/SmartDialogInfo.js @@ -0,0 +1,186 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; +import Theme from '../theme'; +import I18n from '../i18n'; +import List from '@material-ui/core/List'; +import ListItem from '@material-ui/core/ListItem'; +import Button from '@material-ui/core/Button'; +import Slider from '@material-ui/lab/Slider'; +import SmartDialogGeneric from './SmartDialogGeneric'; +import Typography from '@material-ui/core/Typography'; +import BoolControl from '../basic-controls/react-info-controls/BoolControl' +import InputControl from '../basic-controls/react-info-controls/InputControl' +import InfoControl from '../basic-controls/react-info-controls/InfoControl' + +class SmartDialogInfo extends SmartDialogGeneric { + // expected: + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string.isRequired, + windowWidth: PropTypes.number, + onClose: PropTypes.func.isRequired, + objects: PropTypes.object, + states: PropTypes.object, + onValueChange: PropTypes.func, + points: PropTypes.array.isRequired + }; + + constructor(props) { + super(props); + this.props.points.forEach(e => { + const state = this.props.states[e.id]; + if (state) { + this.stateRx[e.id] = {val: state.val, ts: state.ts, lc: state.lc}; + } else { + this.stateRx[e.id] = null; + } + this.subscribes = this.subscribes || []; + this.subscribes.push(e.id); + }); + this.refDialog = React.createRef(); + + this.componentReady(); + } + + controlValue(id, value) { + this.setState({toast: I18n.t('sent')}); + this.props.onValueChange && this.props.onValueChange(id, value); + } + + handleToggle(id) { + const newState = {}; + const state = this.state[id]; + newState[id] = {val: !(state && state.val)}; + if (state) { + newState[id].lc = state.lc; + newState[id].ts = state.ts; + } + this.setState(newState); + this.controlValue(id, newState[id].val); + } + + handleValue(id, value) { + const newState = {}; + newState[id] = {val: value}; + const state = this.state[id]; + if (state) { + newState[id].lc = state.lc; + newState[id].ts = state.ts; + } + if (this.state[id].val !== newState[id].val) { + this.setState(newState); + } + this.controlValue(id, value); + } + + generateContent() { + const result = this.props.points.map((e, i) => { + const divider = i !== this.props.points.length - 1 ? () : null; + + let item; + + if (e.common && e.common.write) { + if (e.common.type === 'boolean') { + // switch + if (e.common.read !== false) { + item = ( this.handleToggle(e.id)} + />); + } else { // button: read = false, write = true + item = (
+ +
); + } + } else + if (e.common.type === 'number' && e.common.min !== undefined && e.common.max !== undefined && e.common.max - e.common.min < 5000) { + // slider + item = [({e.name} - {this.state[e.id] ? this.state[e.id].val : '?'}{e.unit}), + ( this.handleValue(e.id, value)} + /*label={ +
+
+ {this.state[e.id].val} +
+
+ }*/ + />)]; + } else { + // input field + item = ( this.handleValue(e.id, value)} + />); + } + } else { + if (e.common && e.common.type === 'boolean') { + item = (); + } else { + item = ( + + ); + } + } + + if (divider) { + return [item, divider]; + } else { + return item; + } + }); + return [ + (

{this.props.name}

), + ({result}) + ]; + } +} + +export default SmartDialogInfo; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogKnob.js b/src/src/Dialogs/SmartDialogKnob.js new file mode 100644 index 0000000..460bf55 --- /dev/null +++ b/src/src/Dialogs/SmartDialogKnob.js @@ -0,0 +1,159 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; +import Button from '@material-ui/core/Button'; + +import {MdVolumeMute as IconVolume0} from 'react-icons/md'; +import {MdVolumeUp as IconVolume100} from 'react-icons/md'; + +import SmartDialogGeneric from './SmartDialogGeneric'; +import KnobControl from '../basic-controls/react-knob/KnobControl'; +import I18n from '../i18n'; + +class SmartDialogKnob extends SmartDialogGeneric { + // expected: + + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string, + windowWidth: PropTypes.number, + + onClose: PropTypes.func, + + onMute: PropTypes.func, + + onValueChange: PropTypes.func, + startValue: PropTypes.number, + startMuteValue: PropTypes.bool, + type: PropTypes.number + }; + + static buttonMuteStyle = { + position: 'absolute', + left: 'calc(50% + 8em)', + top: '16.5em', + height: '2em', + width: '2.5em', + background: '-webkit-gradient(linear, left bottom, left top, color-stop(0, #1d1d1d), color-stop(1, #131313))', + boxShadow: '0 0.2em 0.1em 0.05em rgba(255, 255, 255, 0.1) inset, 0 -0.2em 0.1em 0.05em rgba(0, 0, 0, 0.5) inset, 0 0.5em 0.65em 0 rgba(0, 0, 0, 0.3)', + color: 'rgb(99, 99, 99)', + textShadow: '0 0 0.3em rgba(23,23,23)' + }; + + static buttonMuted = { + color: '#a8d8f8' + }; + + constructor(props) { + super(props); + this.stateRx.value = this.externalValue2localValue(this.props.startValue || 0); + this.stateRx.muteValue = this.props.startMuteValue || false; + + this.dialogStyle = { // used in generic + background: 'rgba(136,136,136,0.8)', + maxHeight: 412, + minHeight: 280, + }; + + this.closeOnPaperClick = true; // used in generic + + this.componentReady(); + } + + componentWillReceiveProps(nextProps) { + if (nextProps.startValue !== this.state.value) { + this.setState({value: nextProps.startValue}); + } + if (nextProps.startMuteValue !== undefined && nextProps.startMuteValue !== this.state.muteValue) { + this.setState({muteValue: nextProps.startMuteValue}); + } + } + + localValue2externalValue(value) { + if (this.props.min !== undefined && this.props.max !== undefined) { + return value * (this.props.max - this.props.min) / 100 + this.props.min; + } else { + return value; + } + } + + externalValue2localValue(value) { + if (this.props.min !== undefined && this.props.max !== undefined) { + return ((value - this.props.min) / (this.props.max - this.props.min)) * 100; + } else { + return value; + } + } + + onValueChanged(value) { + this.click = Date.now(); + + this.setState({value: this.externalValue2localValue(value)}); + if (this.controlTimer) { + clearTimeout(this.controlTimer); + } + + if (this.props.onValueChange) { + this.controlTimer = setTimeout(val => { + this.controlTimer = null; + this.props.onValueChange(Math.round(val)); + }, 300, value); + } + } + + onMute(e) { + e && e.preventDefault(); + e && e.stopPropagation(); + this.props.onMute && this.props.onMute(); + } + + getMuteButton() { + if (!this.props.onMute) return null; + const style = Object.assign( + {}, + SmartDialogKnob.buttonMuteStyle, + this.state.muteValue ? SmartDialogKnob.buttonMuted : {}); + return ( + ); + } + + generateContent() { + return [ + (), + this.getMuteButton() + ]; + } +} + +export default SmartDialogKnob; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogMedia.js b/src/src/Dialogs/SmartDialogMedia.js new file mode 100644 index 0000000..2c0945f --- /dev/null +++ b/src/src/Dialogs/SmartDialogMedia.js @@ -0,0 +1,652 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; + +import Button from '@material-ui/core/Button'; +import Slider from '@material-ui/lab/Slider'; + +import {MdMusicNote as IconNote} from 'react-icons/md'; +import {MdPlayArrow as IconPlay} from 'react-icons/md'; +import {MdPause as IconPause} from 'react-icons/md'; +import {MdStop as IconStop} from 'react-icons/md'; +import {MdSkipNext as IconNext} from 'react-icons/md'; +import {MdSkipPrevious as IconPrev} from 'react-icons/md'; + +import {MdShuffle as IconShuffle} from 'react-icons/md'; +import {MdRepeat as IconRepeatAll} from 'react-icons/md'; +import {MdRepeatOne as IconRepeatOne} from 'react-icons/md'; +import {MdVolumeUp as IconVolume100} from 'react-icons/md'; +import {MdVolumeMute as IconVolume0} from 'react-icons/md'; + +import Utils from '../Utils'; +import SmartDialogGeneric from './SmartDialogGeneric'; +import I18n from '../i18n'; +import Theme from "../theme"; +//import cover from '../assets/cover.png'; + +const HEIGHT_HEADER = 48; +const HEIGHT_VOLUME = 48; +const HEIGHT_COVER = 365; +const HEIGHT_INFO = 88; +const HEIGHT_CONTROL = 48; +const HEIGHT_TIME = 48; + +const REPEAT = { + NONE: 0, + ALL: 1, + ONE: 2 +}; + +const styles = { + info: { + div: { + zIndex: 1, + background: 'rgba(0,0,0,0.55)', + position: 'absolute', + bottom: 100, + width: 'calc(100% + 1em)', + left: '-0.5em', + padding: '1.2em', + }, + artist: { + fontSize: 14, + fontWeight: 'normal', + color: 'white' + }, + album: { + fontSize: 16, + fontWeight: 'bold', + color: 'white' + }, + title: { + fontSize: 14, + fontWeight: 'normal', + color: 'white' + } + }, + control: { + div: { + zIndex: 1, + background: 'rgba(255,255,255,0.9)', + position: 'absolute', + width: 'calc(100% + 1em)', + bottom: 48, + left: '-0.5em', + height: HEIGHT_CONTROL, + textAlign: 'center', + lineHeight: '48px', + verticalAlign: 'middle' + }, + prev: { + height: 24, + width: 24, + marginLeft: 3, + minHeight: 24, + verticalAlign: 'middle', + boxShadow: 'none', + background: 'rgba(255,255,255,1)' + }, + next: { + height: 24, + width: 24, + marginLeft: 3, + minHeight: 24, + verticalAlign: 'middle', + boxShadow: 'none', + background: 'rgba(255,255,255,1)' + }, + stop: { + height: 24, + width: 24, + marginLeft: 3, + minHeight: 24, + verticalAlign: 'middle', + boxShadow: 'none', + background: 'rgba(255,255,255,1)' + }, + play: { + + }, + pause: { + background: '#40EE40' + }, + repeat: { + position: 'absolute', + top: 5, + right: 54, + height: 24, + width: 24, + minHeight: 24, + marginLeft: 3, + verticalAlign: 'middle', + boxShadow: 'none', + background: 'rgba(255,255,255,1)', + float: 'right' + }, + shuffle: { + position: 'absolute', + top: 5, + right: 12, + height: 24, + width: 24, + minHeight: 24, + marginLeft: 3, + verticalAlign: 'middle', + boxShadow: 'none', + background: 'rgba(255,255,255,1)', + float: 'right' + }, + name: { + position: 'absolute', + left: '1.2em', + bottom: 2, + fontSize: 14, + color: 'rgba(0,0,0,0.6)' + } + }, + time: { + div: { + zIndex: 1, + background: 'rgba(255,255,255,0.9)', + position: 'absolute', + width: 'calc(100% + 1em)', + bottom: 0, + left: '-0.5em', + height: HEIGHT_TIME, + lineHeight: '48px', + textAlign: 'center', + verticalAlign: 'middle', + color: 'rgba(0,0,0,0.9)' + }, + elapsed: { + display: 'inline-block', + float: 'left', + paddingLeft: '1.2em' + }, + slider: { + display: 'inline-block', + width: 'calc(100% - 10em)', + verticalAlign: 'middle', + }, + duration: { + display: 'inline-block', + float: 'right', + paddingRight: '1.2em' + } + }, + volume: { + div: { + zIndex: 1, + background: 'rgba(255,255,255,0.9)', + position: 'absolute', + width: 'calc(100% + 1em)', + bottom: 0, + left: '-0.5em', + height: HEIGHT_TIME, + lineHeight: '48px', + textAlign: 'center', + verticalAlign: 'middle', + color: 'rgba(0,0,0,0.9)' + }, + mute: { + display: 'inline-block', + position: 'absolute', + left: '1.5em', + top: 4, + boxShadow: 'none' + }, + slider: { + display: 'inline-block', + width: 'calc(100% - 10em)', + verticalAlign: 'middle', + } + }, + cover: { + div: { + position: 'absolute', + top: 48, + width: 'calc(100% - 2em)', + height: 'calc(100% - 2em)', + maxHeight: HEIGHT_COVER, + zIndex: 0, + backgroundSize: '100% auto', + backgroundRepeat: 'no-repeat', + backgroundPosition: 'center' + }, + img: { + width: '100%', + height: 'auto' + } + }, + header: { + div: { + position: 'absolute', + fontSize: 16, + height: HEIGHT_HEADER -16, + zIndex: 1, + paddingTop: 16 + } + } +}; + +class SmartDialogMedia extends SmartDialogGeneric { + // expected: + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string.isRequired, + windowWidth: PropTypes.number, + onClose: PropTypes.func.isRequired, + objects: PropTypes.object, + states: PropTypes.object, + onCollectIds: PropTypes.func, + enumNames: PropTypes.array, + onControl: PropTypes.func, + ids: PropTypes.object.isRequired, + settings: PropTypes.object + }; + + constructor(props) { + super(props); + + this.ids = this.props.ids; + + for (const type in this.ids) { + if (this.ids.hasOwnProperty(type) && type !== 'buttons') { + for (const id in this.ids[type]) { + if (this.ids[type].hasOwnProperty(id) && this.ids[type][id]) { + this.subscribes = this.subscribes || []; + this.subscribes.push(this.ids[type][id]); + } + } + } + } + let maxHeight = 0; + + this.divs = { + 'header': {height: HEIGHT_HEADER, position: 'top', visible: true}, + 'volume': {height: HEIGHT_VOLUME, position: 'top', visible: this.ids.volume.set}, + 'cover': {height: HEIGHT_COVER, position: 'top', visible: this.ids.info.cover}, + 'info': {height: HEIGHT_INFO, position: 'bottom', visible: this.ids.info.artist || this.ids.info.album || this.ids.info.title}, + 'control': {height: HEIGHT_CONTROL, position: 'bottom', visible: true}, + 'time': {height: HEIGHT_TIME, position: 'bottom', visible: this.ids.control.elapsed || this.ids.control.duration || this.ids.control.seek}, + }; + // calculate positions + let top = 0; + let bottom = 0; + for (const name in this.divs) { + if (this.divs.hasOwnProperty(name) && this.divs[name].visible) { + maxHeight += this.divs[name].height; + if (this.divs[name].position === 'top') { + this.divs[name].points = top; + top += this.divs[name].height; + } + } + } + const keys = Object.keys(this.divs); + for (let j = keys.length - 1; j >= 0; j--) { + if (this.divs[keys[j]].visible && this.divs[keys[j]].position === 'bottom') { + this.divs[keys[j]].points = bottom; + bottom += this.divs[keys[j]].height; + } + } + for (const name in this.divs) { + if (this.divs.hasOwnProperty(name) && this.divs[name].visible) { + this.divs[name].style = Object.assign({}, styles[name].div, {[this.divs[name].position] : this.divs[name].points}); + } + } + + this.dialogStyle = { + maxHeight: maxHeight + }; + + const enums = []; + this.props.enumNames.forEach(e => (enums.indexOf(e) === -1) && enums.push(e)); + if (enums.indexOf(this.props.name) === -1) { + enums.push(this.props.name); + } + this.name = enums.join(' / '); + this.collectState = null; + this.collectTimer = null; + + this.volumeTimer = null; + this.seekTimer = null; + + this.componentReady(); + } + + onSeek(value) { + if (value !== this.state[this.ids.control.seek]){ + this.setState({[this.ids.control.seek]: value}); + + if (this.seekTimer) { + clearTimeout(this.seekTimer); + } + this.seekTimer = setTimeout((_value) => { + this.seekTimer = null; + this.props.onControl(this.ids.control.seek, _value); + }, 400, value); + } + } + + onVolume(value) { + if (value !== this.state[this.ids.volume.actual]){ + this.setState({[this.ids.volume.actual]: value}); + + if (this.volumeTimer) { + clearTimeout(this.volumeTimer); + } + this.volumeTimer = setTimeout((_value) => { + this.volumeTimer = null; + this.props.onControl(this.ids.volume.set, _value); + }, 400, value); + } + } + + onToggleMute() { + this.props.onControl(this.ids.volume.mute, !this.state[this.ids.volume.mute]); + } + + onShuffle() { + this.props.onControl(this.ids.mode.shuffle, !this.state[this.ids.mode.shuffle]); + } + + onRepeat() { + this.props.onControl(this.ids.mode.repeat, (this.state[this.ids.mode.repeat] + 1) % 3); + } + + onUpdateTimer() { + this.collectTimer = null; + if (this.collectState) { + this.setState(this.collectState); + this.collectState = null; + } + } + + updateState(id, state) { + if (id === this.ids.info.cover) { + this.collectState = this.collectState || {}; + let url = state && state.val; + if (url) { + //url = cover; + if (url.match(/\?.+$/)) { + url += '&ts=' + Date.now(); + } else { + url += '?ts=' + Date.now(); + } + } + this.setState({[id]: url}); + } else + if (id === this.ids.control.elapsed || + id === this.ids.control.seek || + id === this.ids.control.duration || + id === this.ids.volume.set || + id === this.ids.volume.actual) { + this.collectState = this.collectState || {}; + this.collectState[id] = Math.round(parseFloat(state.val)); + this.collectTimer && clearTimeout(this.collectTimer); + this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200); + } else + if (id === this.ids.info.album || id === this.ids.info.artist || id === this.ids.info.title) { + this.collectState = this.collectState || {}; + this.collectState[id] = state.val; + this.collectTimer && clearTimeout(this.collectTimer); + this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200); + } else + if (id === this.ids.volume.mute || id === this.ids.mode.shuffle) { + this.collectState = this.collectState || {}; + + this.collectState[id] = + state.val === 'true' || + state.val === true || + state.val === 'mute' || + state.val === 'shuffle' || + state.val === 'muted' || + state.val === 1 || + state.val === '1'; + + this.collectTimer && clearTimeout(this.collectTimer); + this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200); + } else + if (id === this.ids.mode.repeat) { + this.collectState = this.collectState || {}; + let val; + if (state.val === true || state.val === 'true') { + val = REPEAT.ALL; + } else if (state.val === 'false' || state.val === false) { + val = REPEAT.NONE; + } else if (state.val === 'all' || state.val === 'ALL' || state.val === 1 || state.val === '1') { + val = REPEAT.ALL; + } else if (state.val === 'one' || state.val === 'ONE' || state.val === 2 || state.val === '2') { + val = REPEAT.ONE; + } else { + val = REPEAT.NONE; + } + this.collectState[id] = val; + this.collectTimer && clearTimeout(this.collectTimer); + this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200); + } else + if (this.ids.control.state === id && state.ack) { + this.collectState = this.collectState || {}; + const val = + state.val === 'true' || + state.val === true || + state.val === 'PLAY' || + state.val === 'play' || + state.val === 1 || + state.val === '1'; + + // here can be 'stop' + this.collectState.stop = (state.val === 'STOP' || state.val === 'stop' || state.val === 'stopped' || state.val === 'STOPPED'); + + this.collectState = this.collectState || {}; + this.collectState[id] = val; + + if (state.ack && this.state.executing) { + this.collectState.executing = false; + } + this.collectTimer && clearTimeout(this.collectTimer); + this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200); + } else { + super.updateState(id, state); + } + } + + onButton(id) { + this.props.onControl(id, true); + } + + getVolumeSlider() { + if (this.ids.volume.set) { + return ( this.onVolume(value)} />); + } else if (this.ids.volume.actual) { + return (); + } else { + return null; + } + } + + getMute() { + if (!this.ids.volume.mute) return null; + let Icon; + let text; + let background; + let color; + let title; + + if (this.state[this.ids.volume.mute]) { + Icon = IconVolume0; + text = I18n.t('mute'); + background = '#f50057'; + color = 'white'; + title = I18n.t('muted'); + } else { + Icon = IconVolume100; + text = I18n.t('unmute'); + background = 'inherit'; + color = 'black'; + title = I18n.t('unmuted'); + } + + return ( + + ); + } + + getVolumeDiv() { + if (!this.divs.volume.visible) return null; + + return ( +
+ {this.getMute()} + {this.getVolumeSlider()} +
+ ); + } + + getSlider() { + if (this.ids.control.seek) { + return ( this.onSeek(value)} />); + } else if (this.ids.control.elapsed && this.ids.control.duration && this.state[this.ids.control.duration]) { + const value = Math.round(this.state[this.ids.control.elapsed] / this.state[this.ids.control.duration] * 100); + return (); + } else { + return null; + } + } + + getTimeDiv() { + if (!this.divs.time.visible) return null; + return ( +
+ {this.ids.control.elapsed ? (
{Utils.getTimeString(this.state[this.ids.control.elapsed])}
) : null} + {this.getSlider()} + {this.ids.control.duration ? (
{Utils.getTimeString(this.state[this.ids.control.duration])}
) : null} +
+ ); + } + + getRepeat() { + if (!this.ids.mode.repeat) return null; + let style; + let title; + if (this.state[this.ids.mode.repeat]) { + style = Object.assign({}, styles.control.repeat, {background: 'rgb(64, 238, 64)', color: 'white'}); + } else { + style = styles.control.repeat; + title = I18n.t('No repeat'); + } + let Icon; + if (this.state[this.ids.mode.repeat] === REPEAT.NONE || this.state[this.ids.mode.repeat] === REPEAT.ALL) { + title = title || I18n.t('Repeat mode: all'); + Icon = IconRepeatAll; + } else { + Icon = IconRepeatOne; + title = title || I18n.t('Repeat mode: one'); + } + + return (); + } + + getShuffle() { + if (!this.ids.mode.shuffle) return null; + let style; + if (this.state[this.ids.mode.shuffle]) { + style = Object.assign({}, styles.control.shuffle, {background: '#b6b6f3'}); + } else { + style = styles.control.shuffle; + } + + return (); + + } + + getControlsDiv() { + const state = this.state[this.ids.control.state]; + return (
+ {this.ids.buttons.prev ? () : null} + + {this.props.settings.showStop && this.ids.buttons.stop ? () : null} + {this.ids.buttons.next ? () : null} + {this.getShuffle()} + {this.getRepeat()} +
); + } + + getInfoDiv() { + if (!this.divs.info.visible) return null; + + return (
+ {this.ids.info.artist && this.state[this.ids.info.artist] ? (
{this.state[this.ids.info.artist]}
) : null} + {this.ids.info.album && this.state[this.ids.info.album] ? (
{this.state[this.ids.info.album]}
) : null} + {this.ids.info.title && this.state[this.ids.info.title] ? (
{this.state[this.ids.info.title]}
) : null} + {this.ids.info.title && this.state[this.ids.info.title] ? (
{this.state[this.ids.info.title]}
) : null} +
); + } + + getCoverDiv() { + if (!this.divs.cover.visible) return null; + + if (this.state[this.ids.info.cover]) { + const style = Object.assign({}, this.divs.cover.style, {backgroundImage: 'url(' + this.state[this.ids.info.cover] + ')'}); + return (
); + } else { + return ( +
+
+ +
+
+ ); + } + } + + getHeaderDiv() { + if (!this.divs.header.visible) return null; + return (
{this.name}
); + } + + generateContent() { + return [ + this.getHeaderDiv(), + this.getVolumeDiv(), + this.getCoverDiv(), + this.getInfoDiv(), + this.getTimeDiv(), + this.getControlsDiv() + ]; + } +} + +export default SmartDialogMedia; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogSettings.js b/src/src/Dialogs/SmartDialogSettings.js new file mode 100644 index 0000000..76610fa --- /dev/null +++ b/src/src/Dialogs/SmartDialogSettings.js @@ -0,0 +1,369 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIOselectNS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; +import CopyToClipboard from 'react-copy-to-clipboard'; + +import List from '@material-ui/core/List'; +import ListItem from '@material-ui/core/ListItem'; +import TextField from '@material-ui/core/TextField'; +import Button from '@material-ui/core/Button'; +import Dialog from '@material-ui/core/Dialog'; +import DialogActions from '@material-ui/core/DialogActions'; +import DialogContent from '@material-ui/core/DialogContent'; +import DialogContentText from '@material-ui/core/DialogContentText'; +import DialogTitle from '@material-ui/core/DialogTitle'; +import Toolbar from '@material-ui/core/Toolbar'; +import Paper from '@material-ui/core/Paper'; +import IconButton from '@material-ui/core/IconButton'; + +import {MdSave as OkIcon} from 'react-icons/md'; +import {MdContentCopy as CopyIcon} from 'react-icons/md'; + +import ColorPicker from '../basic-controls/react-color-picker/ColorPicker'; +import ImageSelector from '../basic-controls/react-image-selector/ImageSelector'; +import ChipsControl from '../basic-controls/react-info-controls/ChipsControl'; +import SelectControl from '../basic-controls/react-info-controls/SelectControl'; +import BoolControl from '../basic-controls/react-info-controls/BoolControl'; + +import SmartDialogGeneric from './SmartDialogGeneric'; +import Utils from '../Utils'; +import Theme from '../theme'; +import I18n from '../i18n'; + +const styles = { + descCopyIcon: { + position: 'absolute', + top: 0, + right: 0, + background: 'rgba(255,255,255,0.7)' + }, + descDivId: { + fontSize: 'smaller' + }, + descTitle: { + fontWeight: 'bold' + }, + descCopied: { + position: 'absolute', + top: 3, + right: 3, + background: 'white' + } + +}; +class SmartDialogSettings extends SmartDialogGeneric { + + // expected: + // settings - array of [{id, icon, color, ...}] + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + getImages: PropTypes.func, + dialogKey: PropTypes.string, + windowWidth: PropTypes.number, + settings: PropTypes.array.isRequired, + objectInfo: PropTypes.object, + onSave: PropTypes.func.isRequired, + onClose: PropTypes.func + }; + + constructor(props) { + super(props); + this.stateRx.changed = false; + this.stateRx.unsavedDialog = false; + this.stateRx.values = { + + }; + this.stateRx.images = []; + this.stateRx.anchorEl = null; + + this.props.settings.forEach(e => { + this.stateRx.values[e.name] = e.value === '__default__' ? '' : e.value; + }); + + // This is asynchronous + this.props.getImages && this.props.getImages(function(images) { + this.setState({images}); + }.bind(this)); + + this.dialogStyle = Theme.dialog.settingsBack; + + this.componentReady(); + } + + onClose() { + if (!super.mayClose()) return; + + if (!this.ignoreUnsaved && this.isChanged()) { + this.setState({unsavedDialog: true}); + } else { + super.onClose(true); + } + } + + onSave() { + const settings = {}; + this.props.settings.forEach(item => { + settings[item.name] = this.state.values[item.name]; + }); + this.props.onSave(settings); + this.ignoreUnsaved = true; + this.onClose(); + } + + handleWarningCancel = () => { + this.ignoreUnsaved = false; + this.click = Date.now(); + this.setState({unsavedDialog: false}); + }; + + handleWarningIgnore = () => { + this.ignoreUnsaved = true; + this.setState({unsavedDialog: false}); + this.click = 0; + this.onClose(); + }; + + handleText(name, ev) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = ev.target.value; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + + handleToggle(name, ev) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = ev ? ev.target.checked : !this.state.values[name]; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + + handleValue(name, value) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = value; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + + handleUploadImage(name, files, pictures) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = pictures[pictures.length - 1]; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + handleDropImage(name, file) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = file; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + + handleIcon(name, file) { + const newValue = {values: JSON.parse(JSON.stringify(this.state.values))}; + this.click = Date.now(); + newValue.values[name] = typeof file === 'object' ? file.data : file; + newValue.changed = this.isChanged(name, newValue.values[name]); + this.setState(newValue); + } + + onDelete() { + this.props.onSave(false); + this.ignoreUnsaved = true; + this.onClose(); + } + + isChanged(name, newVal) { + return !!this.props.settings.find(item => { + if (item.name === name) { + return newVal !== item.value; + } else { + return item.value !== this.state.values[item.name] + } + }); + } + + copyId(event) { + this.setState({anchorEl: event.currentTarget}); + setTimeout(() => { + this.setState({anchorEl: null}); + }, 2000); + } + + generateObjectInfo() { + if (this.props.settingsId) { + return ( + + + + + + {this.state.anchorEl ? () : null} +
{I18n.t('Name')}: {Utils.getObjectName(this.props.objects, this.props.settingsId)}
+
{I18n.t('Description')}: {Utils.getObjectName(this.props.objects, this.props.settingsId, null, null, true)}
+
ID: {this.props.settingsId}
+
); + } else { + return null; + } + } + + generateContent() { + const result = this.props.settings.map(function (e, i) { + const divider = i !== this.props.settings.length - 1 ? () : null; + + let item; + if (e.type === 'delete') { + item = (); + } else if (e.type === 'boolean') { + item = ( this.handleToggle(e.name)} + icon={e.icon} + language={I18n.getLanguage()} + value={this.state.values[e.name] || false} + />); + } else if (e.type === 'color') { + item = ( this.handleValue(e.name, color)} + />); + } else if (e.type === 'chips') { + item = ( this.handleValue(e.name, value)} + />); + } else if (e.type === 'select') { + item = ( this.handleValue(e.name, value)} + label={I18n.t(e.name)} + options={e.options} + />); + } else if (e.type === 'icon') { + item = ( this.handleIcon(e.name, file)} + textAccepted={I18n.t('All files will be accepted')} + textRejected={I18n.t('Some files will be rejected')} + textWaiting={I18n.t('Drop some files here or click...')} + />); + } else if (e.type === 'image') { + item = ( this.handleDropImage(e.name, file)} + textAccepted={I18n.t('All files will be accepted')} + textRejected={I18n.t('Some files will be rejected')} + textWaiting={I18n.t('Drop some files here or click...')} + />); + } else if (e.type === 'number') { + // input field + item = ( this.handleText(e.name, ev)} + margin="normal" + />); + } else { + // input field + item = ( this.handleText(e.name, ev)} + margin="normal" + />); + } + + if (0 && divider) { + return [item, divider]; + } else { + return ({item}); + } + }.bind(this)); + + result.push(this.generateObjectInfo()); + + return [ + ( +

{this.props.name}

+ +
), + ({result}) + ]; + } + + getAdditionalElements() { + return ( + {I18n.t('Ignore changes?')} + + {I18n.t('Changes are not saved.')} + + + + + + ); + } +} + +export default SmartDialogSettings; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogSlider.js b/src/src/Dialogs/SmartDialogSlider.js new file mode 100644 index 0000000..6164760 --- /dev/null +++ b/src/src/Dialogs/SmartDialogSlider.js @@ -0,0 +1,440 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; +import {FaAngleDoubleUp as IconUp} from 'react-icons/fa'; +import {FaAngleDoubleDown as IconDown} from 'react-icons/fa'; +import {TiLightbulb as IconLamp} from 'react-icons/ti'; +import {MdStop as IconStop} from 'react-icons/md' +import {darken} from '@material-ui/core/styles/colorManipulator'; +import Button from '@material-ui/core/Button'; + +import Theme from '../theme'; +import I18n from '../i18n'; +import SmartDialogGeneric from './SmartDialogGeneric'; + +class SmartDialogSlider extends SmartDialogGeneric { + // expected: + + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string, + windowWidth: PropTypes.number, + + onClose: PropTypes.func, + + onStop: PropTypes.func, + onToggle: PropTypes.func, + + onValueChange: PropTypes.func, + startValue: PropTypes.number, + startToggleValue: PropTypes.bool, + type: PropTypes.number + }; + static types = { + value: 0, + dimmer: 1, + blinds: 2 + }; + + static buttonStyle = { + position: 'absolute', + left: 'calc(50% - 2em)', + height: '1.3em', + width: '4em', + borderRadius: '1em', + background: 'white', + border: '1px solid #b5b5b5', + paddingTop: '0.1em', + fontSize: '2em', + textAlign: 'center', + cursor: 'pointer', + boxShadow: '0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12)' + }; + static buttonStopStyle = { + position: 'absolute', + left: 'calc(50% + 6em)', + bottom: '4.5em', + height: '2em', + width: '2.5em' + }; + static sliderStyle = { + position: 'absolute', + zIndex: 11, + width: 200, + border: '1px solid #b5b5b5', + borderRadius: '2em', + overflow: 'hidden', + background: 'white', + cursor: 'pointer', + boxShadow: '0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12)', + height: 'calc(100% - 12em - 48px)', + top: 'calc(4em + 48px)', + left: 'calc(50% - 100px)' + }; + + constructor(props) { + super(props); + this.stateRx.value = this.externalValue2localValue(this.props.startValue || 0); + this.stateRx.toggleValue = this.props.startToggleValue || false; + this.onMouseMoveBind = this.onMouseMove.bind(this); + this.onMouseUpBind = this.onMouseUp.bind(this); + this.lastControl = 0; + + this.refSlider = React.createRef(); + + this.type = this.props.type || SmartDialogSlider.types.dimmer; + this.step = this.props.step || 20; + this.button = { + time: 0, + name: '', + timer: null, + timeUp: 0 + }; + this.closeOnPaperClick = true; // used in generic + this.componentReady(); + } + + componentWillReceiveProps(nextProps) { + if (nextProps.startValue !== this.state.value && !this.mouseDown && Date.now() - this.lastControl > 1000) { + this.setState({value: nextProps.startValue}); + } + if (nextProps.startToggleValue !== undefined && nextProps.startToggleValue !== this.state.toggleValue) { + this.setState({toggleValue: nextProps.startToggleValue}); + } + } + + eventToValue(e) { + const pageY = e.touches ? e.touches[e.touches.length - 1].clientY : e.clientY; + + let value = 100 - Math.round((pageY - this.top) / this.height * 100); + + if (value > 100) { + value = 100; + } else if (value < 0) { + value = 0; + } + this.setState({value}); + if (Date.now() - this.lastControl > 200 && this.type !== SmartDialogSlider.types.blinds) { + this.lastControl = Date.now(); + this.props.onValueChange && this.props.onValueChange(this.localValue2externalValue(this.state.value)); + } + } + + onMouseMove(e) { + e.preventDefault(); + e.stopPropagation(); + this.eventToValue(e); + } + + onMouseDown(e) { + e.preventDefault(); + e.stopPropagation(); + + this.mouseDown = true; + + if (!this.height) { + if (this.refSlider.current) { + this.height = this.refSlider.current.offsetHeight; + this.top = this.refSlider.current.offsetTop; + } else { + return; + } + } + + this.eventToValue(e); + + document.addEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.addEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + } + + localValue2externalValue(value) { + if (this.props.min !== undefined && this.props.max !== undefined) { + return value * (this.props.max - this.props.min) / 100 + this.props.min; + } else { + return value; + } + } + + externalValue2localValue(value) { + if (this.props.min !== undefined && this.props.max !== undefined) { + return ((value - this.props.min) / (this.props.max - this.props.min)) * 100; + } else { + return value; + } + } + + onMouseUp(e) { + e.preventDefault(); + e.stopPropagation(); + this.click = Date.now(); + this.mouseDown = false; + console.log('Stopped'); + document.removeEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.removeEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + + this.lastControl = Date.now(); + this.props.onValueChange && this.props.onValueChange(this.localValue2externalValue(this.state.value)); + } + + getTopButtonName() { + switch (this.props.type) { + case SmartDialogSlider.types.blinds: + return ; + + case SmartDialogSlider.types.dimmer: + return ; + + default: + if (this.props.max !== undefined) { + return this.props.max + (this.props.unit || ''); + } else { + return I18n.t('ON'); + } + } + } + + getBottomButtonName() { + switch (this.props.type) { + case SmartDialogSlider.types.blinds: + return ; + + case SmartDialogSlider.types.dimmer: + return ; + + default: + + if (this.props.min !== undefined) { + return this.props.min + (this.props.unit || ''); + } else { + return I18n.t('OFF'); + } + } + } + + onButtonDown(e, buttonName) { + e && e.stopPropagation(); + if (Date.now() - this.button.time < 50) return; + if (this.button.timer) { + clearTimeout(this.button.timer); + } + this.button.name = buttonName; + this.button.time = Date.now(); + this.button.timer = setTimeout(() => { + this.button.timer = null; + let value; + switch (this.button.name) { + case 'top': + value = 100; + break; + + case 'bottom': + value = 0; + break; + default: + break; + } + this.setState({value}); + this.props.onValueChange && this.props.onValueChange(this.localValue2externalValue(value)); + }, 400); + } + + onButtonUp(e) { + e && e.stopPropagation(); + if (Date.now() - this.button.timeUp < 100) { + if (this.button.timer) { + clearTimeout(this.button.timer); + this.button.timer = null; + } + } else{ + console.log('on Button UP: ' + (Date.now() - this.button.timeUp)); + this.button.timeUp = Date.now(); + + if (this.button.timer) { + clearTimeout(this.button.timer); + this.button.timer = null; + let value = this.state.value; + switch (this.button.name) { + case 'top': + if (value % this.step === 0) { + value += this.step; + } else{ + value += this.step - (value % this.step); + } + break; + + case 'bottom': + if (value % this.step === 0) { + value -= this.step; + } else { + value -= value % this.step; + } + break; + default: + break; + } + if (value > 100) { + value = 100; + } else if (value < 0) { + value = 0; + } + this.setState({value}); + this.props.onValueChange && this.props.onValueChange(this.localValue2externalValue(value)); + } + this.click = Date.now(); + } + } + + getSliderColor() { + if (this.props.type === SmartDialogSlider.types.blinds) { + return undefined; + } else if (this.props.type === SmartDialogSlider.types.dimmer) { + const val = this.state.value; + return darken(Theme.palette.lampOn, 1 - (val / 70 + 0.3)); + } else { + return Theme.slider.background; + } + } + + onStop(e) { + e && e.preventDefault(); + e && e.stopPropagation(); + this.setState({toast: I18n.t('sent')}); + this.props.onStop && this.props.onStop(); + } + + onToggle(e) { + e && e.preventDefault(); + e && e.stopPropagation(); + this.props.onToggle && this.props.onToggle(); + } + + getValueText() { + let unit = '%'; + if (this.props.type !== SmartDialogSlider.types.blinds && this.props.type !== SmartDialogSlider.types.dimmer) { + unit = (this.props.unit || ''); + } + if (this.props.min !== undefined && this.props.max !== undefined) { + return (this.state.value * (this.props.max - this.props.min) / 100 + this.props.min).toFixed() + unit; + } else { + return this.state.value + unit; + } + } + + getToggleButton() { + if (!this.props.onToggle) return null; + const style = Object.assign({}, SmartDialogSlider.buttonStopStyle, this.state.toggleValue ? {background: Theme.palette.lampOn} : {}); + return ( + ); + } + + getStopButton() { + if (!this.props.onStop) return null; + + return ( + ); + } + + generateContent() { + let sliderStyle = { + position: 'absolute', + width: '100%', + left: 0, + height: (this.props.type === SmartDialogSlider.types.blinds ? 100 - this.state.value : this.state.value) + '%', + background: this.props.background || this.getSliderColor() + }; + if (true || !this.mouseDown) { + sliderStyle.transitionProperty = 'height'; + sliderStyle.transitionDuration = '0.3s'; + } + + let handlerStyle = {position: 'absolute', + width: '2em', + height: '0.3em', + left: 'calc(50% - 1em)', + background: 'white', + borderRadius: '0.4em' + }; + + if (this.props.type === SmartDialogSlider.types.blinds) { + sliderStyle.top = 0; + handlerStyle.bottom = '0.4em'; + sliderStyle.backgroundImage = 'linear-gradient(0deg, #949494 4.55%, #c9c9c9 4.55%, #c9c9c9 50%, #949494 50%, #949494 54.55%, #c9c9c9 54.55%, #c9c9c9 100%)'; + sliderStyle.backgroundSize = '44px 44px'; + sliderStyle.backgroundPosition = 'center bottom'; + } else { + sliderStyle.bottom = 0; + handlerStyle.top = '0.4em'; + } + + return [ + (
this.onButtonDown(e, 'top')} + onMouseDown={e => this.onButtonDown(e, 'top')} + onTouchEnd={this.onButtonUp.bind(this)} + onMouseUp={this.onButtonUp.bind(this)} + onClick={e => e.stopPropagation()} + style={Object.assign({}, SmartDialogSlider.buttonStyle, {top: '1.3em'})} className="dimmer-button">{this.getTopButtonName()}
), + (
e.stopPropagation()} + style={SmartDialogSlider.sliderStyle}> +
+
+
+
+ {this.getValueText()} +
+
), + (
this.onButtonDown(e, 'bottom')} + onMouseDown={e => this.onButtonDown(e, 'bottom')} + onTouchEnd={this.onButtonUp.bind(this)} + onMouseUp={this.onButtonUp.bind(this)} + onClick={e => e.stopPropagation()} + style={Object.assign({}, SmartDialogSlider.buttonStyle, {bottom: '1.8em'})} className="dimmer-button">{this.getBottomButtonName()}
), + this.getStopButton(), + this.getToggleButton() + ]; + } +} + +export default SmartDialogSlider; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogThermostat.js b/src/src/Dialogs/SmartDialogThermostat.js new file mode 100644 index 0000000..8c2bf76 --- /dev/null +++ b/src/src/Dialogs/SmartDialogThermostat.js @@ -0,0 +1,215 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import PropTypes from 'prop-types'; +import I18n from '../i18n'; +import ThermostatControl from '../basic-controls/react-nest-thermostat/src/react-nest-thermostat'; +import Button from '@material-ui/core/Button'; +import SmartDialogGeneric from './SmartDialogGeneric'; + +class SmartDialogThermostat extends SmartDialogGeneric { + // expected: + + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string.isRequired, + windowWidth: PropTypes.number, + onClose: PropTypes.func.isRequired, + + objects: PropTypes.object, + states: PropTypes.object, + onValueChange: PropTypes.func, + startValue: PropTypes.number.isRequired, + actualValue: PropTypes.number, + }; + + static buttonBoostStyle = { + position: 'absolute', + left: 'calc(50% - 2em)', + height: '1.3em', + width: '4em', + borderRadius: '1em', + background: 'white', + border: '1px solid #b5b5b5', + paddingTop: '0.1em', + fontSize: '2em', + textAlign: 'center', + cursor: 'pointer', + boxShadow: '0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12)' + }; + // expected: + // startValue + // actualValue + // onValueChange + // onClose + // objects + // states + constructor(props) { + super(props); + this.stateRx.value = props.startValue || 0; + this.stateRx.boostValue = props.boostValue; + + this.min = props.min; + if (this.min > props.actualValue) { + this.min = props.actualValue + } + if (this.min > props.startValue) { + this.min = props.startValue + } + this.max = props.max; + if (this.max < props.actualValue) { + this.max = props.actualValue + } + if (this.max < props.startValue) { + this.max = props.startValue + } + + this.onMouseMoveBind = this.onMouseMove.bind(this); + this.onMouseUpBind = this.onMouseUp.bind(this); + this.onMouseDownBind = this.onMouseDown.bind(this); + + this.refPanel = React.createRef(); + this.svgControl = null; + this.componentReady(); + } + + componentDidMount() { + super.componentDidMount(); + this.svgControl = this.refPanel.current.getElementsByTagName('svg')[0]; + this.svgWidth = this.svgControl.clientWidth; + this.svgHeight = this.svgControl.clientHeight; + this.svgCenterX = this.svgWidth / 2; + this.svgCenterY = this.svgHeight / 2; + this.svgRadius = this.svgCenterX > this.svgCenterY ? this.svgCenterY : this.svgCenterX; + this.rect = this.svgControl.getBoundingClientRect(); + + this.svgControl.addEventListener('mousedown', this.onMouseDownBind, {passive: false, capture: true}); + this.svgControl.addEventListener('touchstart', this.onMouseDownBind, {passive: false, capture: true}); + } + + static roundValue(value, round) { + round = round || 0.5; + return Math.round(value / round) * round; + } + posToTemp(x, y) { + let h; + if (x < 0) { + h = Math.atan2(y, -x) * 180 / Math.PI; + if (y > 0) { + h = 180 - h; + } else{ + h = 180 - h; + } + } else { + h = Math.atan2(y, x) * 180 / Math.PI; + } + h = h * -1; + if (h < 0) h += 360; + h = 360 - h; + // owr sector + // 60 => 100% + // 120 => 0% + // 270 => 50% + if (h > 60 && h < 90) { + h = 60; + } + if (h > 90 && h < 120) { + h = 120; + } + if (h < 90) { + h += 360; + } + h -= 120; + h /= 360 - 60; + return SmartDialogThermostat.roundValue((this.max - this.min) * h + this.min); + } + + eventToValue(e, checkRadius) { + let pageY = e.touches ? e.touches[e.touches.length - 1].clientY : e.pageY; + let pageX = e.touches ? e.touches[e.touches.length - 1].clientX : e.pageX; + const x = pageX - this.rect.left - this.svgCenterX; + const y = pageY - this.rect.top - this.svgCenterY; + if (checkRadius) { + const radius = Math.sqrt(x * x + y * y); + if (radius > this.svgRadius * 1.1) { + return false; + } + } + + this.setState({value: this.posToTemp(x, y)}); + + return true; + } + + onMouseMove(e) { + e.preventDefault(); + e.stopPropagation(); + this.eventToValue(e); + } + + onMouseDown(e) { + e.preventDefault(); + e.stopPropagation(); + + if (this.eventToValue(e, true)) { + document.addEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.addEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.addEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + } else { + this.onClose(); + } + } + + onMouseUp(e) { + e.preventDefault(); + e.stopPropagation(); + this.click = Date.now(); + document.removeEventListener('mousemove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true}); + document.removeEventListener('touchmove', this.onMouseMoveBind, {passive: false, capture: true}); + document.removeEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true}); + + this.props.onValueChange && this.props.onValueChange(this.state.value); + } + + onBoostMode() { + this.props.onBoostToggle && this.props.onBoostToggle(!this.state.boostValue); + this.setState({boostValue: !this.state.boostValue}); + } + + generateContent() { + return (
+ {this.state.boostValue !== null && this.state.boostValue !== undefined ? + () : null} + +
); + } +} + +export default SmartDialogThermostat; \ No newline at end of file diff --git a/src/src/Dialogs/SmartDialogURL.js b/src/src/Dialogs/SmartDialogURL.js new file mode 100644 index 0000000..dae7d48 --- /dev/null +++ b/src/src/Dialogs/SmartDialogURL.js @@ -0,0 +1,193 @@ +/** + * Copyright 2018 bluefox + * + * Licensed under the Creative Commons Attribution-NonCommercial License, Version 4.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by-nc/4.0/legalcode.txt + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ +import React from 'react'; +import { withStyles } from '@material-ui/core/styles'; +import PropTypes from 'prop-types'; +import Paper from '@material-ui/core/Paper'; + +import SmartDialogGeneric from './SmartDialogGeneric'; + +const HEIGHT_TITLE = 64; +const HEIGHT_IFRAME = 300; + +const styles = { + 'header-div': { + width: 'calc(100% - 1em)', + position: 'relative', + marginBottom: 16 + }, + 'title-div': { + width: 'calc(100% - 1em)', + position: 'relative', + fontWeight: 'bold', + fontSize: 20, + marginBottom: 16, + }, + 'title-text': { + color: 'black' + }, + + 'iframe-div': { + width: 'calc(100% - 1em)', + minHeight: HEIGHT_IFRAME, + height: 'calc(100% - ' + HEIGHT_TITLE + 'px)' + }, + iframe: { + width: '100%', + height: '100%', + border: 0 + }, + 'image-img': { + width: '100%', + height: '100%', + objectFit: 'contain' + }, + +}; + +class SmartDialogURL extends SmartDialogGeneric { + // expected: + static propTypes = { + name: PropTypes.oneOfType([ + PropTypes.string, + PropTypes.object + ]), + dialogKey: PropTypes.string.isRequired, + windowWidth: PropTypes.number, + onClose: PropTypes.func.isRequired, + objects: PropTypes.object, + states: PropTypes.object, + onCollectIds: PropTypes.func, + settings: PropTypes.object, + image: PropTypes.bool + }; + + constructor(props) { + super(props); + + this.ids = this.props.ids; + + this.setMaxHeight(); + this.dialogStyle = {overflowY: 'auto'}; + this.stateRx.url = this.getUrl(this.props.settings.background); + + if (this.props.settings.fullWidth) { + this.dialogStyle = {width: 'calc(100% - 4rem)', maxWidth: 'calc(100% - 4rem)', left: '2rem'}; + } + + this.componentReady(); + } + + getUrl(url) { + let _url; + if (this.props.image && url) { + if (url.indexOf('?') !== -1) { + _url = url + '&ts=' + Date.now(); + } else { + _url = url + '?ts=' + Date.now(); + } + return _url; + } else { + return url; + } + } + + setMaxHeight(states) { + let maxHeight = 0; + states = states || this.state; + + this.divs = { + 'title': {height: HEIGHT_TITLE, visible: !!this.props.settings.title}, + 'iframe': {height: HEIGHT_IFRAME, visible: true} + }; + + // calculate height + for (const name in this.divs) { + if (this.divs.hasOwnProperty(name) && this.divs[name].visible) { + maxHeight += this.divs[name].height + 16; + } + } + + if (this.dialogStyle.maxHeight !== maxHeight) { + this.dialogStyle = {maxHeight: maxHeight}; + } + } + + updateUrl() { + if (this.props.image) { + this.setState({url: this.getUrl(this.props.settings.background)}); + } + } + + componentDidMount () { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + if (this.props.settings.updateInDialog || this.props.settings.update) { + this.interval = setInterval(() => this.updateUrl(), this.props.settings.updateInDialog || this.props.settings.update); + } + } + + componentWillUnmount() { + if (this.interval) { + clearInterval(this.interval); + this.interval = null; + } + } + + onOpenNewWindow() { + if (this.props.settings.background) { + const win = window.open(this.props.settings.background, '_blank'); + win.focus(); + } + } + + getTitleDiv() { + const classes = this.props.classes; + let title = this.props.settings.title; + + if (title) { + return (
+
{title}
+
); + } else { + return null; + } + } + + getIFrameDiv() { + const style = {height: 'calc(100% - ' + (this.props.settings.title ? HEIGHT_TITLE : '0') + 'px)'}; + if (!this.props.image && this.state.url) { + return ( this.onOpenNewWindow()} className={this.props.classes['iframe-div']} style={style}> +