Initial commit
33
.gitignore
vendored
Normal file
@ -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
|
12
.npmignore
Normal file
@ -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
|
7
.travis.yml
Normal file
@ -0,0 +1,7 @@
|
||||
os:
|
||||
- linux
|
||||
language: node_js
|
||||
node_js:
|
||||
- '6'
|
||||
- '8'
|
||||
- '10'
|
91
LICENSE
Normal file
@ -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.
|
117
README.md
Normal file
@ -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 <dogafox@gmail.com>
|
||||
|
||||
Commercial use is not allowed without permission.
|
BIN
admin/material.png
Normal file
After Width: | Height: | Size: 4.1 KiB |
10
admin/material.svg
Normal file
@ -0,0 +1,10 @@
|
||||
<svg width="225" height="225" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Created by bluefox -->
|
||||
<g>
|
||||
<ellipse fill="#2979ff" stroke="#2979ff" stroke-width="1.5" cx="112.9" cy="114" rx="112" ry="112"/>
|
||||
<ellipse fill="#40c4ff" stroke-width="1.5" cx="112.900006" cy="113.999995" rx="73.684216" ry="73.684216"
|
||||
stroke="#40c4ff"/>
|
||||
<ellipse fill="#ffffff" stroke-width="1.5" cx="112.900003" cy="114" rx="33.578948" ry="33.578948"
|
||||
stroke="#ffffff"/>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 520 B |
18
appveyor.yml
Normal file
@ -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'
|
283
gulpfile.js
Normal file
@ -0,0 +1,283 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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']);
|
BIN
img/screenshot1.png
Normal file
After Width: | Height: | Size: 2.3 MiB |
232
io-package.json
Normal file
@ -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 <dogafox@gmail.com>"
|
||||
],
|
||||
"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": {}
|
||||
}
|
||||
]
|
||||
}
|
54
package.json
Normal file
@ -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 <dogafox@gmail.com>"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
}
|
21
src/.gitignore
vendored
Normal file
@ -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*
|
1901
src/README.md
Normal file
BIN
src/img_backup/faviconIO.ico
Normal file
After Width: | Height: | Size: 31 KiB |
BIN
src/img_backup/homekit.png
Normal file
After Width: | Height: | Size: 13 MiB |
BIN
src/img_backup/leaves_autumn.jpg
Normal file
After Width: | Height: | Size: 5.3 MiB |
BIN
src/img_backup/leaves_green.jpg
Normal file
After Width: | Height: | Size: 6.5 MiB |
BIN
src/img_backup/leaves_red.jpg
Normal file
After Width: | Height: | Size: 375 KiB |
BIN
src/img_backup/lemon.jpg
Normal file
After Width: | Height: | Size: 1.2 MiB |
BIN
src/img_backup/macarons.jpg
Normal file
After Width: | Height: | Size: 228 KiB |
BIN
src/img_backup/wall_brick.jpg
Normal file
After Width: | Height: | Size: 1.3 MiB |
BIN
src/img_backup/wood.jpg
Normal file
After Width: | Height: | Size: 925 KiB |
47
src/package.json
Normal file
@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "material-app",
|
||||
"version": "0.2.3",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@ctrl/tinycolor": "^2.2.1",
|
||||
"@material-ui/core": "^3.3.1",
|
||||
"@material-ui/lab": "^3.0.0-alpha.21",
|
||||
"@svgr/cli": "^3.1.0",
|
||||
"classnames": "^2.2.6",
|
||||
"keycode": "^2.2.0",
|
||||
"material-ui-slider-label": "https://git.spacen.net/tariqwest/material-ui-slider-label/tarball/master",
|
||||
"moment": "^2.22.2",
|
||||
"moment-timezone": "^0.5.21",
|
||||
"react": "^16.6.0",
|
||||
"react-beautiful-dnd": "^9.0.2",
|
||||
"react-camera": "^0.1.3",
|
||||
"react-color": "^2.14.1",
|
||||
"react-copy-to-clipboard": "^5.0.1",
|
||||
"react-dom": "^16.6.0",
|
||||
"react-dropzone": "^6.2.4",
|
||||
"react-flexbox-grid": "^2.1.2",
|
||||
"react-fullscreen": "^0.1.0",
|
||||
"react-i18next": "^8.1.0",
|
||||
"react-icons": "^3.2.2",
|
||||
"react-image-crop": "^6.0.1",
|
||||
"react-images-upload": "^1.2.3",
|
||||
"react-moment": "^0.8.2",
|
||||
"react-native-i18n": "^2.0.15",
|
||||
"react-scripts": "^2.0.5",
|
||||
"typeface-roboto": "^0.0.54"
|
||||
},
|
||||
"homepage": "./",
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test --env=jsdom",
|
||||
"eject": "react-scripts eject",
|
||||
"svgr": "node node_modules/@svgr/cli/bin/svgr --no-semi -d ./src/icons/ ./src/icons/"
|
||||
},
|
||||
"browserslist": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not ie <= 11",
|
||||
"not op_mini all"
|
||||
]
|
||||
}
|
BIN
src/public/favicon.ico
Normal file
After Width: | Height: | Size: 353 KiB |
48
src/public/index.html
Normal file
@ -0,0 +1,48 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<!--
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
-->
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||
|
||||
<!-- Chrome, Firefox OS and Opera -->
|
||||
<meta name="theme-color" class="theme-color" content="#3f51b5">
|
||||
<!-- Windows Phone -->
|
||||
<meta name="msapplication-navbutton-color" class="theme-color" content="#3f51b5">
|
||||
<!-- iOS Safari -->
|
||||
<meta name="apple-mobile-web-app-status-bar-style" class="theme-color" content="#3f51b5">
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is added to the
|
||||
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
|
||||
-->
|
||||
<link href='vendor/fonts/roboto-woff.css' rel='stylesheet' type='text/css'>
|
||||
<link href="manifest.json" rel="manifest">
|
||||
<link href="favicon.ico" rel="shortcut icon">
|
||||
<script type="text/javascript" src="_socket/info.js"></script>
|
||||
<script type="text/javascript" src="vendor/socket.io.js"></script>
|
||||
<script type="text/javascript" src="vendor.js"></script>
|
||||
<title>Material - yunkong2</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
You need to enable JavaScript to run this app.
|
||||
</noscript>
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
74
src/public/iob.css
Normal file
@ -0,0 +1,74 @@
|
||||
.iob-icon {
|
||||
display: inline-block;
|
||||
width: 2rem;
|
||||
height: 1.8rem;
|
||||
border-radius: 0.4rem;
|
||||
text-align: center;
|
||||
padding-top: 0.2rem;
|
||||
float: right;
|
||||
}
|
||||
|
||||
.dimmer-button:active:hover {
|
||||
-webkit-transform: scale(0.9);
|
||||
-moz-transform: scale(0.9);
|
||||
-ms-transform: scale(0.9);
|
||||
-o-transform: scale(0.9);
|
||||
transform: scale(0.9);
|
||||
}
|
||||
|
||||
/* menu selected */
|
||||
.selected {
|
||||
background: #3f51b5 !important;
|
||||
}
|
||||
.selected span {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
/* scrollbar */
|
||||
*::-webkit-scrollbar-track {
|
||||
background-color: #ccc;
|
||||
}
|
||||
*::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
background-color: #ccc;
|
||||
}
|
||||
*::-webkit-scrollbar-thumb {
|
||||
background-color: #575757;
|
||||
}
|
||||
|
||||
/* ----------------- indicator-working --------------------------- */
|
||||
@-webkit-keyframes rotating /* Safari and Chrome */ {
|
||||
from {
|
||||
-webkit-transform: rotate(0deg);
|
||||
-o-transform: rotate(0deg);
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
-webkit-transform: rotate(360deg);
|
||||
-o-transform: rotate(360deg);
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
@keyframes rotating {
|
||||
from {
|
||||
-ms-transform: rotate(0deg);
|
||||
-moz-transform: rotate(0deg);
|
||||
-webkit-transform: rotate(0deg);
|
||||
-o-transform: rotate(0deg);
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
-ms-transform: rotate(360deg);
|
||||
-moz-transform: rotate(360deg);
|
||||
-webkit-transform: rotate(360deg);
|
||||
-o-transform: rotate(360deg);
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
.indicator-working {
|
||||
-webkit-animation: rotating 2s linear infinite;
|
||||
-moz-animation: rotating 2s linear infinite;
|
||||
-ms-animation: rotating 2s linear infinite;
|
||||
-o-animation: rotating 2s linear infinite;
|
||||
animation: rotating 2s linear infinite;
|
||||
}
|
15
src/public/manifest.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "yunkong2 Material",
|
||||
"name": "Mobile interface",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"start_url": "./index.html",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#e7e7e7"
|
||||
}
|
1411
src/public/vendor/conn.js
vendored
Normal file
1057
src/public/vendor/detector.js
vendored
Normal file
202
src/public/vendor/fonts/LICENSE.txt
vendored
Normal file
@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
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.
|
BIN
src/public/vendor/fonts/Roboto-Black.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-BlackItalic.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Bold.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-BoldItalic.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Italic.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Light.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-LightItalic.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Medium.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-MediumItalic.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Regular.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Regular.woff2
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Regular1-latin-ext.woff2
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Regular1-latin.woff2
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-Thin.ttf
vendored
Normal file
BIN
src/public/vendor/fonts/Roboto-ThinItalic.ttf
vendored
Normal file
56
src/public/vendor/fonts/roboto-woff.css
vendored
Normal file
@ -0,0 +1,56 @@
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu72xKOzY.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu5mxKOzY.woff2) format('woff2');
|
||||
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek-ext */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu7mxKOzY.woff2) format('woff2');
|
||||
unicode-range: U+1F00-1FFF;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4WxKOzY.woff2) format('woff2');
|
||||
unicode-range: U+0370-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu7WxKOzY.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu7GxKOzY.woff2) format('woff2');
|
||||
unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(https://fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxK.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
29
src/public/vendor/fonts/roboto.css
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(Roboto-Regular.ttf) format('ttf');
|
||||
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: italic;
|
||||
font-weight: 400;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(Roboto-Italic.ttf) format('ttf');
|
||||
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(Roboto-Bold.ttf) format('ttf');
|
||||
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
|
||||
}
|
||||
@font-face {
|
||||
font-family: 'Roboto';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
src: local('Roboto'), local('Roboto-Regular'), url(Roboto-BoldItalic.ttf) format('ttf');
|
||||
unicode-range: U+0460-052F, U+20B4, U+2DE0-2DFF, U+A640-A69F;
|
||||
}
|
4
src/public/vendor/socket.io.js
generated
vendored
Normal file
97
src/src/App.css
Normal file
@ -0,0 +1,97 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
.App {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.App-logo {
|
||||
animation: App-logo-spin infinite 20s linear;
|
||||
height: 80px;
|
||||
}
|
||||
|
||||
.App-header {
|
||||
/* background-color: #222;*/
|
||||
height: 150px;
|
||||
padding: 20px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.App-intro {
|
||||
font-size: large;
|
||||
}
|
||||
|
||||
@keyframes App-logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.corner:hover {
|
||||
border-width: 0 32px 32px 0 !important;
|
||||
}
|
||||
|
||||
.edit-buttons:hover {
|
||||
background: rgba(200, 200, 200, 0.8) !important;
|
||||
color: black !important;
|
||||
}
|
||||
|
||||
.small-visibility-button:hover {
|
||||
background: #ff6a5b;
|
||||
}
|
||||
|
||||
/* The animation code */
|
||||
@keyframes back-red {
|
||||
0% {
|
||||
background-color: red;
|
||||
}
|
||||
50% {
|
||||
background-color: red;
|
||||
}
|
||||
100% {
|
||||
background-color: white;
|
||||
}
|
||||
}
|
||||
|
||||
.just-enabled-disabled-1 {
|
||||
background-color: white;
|
||||
animation-name: back-red;
|
||||
animation-duration: 2s;
|
||||
}
|
||||
|
||||
.just-enabled-disabled-2 {
|
||||
background-color: white;
|
||||
animation-name: back-red;
|
||||
animation-duration: 2s;
|
||||
}
|
||||
|
||||
.menu-selected-bright span {
|
||||
color: #1c8fe0 !important;
|
||||
}
|
||||
|
||||
.menu-selected-dark span {
|
||||
color: #3cc1ff !important;
|
||||
}
|
||||
|
||||
.menu-text-bright span {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
.menu-text-dark span {
|
||||
color: black !important;
|
||||
}
|
1439
src/src/App.js
Normal file
8
src/src/App.test.js
Normal file
@ -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(<App />, div);
|
||||
});
|
1523
src/src/Connection.js
Normal file
575
src/src/Dialogs/SmartDialogColor.js
Normal file
@ -0,0 +1,575 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (
|
||||
<Button key="onoff-button"
|
||||
variant="fab"
|
||||
color="primary"
|
||||
aria-label="mute"
|
||||
title={this.state.on ? I18n.t('Off') : I18n.t('On')}
|
||||
style={style}
|
||||
onClick={this.onToggle.bind(this)}
|
||||
>
|
||||
<IconLight/>
|
||||
</Button>);
|
||||
}
|
||||
|
||||
getColorModeButton() {
|
||||
if (!this.props.modeTemperature || !this.props.modeRGB) return null;
|
||||
const style = Object.assign(
|
||||
{},
|
||||
styles.buttonColor,
|
||||
this.state.tempMode ? styles.buttonRgb : styles.buttonTemp);
|
||||
return (
|
||||
<Button key="color-mode-button"
|
||||
variant="fab"
|
||||
color="primary"
|
||||
aria-label="mute"
|
||||
title={this.state.tempMode ? I18n.t('HUE') : I18n.t('Color temperature')}
|
||||
style={style}
|
||||
onClick={this.onSwitchColorMode.bind(this)}
|
||||
>
|
||||
{this.state.tempMode ? (<IconRGB/>) : (<IconTemp/>)}
|
||||
</Button>);
|
||||
}
|
||||
|
||||
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 [(
|
||||
<div key="color-dialog" ref={this.refColor}
|
||||
className={this.props.classes.div}
|
||||
style={{
|
||||
width: this.colorWidth || '20rem',
|
||||
left: 'calc(50% - ' + (this.colorWidth ? (this.colorWidth / 2) + 'px' : '10rem') + ')'
|
||||
}}>
|
||||
<img ref={this.refColorImage}
|
||||
alt="color"
|
||||
src={this.state.tempMode ? this.imageCT : ColorsImg}//{ColorsImg}this.rgb || SmartDialogColor.createCT(600)}
|
||||
onMouseDown={this.onMouseDown.bind(this)}
|
||||
onTouchStart={this.onMouseDown.bind(this)}
|
||||
className={this.props.classes.colorCircle}/>
|
||||
<div ref={this.refColorCursor}
|
||||
className={this.props.classes.cursor}
|
||||
style={{
|
||||
background: this.state.tempMode ? UtilsColors.rgb2string(UtilsColors.temperatureToRGB(this.state.temperature)) : this.state.color,
|
||||
top: pos.y + this.colorTop + (pos.y > 0 ? 0 : -HANDLER_SIZE),
|
||||
left: pos.x + this.colorLeft + (pos.x > 0 ? 0 : -HANDLER_SIZE),
|
||||
}}>
|
||||
</div>
|
||||
</div>),
|
||||
this.props.useDimmer ? (<div style={styles.dimmerSlider} key="dimmer">
|
||||
<ColorSaturation
|
||||
hue={this.getHue()}
|
||||
saturation={this.state.dimmer}
|
||||
onChange={this.onDimmerChanged.bind(this)
|
||||
}/>
|
||||
</div>) : null,
|
||||
this.getOnOffButton(),
|
||||
this.getColorModeButton()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartDialogColor);
|
195
src/src/Dialogs/SmartDialogGeneric.js
Normal file
@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (<Button variant="fab"
|
||||
aria-label={I18n.t('close')}
|
||||
onClick={() => this.onClose(true)}
|
||||
style={Theme.dialog.closeButton}>
|
||||
<CloseIcon />
|
||||
</Button>)
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
setDialogStyle(style) {
|
||||
this.dialogStyle = style || {};
|
||||
this.forceUpdate();
|
||||
}
|
||||
|
||||
render() {
|
||||
return (<div key={this.props.dialogKey + '-dialog'}
|
||||
ref={this.refModal}
|
||||
onClick={() => this.onClose()}
|
||||
style={Theme.dialog.back}>
|
||||
<Paper onClick={this.onClick.bind(this)}
|
||||
style={Object.assign({}, Theme.dialog.inner, this.dialogStyle)}
|
||||
>
|
||||
{this.generateContent()}
|
||||
<Snackbar
|
||||
key={this.props.dialogKey + '-toast'}
|
||||
anchorOrigin={{vertical: 'top', horizontal: 'right'}}
|
||||
open={!!this.state.toast}
|
||||
onClick={this.handleToastClose.bind(this)}
|
||||
onClose={this.handleToastClose.bind(this)}
|
||||
autoHideDuration={4000}
|
||||
ContentProps={{
|
||||
'aria-describedby': 'message-id',
|
||||
}}
|
||||
message={<span id="message-id">{this.state.toast}</span>}
|
||||
/>
|
||||
{this.showCloseButton()}
|
||||
</Paper>
|
||||
|
||||
{this.getAdditionalElements && this.getAdditionalElements()}
|
||||
|
||||
</div>);
|
||||
}
|
||||
}
|
||||
|
||||
//export default withStyles(styles)(SmartDialogGeneric);
|
||||
export default SmartDialogGeneric;
|
186
src/src/Dialogs/SmartDialogInfo.js
Normal file
@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 ? (<ListItem key={e.id + '_div'} style={Theme.dialog.divider}/>) : null;
|
||||
|
||||
let item;
|
||||
|
||||
if (e.common && e.common.write) {
|
||||
if (e.common.type === 'boolean') {
|
||||
// switch
|
||||
if (e.common.read !== false) {
|
||||
item = (<BoolControl
|
||||
key={this.props.dialogKey + '-' + e.id + '-control'}
|
||||
label={e.name}
|
||||
value={this.state[e.id]}
|
||||
language={I18n.getLanguage()}
|
||||
icon={e.icon}
|
||||
onChange={() => this.handleToggle(e.id)}
|
||||
/>);
|
||||
} else { // button: read = false, write = true
|
||||
item = (<div key={this.props.dialogKey + '-' + e.id + '-control'}
|
||||
style={{width: '100%', textAlign: 'center'}}>
|
||||
<Button variant="contained" style={{minWidth: '50%'}} onClick={event => this.handleButton(event, e.id)}>{e.name}</Button>
|
||||
</div>);
|
||||
}
|
||||
} else
|
||||
if (e.common.type === 'number' && e.common.min !== undefined && e.common.max !== undefined && e.common.max - e.common.min < 5000) {
|
||||
// slider
|
||||
item = [(<Typography key={this.props.dialogKey + '-' + e.id + '-title'}>{e.name} - {this.state[e.id] ? this.state[e.id].val : '?'}{e.unit}</Typography>),
|
||||
(<Slider
|
||||
key={this.props.dialogKey + '-' + e.id + '-control'}
|
||||
min={e.common.min}
|
||||
max={e.common.max}
|
||||
step={((e.common.max - e.common.min) / 100)}
|
||||
value={this.state[e.id].val}
|
||||
aria-labelledby={e.name}
|
||||
style={{width: 'calc(100% - 20px)', marginLeft: 10}}
|
||||
onChange={(event, value) => this.handleValue(e.id, value)}
|
||||
/*label={
|
||||
<div style={styles.labelStyleOuter}>
|
||||
<div style={styles.labelStyleInner}>
|
||||
{this.state[e.id].val}
|
||||
</div>
|
||||
</div>
|
||||
}*/
|
||||
/>)];
|
||||
} else {
|
||||
// input field
|
||||
item = (<InputControl
|
||||
key={this.props.dialogKey + '-' + e.id + '-title'}
|
||||
type={e.common && e.common.type === 'number' ? 'number' : 'text'}
|
||||
icon={e.icon}
|
||||
label={e.name + (e.unit ? ' (' + e.unit.trim() + ')' : '')}
|
||||
min={e.common.min}
|
||||
max={e.common.max}
|
||||
value={this.state[e.id]}
|
||||
onChange={value => this.handleValue(e.id, value)}
|
||||
/>);
|
||||
}
|
||||
} else {
|
||||
if (e.common && e.common.type === 'boolean') {
|
||||
item = (<BoolControl
|
||||
key={this.props.dialogKey + '-' + e.id + '-control'}
|
||||
label={e.name}
|
||||
value={this.state[e.id]}
|
||||
language={I18n.getLanguage()}
|
||||
/>);
|
||||
} else {
|
||||
item = (
|
||||
<InfoControl
|
||||
key={this.props.dialogKey + '-' + e.id + '-control'}
|
||||
label={e.name}
|
||||
unit={e.unit || ''}
|
||||
value={this.state[e.id]}
|
||||
language={I18n.getLanguage()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (divider) {
|
||||
return [item, divider];
|
||||
} else {
|
||||
return item;
|
||||
}
|
||||
});
|
||||
return [
|
||||
(<h4 key={this.props.points[0].id + '_info_header'} style={Theme.dialog.header}>{this.props.name}</h4>),
|
||||
(<List key={this.props.points[0].id + '_info_list'} style={Theme.dialog.list}>{result}</List>)
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogInfo;
|
159
src/src/Dialogs/SmartDialogKnob.js
Normal file
@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (
|
||||
<Button key={this.props.dialogKey + '-mute-button'}
|
||||
variant="fab"
|
||||
color="primary"
|
||||
aria-label="mute"
|
||||
title={this.state.muteValue ? I18n.t('unmute') : I18n.t('mute')}
|
||||
style={style}
|
||||
onClick={this.onMute.bind(this)}
|
||||
className="mute-button">
|
||||
{this.state.muteValue ? (<IconVolume0/>) : (<IconVolume100/>)}
|
||||
</Button>);
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
return [
|
||||
(<KnobControl
|
||||
style={{left: 'calc(50% - 6em)', marginTop: '2em', width: '12em', height: '12em', position: 'absolute'}}
|
||||
value={this.localValue2externalValue(this.state.value)}
|
||||
onChange={this.onValueChanged.bind(this)}
|
||||
parent={this}
|
||||
/>),
|
||||
this.getMuteButton()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogKnob;
|
652
src/src/Dialogs/SmartDialogMedia.js
Normal file
@ -0,0 +1,652 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (<Slider value={this.state[this.ids.volume.actual] || 0} style={styles.volume.slider} onChange={(event, value) => this.onVolume(value)} />);
|
||||
} else if (this.ids.volume.actual) {
|
||||
return (<Slider value={this.state[this.ids.volume.actual] || 0} style={styles.volume.slider} disabled />);
|
||||
} 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 (
|
||||
<Button variant="fab" mini
|
||||
title={title}
|
||||
onClick={this.onToggleMute.bind(this)}
|
||||
style={Object.assign({}, styles.volume.mute, {background, color})}
|
||||
aria-label={text}>
|
||||
<Icon />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
getVolumeDiv() {
|
||||
if (!this.divs.volume.visible) return null;
|
||||
|
||||
return (
|
||||
<div key={this.key + 'tile-volume'} style={this.divs.volume.style}>
|
||||
{this.getMute()}
|
||||
{this.getVolumeSlider()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getSlider() {
|
||||
if (this.ids.control.seek) {
|
||||
return (<Slider value={this.state[this.ids.control.seek] || 0} style={styles.time.slider} onChange={(event, value) => 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 (<Slider value={value || 0} disabled style={styles.time.slider} />);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getTimeDiv() {
|
||||
if (!this.divs.time.visible) return null;
|
||||
return (
|
||||
<div key={this.key + 'tile-time'} style={this.divs.time.style}>
|
||||
{this.ids.control.elapsed ? (<div style={styles.time.elapsed}>{Utils.getTimeString(this.state[this.ids.control.elapsed])}</div>) : null}
|
||||
{this.getSlider()}
|
||||
{this.ids.control.duration ? (<div style={styles.time.duration}>{Utils.getTimeString(this.state[this.ids.control.duration])}</div>) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (<Button variant="fab" mini onClick={() => this.onRepeat()} style={style} title={title} aria-label="repeat">
|
||||
<Icon/>
|
||||
</Button>);
|
||||
}
|
||||
|
||||
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 (<Button variant="fab" mini onClick={() => this.onShuffle()} title={I18n.t('Shuffle mode')} style={style} aria-label="shuffle">
|
||||
<IconShuffle/>
|
||||
</Button>);
|
||||
|
||||
}
|
||||
|
||||
getControlsDiv() {
|
||||
const state = this.state[this.ids.control.state];
|
||||
return (<div key={this.key + 'tile-control'} style={this.divs.control.style}>
|
||||
{this.ids.buttons.prev ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.prev)} style={styles.control.prev} aria-label="prev"><IconPrev/></Button>) : null}
|
||||
<Button variant="fab" mini
|
||||
color={state ? 'primary' : 'secondary'}
|
||||
onClick={() => this.onButton(this.state[this.ids.control.state] ? this.ids.buttons.pause : this.ids.buttons.play)}
|
||||
style={state ? styles.control.pause : styles.control.play} aria-label="play pause">
|
||||
{state ? (<IconPause/>) : (<IconPlay/>)}
|
||||
</Button>
|
||||
{this.props.settings.showStop && this.ids.buttons.stop ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.stop)} style={Object.assign({}, styles.control.stop, this.state.stop ? {color: 'red'} : {})} aria-label="stop"><IconStop/></Button>) : null}
|
||||
{this.ids.buttons.next ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.next)} style={styles.control.prev} aria-label="next"><IconNext/></Button>) : null}
|
||||
{this.getShuffle()}
|
||||
{this.getRepeat()}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getInfoDiv() {
|
||||
if (!this.divs.info.visible) return null;
|
||||
|
||||
return (<div key={this.key + 'tile-info'} style={this.divs.info.style}>
|
||||
{this.ids.info.artist && this.state[this.ids.info.artist] ? (<div style={styles.info.artist}>{this.state[this.ids.info.artist]}</div>) : null}
|
||||
{this.ids.info.album && this.state[this.ids.info.album] ? (<div style={styles.info.album}>{this.state[this.ids.info.album]}</div>) : null}
|
||||
{this.ids.info.title && this.state[this.ids.info.title] ? (<div style={styles.info.title}>{this.state[this.ids.info.title]}</div>) : null}
|
||||
{this.ids.info.title && this.state[this.ids.info.title] ? (<div style={styles.info.title}>{this.state[this.ids.info.title]}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
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 (<div style={style}/>);
|
||||
} else {
|
||||
return (
|
||||
<div style={this.divs.cover.style}>
|
||||
<div key={this.key + 'icon'} style={styles.cover.img}>
|
||||
<IconNote width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
getHeaderDiv() {
|
||||
if (!this.divs.header.visible) return null;
|
||||
return (<div style={this.divs.header.style}>{this.name}</div>);
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
return [
|
||||
this.getHeaderDiv(),
|
||||
this.getVolumeDiv(),
|
||||
this.getCoverDiv(),
|
||||
this.getInfoDiv(),
|
||||
this.getTimeDiv(),
|
||||
this.getControlsDiv()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogMedia;
|
369
src/src/Dialogs/SmartDialogSettings.js
Normal file
@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (<Paper key={'object-info'} style={{margin: 5, padding: 5, position: 'relative'}} elevation={1}>
|
||||
<CopyToClipboard
|
||||
text={this.props.settingsId}>
|
||||
<IconButton
|
||||
title={I18n.t('Copy ID to clipboard')}
|
||||
onClick={this.copyId.bind(this)}
|
||||
style={styles.descCopyIcon}>
|
||||
<CopyIcon width={Theme.iconSize} height={Theme.iconSize}/>
|
||||
</IconButton>
|
||||
</CopyToClipboard>
|
||||
{this.state.anchorEl ? (<Button variant="outlined" disabled style={styles.descCopied}>{I18n.t('Copied')}</Button>) : null}
|
||||
<div><span style={styles.descTitle}>{I18n.t('Name')}: </span>{Utils.getObjectName(this.props.objects, this.props.settingsId)}</div>
|
||||
<div style={styles.descDivId}><span style={styles.descTitle}>{I18n.t('Description')}: </span>{Utils.getObjectName(this.props.objects, this.props.settingsId, null, null, true)}</div>
|
||||
<div style={styles.descDivId}><span style={styles.descTitle}>ID: </span>{this.props.settingsId}</div>
|
||||
</Paper>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
const result = this.props.settings.map(function (e, i) {
|
||||
const divider = i !== this.props.settings.length - 1 ? (<ListItem key={e.id + '_div'} style={Theme.dialog.divider}/>) : null;
|
||||
|
||||
let item;
|
||||
if (e.type === 'delete') {
|
||||
item = (<Button
|
||||
color="secondary"
|
||||
variant="contained"
|
||||
key={this.props.dialogKey + '-delete'}
|
||||
onClick={() => this.onDelete()}
|
||||
>{I18n.t('Delete')}</Button>);
|
||||
} else if (e.type === 'boolean') {
|
||||
item = (<BoolControl
|
||||
key={this.props.dialogKey + '-' + e.name + '-bool'}
|
||||
label={I18n.t(e.name)}
|
||||
onChange={() => this.handleToggle(e.name)}
|
||||
icon={e.icon}
|
||||
language={I18n.getLanguage()}
|
||||
value={this.state.values[e.name] || false}
|
||||
/>);
|
||||
} else if (e.type === 'color') {
|
||||
item = (<ColorPicker
|
||||
key={this.props.dialogKey + '-' + e.name + '-color'}
|
||||
name={I18n.t(e.name)}
|
||||
color={this.state.values[e.name] || ''}
|
||||
onChange={color => this.handleValue(e.name, color)}
|
||||
/>);
|
||||
} else if (e.type === 'chips') {
|
||||
item = (<ChipsControl
|
||||
label={I18n.t(e.name)}
|
||||
textAdd={I18n.t('add indicator')}
|
||||
value={this.state.values[e.name] || ''}
|
||||
onChange={value => this.handleValue(e.name, value)}
|
||||
/>);
|
||||
} else if (e.type === 'select') {
|
||||
item = (<SelectControl
|
||||
value={this.state.values[e.name] || ''}
|
||||
onChange={value => this.handleValue(e.name, value)}
|
||||
label={I18n.t(e.name)}
|
||||
options={e.options}
|
||||
/>);
|
||||
} else if (e.type === 'icon') {
|
||||
item = (<ImageSelector
|
||||
maxSize={15000}
|
||||
icons={true}
|
||||
height={64}
|
||||
accept={'image/jpeg, image/png, image/gif, image/svg+xml'}
|
||||
key={this.props.dialogKey + '-' + e.name + '-icon'}
|
||||
label={e.label ? I18n.t(e.label) : I18n.t(e.name)}
|
||||
image={this.state.values[e.name]}
|
||||
maxHeight={200}
|
||||
onUpload={file => 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 = (<ImageSelector
|
||||
maxSize={6000000}
|
||||
images={this.state.images}
|
||||
key={this.props.dialogKey + '-' + e.name + '-image'}
|
||||
label={e.label ? I18n.t(e.label) : I18n.t(e.name)}
|
||||
aspect={this.state.values.hasOwnProperty('doubleSize') ? (this.state.values.doubleSize ? 2 : 1) : e.aspect}
|
||||
maxHeight={200}
|
||||
image={this.state.values[e.name]}
|
||||
onUpload={file => 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 = (<TextField
|
||||
key={this.props.dialogKey + '-' + e.name + '-text'}
|
||||
id={e.name}
|
||||
label={I18n.t(e.name)}
|
||||
style={{width: '100%'}}
|
||||
type="number"
|
||||
inputProps={{min: e.min, max: e.max}}
|
||||
value={this.state.values[e.name] || ''}
|
||||
onChange={ev => this.handleText(e.name, ev)}
|
||||
margin="normal"
|
||||
/>);
|
||||
} else {
|
||||
// input field
|
||||
item = (<TextField
|
||||
key={this.props.dialogKey + '-' + e.name + '-text'}
|
||||
id={e.name}
|
||||
label={I18n.t(e.name)}
|
||||
style={{width: '100%'}}
|
||||
value={this.state.values[e.name] || ''}
|
||||
onChange={ev => this.handleText(e.name, ev)}
|
||||
margin="normal"
|
||||
/>);
|
||||
}
|
||||
|
||||
if (0 && divider) {
|
||||
return [item, divider];
|
||||
} else {
|
||||
return (<Paper key={this.props.dialogKey + '-' + e.name + '-paper'} style={{margin: 5, padding: 5}} elevation={1}>{item}</Paper>);
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
result.push(this.generateObjectInfo());
|
||||
|
||||
return [
|
||||
(<Toolbar key={this.props.dialogKey + '-toolbar'} >
|
||||
<h4 key={this.props.dialogKey + '-header'} style={Theme.dialog.header}>{this.props.name}</h4>
|
||||
<Button onClick={this.onSave.bind(this)} key={this.props.dialogKey + '-ok'} style={Theme.dialog.saveButton} disabled={!this.state.changed} variant="extendedFab" color="primary" aria-label="save"><OkIcon />{I18n.t('Save')}</Button>
|
||||
</Toolbar>),
|
||||
(<List key={this.props.dialogKey + '-list'} style={Theme.dialog.list}>{result}</List>)
|
||||
];
|
||||
}
|
||||
|
||||
getAdditionalElements() {
|
||||
return (<Dialog
|
||||
style={{zIndex: 2101}}
|
||||
open={this.state.unsavedDialog}
|
||||
aria-labelledby={I18n.t('Not saved!')}
|
||||
aria-describedby={I18n.t('Changes not saved!')}
|
||||
>
|
||||
<DialogTitle id="alert-dialog-title">{I18n.t('Ignore changes?')}</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText id="alert-dialog-description">{I18n.t('Changes are not saved.')}</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={this.handleWarningCancel.bind(this)} color="primary" autoFocus>{I18n.t('Stay edit')}</Button>
|
||||
<Button onClick={this.handleWarningIgnore.bind(this)} color="secondary">{I18n.t('Discard changes')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogSettings;
|
440
src/src/Dialogs/SmartDialogSlider.js
Normal file
@ -0,0 +1,440 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 <IconUp style={{color: 'black'}}/>;
|
||||
|
||||
case SmartDialogSlider.types.dimmer:
|
||||
return <IconLamp style={{color: Theme.palette.lampOn}} />;
|
||||
|
||||
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 <IconDown style={{color: 'black'}}/>;
|
||||
|
||||
case SmartDialogSlider.types.dimmer:
|
||||
return <IconLamp style={{color: 'black'}} />;
|
||||
|
||||
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 (
|
||||
<Button key={this.props.dialogKey + '-toggle-button'}
|
||||
variant="fab"
|
||||
color="primary"
|
||||
aria-label="on off"
|
||||
style={style}
|
||||
onClick={this.onToggle.bind(this)}
|
||||
className="dimmer-button">
|
||||
<IconLamp/>
|
||||
</Button>);
|
||||
}
|
||||
|
||||
getStopButton() {
|
||||
if (!this.props.onStop) return null;
|
||||
|
||||
return (
|
||||
<Button key={this.props.dialogKey + '-stop-button'}
|
||||
variant="fab"
|
||||
color="secondary"
|
||||
aria-label="stop"
|
||||
style={SmartDialogSlider.buttonStopStyle}
|
||||
onClick={this.onStop.bind(this)}
|
||||
className="dimmer-button">
|
||||
<IconStop/>
|
||||
</Button>);
|
||||
}
|
||||
|
||||
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 [
|
||||
(<div key={this.props.dialogKey + '-top-button'}
|
||||
onTouchStart={e => 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()}</div>),
|
||||
(<div key={this.props.dialogKey + '-slider'}
|
||||
ref={this.refSlider}
|
||||
onMouseDown={this.onMouseDown.bind(this)}
|
||||
onTouchStart={this.onMouseDown.bind(this)}
|
||||
onClick={e => e.stopPropagation()}
|
||||
style={SmartDialogSlider.sliderStyle}>
|
||||
<div style={sliderStyle}>
|
||||
<div style={handlerStyle} />
|
||||
</div>
|
||||
<div style={{position: 'absolute', top: 'calc(50% - 0.55em)', userSelect: 'none', width: '100%', textAlign: 'center', fontSize: '2em'}}>
|
||||
{this.getValueText()}
|
||||
</div>
|
||||
</div>),
|
||||
(<div key={this.props.dialogKey + '-bottom-button'}
|
||||
onTouchStart={e => 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()}</div>),
|
||||
this.getStopButton(),
|
||||
this.getToggleButton()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogSlider;
|
215
src/src/Dialogs/SmartDialogThermostat.js
Normal file
@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (<div ref={this.refPanel} style={{width: 'calc(100% - 1em)', height: '100%'}}>
|
||||
{this.state.boostValue !== null && this.state.boostValue !== undefined ?
|
||||
(<Button variant="contained" color={this.state.boostValue ? 'secondary' : ''} onClick={this.onBoostMode.bind(this)}
|
||||
style={{top: '1.3em'}}
|
||||
className="boost-button">{I18n.t('Boost')}
|
||||
</Button>) : null}
|
||||
<ThermostatControl
|
||||
minValue={this.min}
|
||||
maxValue={this.max}
|
||||
hvacMode={'heating'}
|
||||
ambientTemperature={this.props.actualValue}
|
||||
targetTemperature={this.state.value}
|
||||
/>
|
||||
</div>);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDialogThermostat;
|
193
src/src/Dialogs/SmartDialogURL.js
Normal file
@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 (<div key="title" className={classes['title-div']}>
|
||||
<div className={classes['title-text']}>{title}</div>
|
||||
</div>);
|
||||
} 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 (<Paper onClick={() => this.onOpenNewWindow()} className={this.props.classes['iframe-div']} style={style}>
|
||||
<iframe className={this.props.classes['iframe']} title={this.state.url} src={this.state.url}/>
|
||||
</Paper>);
|
||||
} else if (this.state.url) {
|
||||
return (<Paper key="image" style={style} onClick={() => this.onOpenNewWindow()} className={this.props.classes['iframe-div']}>
|
||||
<img className={this.props.classes['image-img']} alt="" src={this.state.url}/>
|
||||
</Paper>);
|
||||
}
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
return [
|
||||
this.getTitleDiv(),
|
||||
this.getIFrameDiv()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartDialogURL);
|
312
src/src/Dialogs/SmartDialogWarning.js
Normal file
@ -0,0 +1,312 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 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 DialogTitle from '@material-ui/core/DialogTitle';
|
||||
|
||||
import SmartDialogGeneric from './SmartDialogGeneric';
|
||||
import I18n from '../i18n';
|
||||
|
||||
const HEIGHT_HEADER = 64;
|
||||
const HEIGHT_ICON = 300;
|
||||
const HEIGHT_TITLE = 48;
|
||||
const HEIGHT_DATE = 48;
|
||||
const HEIGHT_INFO = 48;
|
||||
const HEIGHT_DESC = 120;
|
||||
|
||||
const styles = {
|
||||
'header-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16
|
||||
},
|
||||
'date-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16
|
||||
},
|
||||
'date-start': {
|
||||
},
|
||||
'date-end': {
|
||||
},
|
||||
'title-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
fontWeight: 'bold',
|
||||
fontSize: 20,
|
||||
marginBottom: 16
|
||||
},
|
||||
'title-text': {
|
||||
},
|
||||
'info-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16
|
||||
},
|
||||
'info-text': {
|
||||
},
|
||||
'icon-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16,
|
||||
cursor: 'pointer',
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center',
|
||||
height: HEIGHT_ICON
|
||||
},
|
||||
'desc-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16
|
||||
},
|
||||
'desc-text': {
|
||||
},
|
||||
'chart-dialog': {
|
||||
zIndex: 2101
|
||||
},
|
||||
'chart-dialog-paper': {
|
||||
width: 'calc(100% - 2em)',
|
||||
maxWidth: 'calc(100% - 2em)',
|
||||
height: 'calc(100% - 2em)',
|
||||
maxHeight: 'calc(100% - 2em)'
|
||||
},
|
||||
'chart-dialog-img': {
|
||||
width: '100%',
|
||||
},
|
||||
'chart-dialog-content': {
|
||||
width: 'calc(100% - 4em)',
|
||||
height: 'calc(100% - 4em)',
|
||||
cursor: 'pointer',
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center',
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
class SmartDialogWarning 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,
|
||||
ids: PropTypes.object.isRequired,
|
||||
settings: PropTypes.object
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.ids = this.props.ids;
|
||||
|
||||
for (const id in this.ids) {
|
||||
if (this.ids.hasOwnProperty(id) && this.ids[id]) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
if (this.ids[id] instanceof Array) {
|
||||
this.ids[id].forEach(i => this.subscribes.push(i));
|
||||
} else {
|
||||
this.subscribes.push(this.ids[id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.stateRx.chartOpened = false;
|
||||
|
||||
this.setMaxHeight();
|
||||
this.dialogStyle = {
|
||||
overflowY: 'auto'
|
||||
};
|
||||
|
||||
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.componentReady();
|
||||
}
|
||||
|
||||
setMaxHeight(states) {
|
||||
let maxHeight = 0;
|
||||
states = states || this.state;
|
||||
|
||||
this.divs = {
|
||||
'header': {height: HEIGHT_HEADER, visible: true},
|
||||
'icon': {height: HEIGHT_ICON, visible: true},
|
||||
'date': {height: HEIGHT_DATE, visible: true},
|
||||
'title': {height: HEIGHT_TITLE, visible: states && states[this.ids.title]},
|
||||
'info': {height: HEIGHT_INFO, visible: states && states[this.ids.info]},
|
||||
'desc': {height: HEIGHT_DESC, visible: states && states[this.ids.description]}
|
||||
};
|
||||
|
||||
// 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};
|
||||
}
|
||||
}
|
||||
|
||||
onUpdateTimer() {
|
||||
this.collectTimer = null;
|
||||
if (this.collectState) {
|
||||
this.setMaxHeight(this.collectState);
|
||||
this.setState(this.collectState);
|
||||
this.collectState = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.ids.title ||
|
||||
id === this.ids.info ||
|
||||
id === this.ids.start ||
|
||||
id === this.ids.description ||
|
||||
id === this.ids.end ||
|
||||
id === this.ids.icon) {
|
||||
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.warning) {
|
||||
const val = parseInt(state.val, 10) || 0;
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else {
|
||||
console.log(id + ' => ' + state.val);
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getHeaderDiv() {
|
||||
if (!this.divs.header.visible) return null;
|
||||
return (<div key="header" className={this.props.classes['header-div']}>{this.name}</div>);
|
||||
}
|
||||
|
||||
onOpenNewWindow() {
|
||||
if (this.ids.icon && this.state[this.ids.icon]) {
|
||||
const win = window.open(this.state[this.ids.icon], '_blank');
|
||||
win.focus();
|
||||
}
|
||||
}
|
||||
|
||||
getIconDiv() {
|
||||
if (!this.ids.icon || !this.state[this.ids.icon]) return null;
|
||||
const chart = this.state[this.ids.icon];
|
||||
|
||||
return [(<Paper key="icon"
|
||||
className={this.props.classes['icon-div']}
|
||||
style={{
|
||||
backgroundImage: 'url(' + chart + ')'
|
||||
}}
|
||||
onClick={() => this.setState({chartOpened: true})}> </Paper>),
|
||||
this.state.chartOpened ? (<Dialog
|
||||
key="chart-dialog"
|
||||
open={true}
|
||||
classes={{paper: this.props.classes['chart-dialog-paper']}}
|
||||
onClose={() => this.setState({chartOpened: false})}
|
||||
className={this.props.classes['chart-dialog']}
|
||||
aria-labelledby="alert-dialog-title"
|
||||
aria-describedby="alert-dialog-description"
|
||||
>
|
||||
<DialogTitle id="alert-dialog-title">{I18n.t('Chart')}</DialogTitle>
|
||||
<DialogContent className={this.props.classes['chart-dialog-content']}
|
||||
onClick={() => this.onOpenNewWindow()}
|
||||
style={{
|
||||
backgroundImage: 'url(' + chart + ')'
|
||||
}}
|
||||
>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => this.setState({chartOpened: false})} color="primary" autoFocus>{I18n.t('Close')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>) : null];
|
||||
}
|
||||
|
||||
getDateDiv() {
|
||||
const classes = this.props.classes;
|
||||
let start = this.ids.start && this.state[this.ids.start];
|
||||
let end = this.ids.end && this.state[this.ids.end];
|
||||
|
||||
return (<div key="date" className={classes['date-div']}>
|
||||
<div className={classes['date-start']}>{start + (end ? ' - ' + end : '')}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTitleDiv() {
|
||||
const classes = this.props.classes;
|
||||
let title = this.ids.title && this.state[this.ids.title];
|
||||
|
||||
return (<div key="title" className={classes['title-div']}>
|
||||
<div className={classes['title-text']}>{title}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getInfoDiv() {
|
||||
const classes = this.props.classes;
|
||||
let info = this.ids.info && this.state[this.ids.info];
|
||||
|
||||
return (<div key="info" className={classes['info-div']}>
|
||||
<div className={classes['info-text']}>{info}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getDescDiv() {
|
||||
const classes = this.props.classes;
|
||||
let info = this.ids.description && this.state[this.ids.description];
|
||||
|
||||
return (<div key="info" className={classes['desc-div']}>
|
||||
<div className={classes['desc-text']}>{info}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
return [
|
||||
this.getHeaderDiv(),
|
||||
this.getTitleDiv(),
|
||||
this.getDateDiv(),
|
||||
this.getInfoDiv(),
|
||||
this.getIconDiv(),
|
||||
this.getDescDiv()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartDialogWarning);
|
944
src/src/Dialogs/SmartDialogWeatherForecast.js
Normal file
@ -0,0 +1,944 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 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 DialogTitle from '@material-ui/core/DialogTitle';
|
||||
|
||||
import Utils from '../Utils';
|
||||
import SmartDialogGeneric from './SmartDialogGeneric';
|
||||
import I18n from '../i18n';
|
||||
|
||||
const HEIGHT_HEADER = 64;
|
||||
const HEIGHT_CURRENT = 200;
|
||||
const HEIGHT_DAY = 140;
|
||||
const HEIGHT_CHART = 160;
|
||||
|
||||
const styles = {
|
||||
'header-div': {
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16
|
||||
},
|
||||
'current-div': {
|
||||
height: HEIGHT_CURRENT,
|
||||
width: 'calc(100% - 1em)',
|
||||
position: 'relative',
|
||||
marginBottom: 16,
|
||||
overflow: 'hidden'
|
||||
},
|
||||
'currentIcon-div': {
|
||||
position: 'absolute',
|
||||
width: 128,
|
||||
height: 128,
|
||||
zIndex: 0,
|
||||
left: 3,
|
||||
top: 24
|
||||
},
|
||||
'currentIcon-icon': {
|
||||
width: '100%',
|
||||
zIndex: 0
|
||||
},
|
||||
'currentIcon-temperature': {
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
fontSize: 40,
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
textAlign: 'right',
|
||||
color: '#9c9c9c',
|
||||
top: 8,
|
||||
right: -50
|
||||
},
|
||||
'currentDate-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 2em)',
|
||||
top: 16,
|
||||
left: 16
|
||||
},
|
||||
'currentDate-date': {
|
||||
fontWeight: 'normal',
|
||||
display: 'inline-block',
|
||||
},
|
||||
'currentDate-location': {
|
||||
display: 'inline-block',
|
||||
position: 'absolute',
|
||||
textOverflow: 'ellipsis',
|
||||
width: 'calc(100% - 75px)',
|
||||
whiteSpace: 'nowrap',
|
||||
right: 0,
|
||||
textAlign: 'right'
|
||||
},
|
||||
'todayTemp-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
top: 35,
|
||||
maxWidth: 'calc(100% - 2em - 90px)',
|
||||
right: 16,
|
||||
textAlign: 'right'
|
||||
},
|
||||
'todayTemp-temperature': {
|
||||
},
|
||||
'todayTemp-temperatureMin': {
|
||||
},
|
||||
'todayTemp-temperatureMax': {
|
||||
fontWeight: 'bold'
|
||||
},
|
||||
'todayTemp-temperatureTitle': {
|
||||
},
|
||||
'todayTemp-temperatureValue': {
|
||||
},
|
||||
'todayTemp-precipitation': {
|
||||
},
|
||||
'todayTemp-precipitationTitle': {
|
||||
},
|
||||
'todayTemp-precipitationValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'todayTemp-pressure': {
|
||||
},
|
||||
'todayTemp-pressureTitle': {
|
||||
},
|
||||
'todayTemp-pressureValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'todayState-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 90px)',
|
||||
fontWeight: 'normal',
|
||||
bottom: 16,
|
||||
left: 118,
|
||||
textAlign: 'left',
|
||||
fontSize: 14
|
||||
},
|
||||
'todayState-wind': {
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
'todayState-windTitle': {
|
||||
},
|
||||
'todayState-windDir': {
|
||||
marginLeft: 2,
|
||||
},
|
||||
'todayState-windSpeed': {
|
||||
marginLeft: 2
|
||||
},
|
||||
'todayState-windIcon': {
|
||||
display: 'inline-block',
|
||||
marginLeft: 5
|
||||
},
|
||||
'todayState-windChill': {
|
||||
},
|
||||
'todayState-windChillTitle': {
|
||||
paddingRight: 5
|
||||
},
|
||||
'todayState-windChillValue': {
|
||||
},
|
||||
'todayState-humidity': {
|
||||
},
|
||||
'todayState-humidityTitle': {
|
||||
paddingRight: 5
|
||||
},
|
||||
'todayState-humidityValue': {
|
||||
},
|
||||
'todayState-state': {
|
||||
},
|
||||
'chart-div': {
|
||||
height: HEIGHT_CHART,
|
||||
width: 'calc(100% - 1em)',
|
||||
overflowX: 'hidden',
|
||||
overflowY: 'auto',
|
||||
marginBottom: 16,
|
||||
padding: '0 16px',
|
||||
cursor: 'pointer'
|
||||
},
|
||||
'chart-header': {
|
||||
width: '100%',
|
||||
fontSize: 16,
|
||||
paddingTop: 16,
|
||||
fontWeight: 'bold'
|
||||
},
|
||||
'chart-img': {
|
||||
width: 'calc(100% - 16px)',
|
||||
height: 'calc(100% - 40px)',
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center',
|
||||
},
|
||||
'chart-dialog': {
|
||||
zIndex: 2101
|
||||
},
|
||||
'chart-dialog-paper': {
|
||||
width: 'calc(100% - 4em)',
|
||||
maxWidth: 'calc(100% - 4em)',
|
||||
height: 'calc(100% - 4em)',
|
||||
maxHeight: 'calc(100% - 4em)',
|
||||
},
|
||||
'chart-dialog-content': {
|
||||
width: 'calc(100% - 5em)',
|
||||
height: 'calc(100% - 4em)',
|
||||
marginLeft: '1em',
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center',
|
||||
},
|
||||
|
||||
'days-div': {
|
||||
height: 'calc(100% - ' + HEIGHT_CURRENT + 'px - ' + HEIGHT_HEADER + 'px)',
|
||||
width: 'calc(100% - 1em)',
|
||||
overflowX: 'hidden',
|
||||
overflowY: 'auto'
|
||||
},
|
||||
'day-div': {
|
||||
height: HEIGHT_DAY,
|
||||
width: '100%',
|
||||
marginBottom: 16,
|
||||
position: 'relative'
|
||||
},
|
||||
'dayIcon-div': {
|
||||
position: 'absolute',
|
||||
width: 90,
|
||||
height: 90,
|
||||
zIndex: 0,
|
||||
left: 16,
|
||||
top: 30,
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center',
|
||||
},
|
||||
'dayIcon-icon': {
|
||||
width: '100%',
|
||||
zIndex: 0
|
||||
},
|
||||
'dayIcon-temperature': {
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
fontSize: 40,
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
textAlign: 'right',
|
||||
color: '#9c9c9c',
|
||||
top: 8,
|
||||
right: -50
|
||||
},
|
||||
'dayDate-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 2em)',
|
||||
top: 16,
|
||||
left: 16
|
||||
},
|
||||
'dayDate-date': {
|
||||
fontWeight: 'bold',
|
||||
display: 'inline-block',
|
||||
},
|
||||
'dayTemp-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
top: 35,
|
||||
maxWidth: 'calc(100% - 2em - 90px)',
|
||||
right: 16,
|
||||
textAlign: 'right'
|
||||
},
|
||||
'dayTemp-temperature': {
|
||||
},
|
||||
'dayTemp-temperatureMin': {
|
||||
},
|
||||
'dayTemp-temperatureMax': {
|
||||
fontWeight: 'bold'
|
||||
},
|
||||
'dayTemp-temperatureTitle': {
|
||||
},
|
||||
'dayTemp-temperatureValue': {
|
||||
},
|
||||
'dayTemp-precipitation': {
|
||||
},
|
||||
'dayTemp-precipitationTitle': {
|
||||
},
|
||||
'dayTemp-precipitationValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'dayTemp-humidity': {
|
||||
},
|
||||
'dayTemp-humidityTitle': {
|
||||
},
|
||||
'dayTemp-humidityValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'dayTemp-pressure': {
|
||||
},
|
||||
'dayTemp-pressureTitle': {
|
||||
},
|
||||
'dayTemp-pressureValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'dayState-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 90px)',
|
||||
fontWeight: 'normal',
|
||||
bottom: 16,
|
||||
left: 118,
|
||||
textAlign: 'left'
|
||||
},
|
||||
'dayState-wind': {
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
fontSize: 14
|
||||
},
|
||||
'dayState-windTitle': {
|
||||
},
|
||||
'dayState-windDir': {
|
||||
marginLeft: 2,
|
||||
},
|
||||
'dayState-windSpeed': {
|
||||
marginLeft: 2
|
||||
},
|
||||
'dayState-windIcon': {
|
||||
display: 'inline-block',
|
||||
marginLeft: 5,
|
||||
width: 16,
|
||||
maxHeight: 16
|
||||
},
|
||||
'dayState-windChill': {
|
||||
},
|
||||
'dayState-windChillTitle': {
|
||||
paddingRight: 5
|
||||
},
|
||||
'dayState-windChillValue': {
|
||||
},
|
||||
'dayState-state': {
|
||||
fontSize: 14
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
class SmartDialogWeatherForecast 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,
|
||||
ids: PropTypes.object.isRequired,
|
||||
settings: PropTypes.object
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.ids = this.props.ids;
|
||||
|
||||
for (const id in this.ids.current) {
|
||||
if (this.ids.current.hasOwnProperty(id) && this.ids.current[id]) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
if (this.ids.current[id] instanceof Array) {
|
||||
this.ids.current[id].forEach(i => this.subscribes.push(i));
|
||||
} else {
|
||||
this.subscribes.push(this.ids.current[id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let d = 0; d < this.ids.days.length; d++) {
|
||||
if (!this.ids.days[d]) continue;
|
||||
for (const id in this.ids.days[d]) {
|
||||
if (this.ids.days[d].hasOwnProperty(id) && this.ids.days[d][id]) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
this.subscribes.push(this.ids.days[d][id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.props.settings) {
|
||||
if (this.props.settings.tempID && this.subscribes.indexOf(this.props.settings.tempID) === -1) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
this.subscribes.push(this.props.settings.tempID);
|
||||
}
|
||||
if (this.props.settings.humidityID && this.subscribes.indexOf(this.props.settings.humidityID) === -1) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
this.subscribes.push(this.props.settings.humidityID);
|
||||
}
|
||||
}
|
||||
|
||||
this.stateRx.chartOpened = false;
|
||||
|
||||
this.setMaxHeight();
|
||||
|
||||
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.componentReady();
|
||||
}
|
||||
|
||||
setMaxHeight(states) {
|
||||
let maxHeight = 0;
|
||||
states = states || this.state;
|
||||
|
||||
this.divs = {
|
||||
'header': {height: HEIGHT_HEADER, visible: true},
|
||||
'current': {height: HEIGHT_CURRENT, visible: true},
|
||||
'chart': {height: HEIGHT_CHART,
|
||||
visible: states && states[this.ids.current.chart] && !states[this.ids.current.chart].match(/\.html$|\.htm/)}
|
||||
};
|
||||
for (let d = 0; d < this.ids.days.length; d++) {
|
||||
if (this.ids.days[d]) {
|
||||
this.divs['day' + d] = {height: HEIGHT_DAY, visible: true};
|
||||
}
|
||||
}
|
||||
// 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};
|
||||
}
|
||||
}
|
||||
|
||||
onUpdateTimer() {
|
||||
this.collectTimer = null;
|
||||
if (this.collectState) {
|
||||
this.setMaxHeight(this.collectState);
|
||||
this.setState(this.collectState);
|
||||
this.collectState = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
for (let d = 0; d < this.ids.days.length; d++) {
|
||||
if (!this.ids.days[d]) continue;
|
||||
if (id === this.ids.days[d].temperature ||
|
||||
id === this.ids.days[d].humidity ||
|
||||
id === this.ids.days[d].humidityMin ||
|
||||
id === this.ids.days[d].humidityMax ||
|
||||
id === this.ids.days[d].windChill ||
|
||||
id === this.ids.days[d].windSpeed ||
|
||||
id === this.ids.days[d].temperatureMin ||
|
||||
id === this.ids.days[d].temperatureMax ||
|
||||
id === this.ids.days[d].precipitation ||
|
||||
id === this.ids.days[d].pressure) {
|
||||
const val = Math.round(parseFloat(state.val));
|
||||
if (!isNaN(val)) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = val;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
}
|
||||
return;
|
||||
} else
|
||||
if (id === this.ids.days[d].icon ||
|
||||
id === this.ids.days[d].state) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
return;
|
||||
} else
|
||||
if (id === this.ids.days[d].icon ||
|
||||
id === this.ids.days[d].state ||
|
||||
id === this.ids.days[d].windIcon) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
return;
|
||||
} else if (id === this.ids.days[d].windDirection) {
|
||||
let dir = '';
|
||||
if (state && state.val !== null && state.val !== '' && state.val !== undefined && (typeof state.val === 'number' || parseInt(state.val, 10).toString() === state.val.toString())) {
|
||||
dir = I18n.t('wind_' + Utils.getWindDirection(state.val)).replace('wind_', '');
|
||||
} else {
|
||||
dir = state.val;
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = dir;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
return;
|
||||
} else if (id === this.ids.days[d].date) {
|
||||
let date = '';
|
||||
|
||||
if (state && state.val) {
|
||||
date = Utils.date2string(state.val) || '';
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = date;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (id === this.ids.current.temperature ||
|
||||
id === this.ids.current.humidity ||
|
||||
id === this.ids.current.windChill ||
|
||||
id === this.ids.current.windSpeed ||
|
||||
id === this.props.settings.tempID ||
|
||||
id === this.props.settings.humidityID ||
|
||||
id === this.ids.current.temperatureMin ||
|
||||
id === this.ids.current.temperatureMax ||
|
||||
id === this.ids.current.precipitation ||
|
||||
id === this.ids.current.pressure) {
|
||||
const val = Math.round(parseFloat(state.val));
|
||||
if (!isNaN(val)) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = val;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
}
|
||||
} else
|
||||
if (id === this.ids.current.icon ||
|
||||
id === this.ids.current.history ||
|
||||
id === this.ids.current.chart ||
|
||||
id === this.ids.current.state ||
|
||||
id === this.ids.current.windIcon) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else
|
||||
if (this.ids.current.location && this.ids.current.location.indexOf(id) !== -1) {
|
||||
this.collectState = this.collectState || {};
|
||||
if (state.val && state.val.replace(/[,.-]/g, '').trim()) {
|
||||
this.collectState.location = state.val || '';
|
||||
}
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else if (id === this.ids.current.windDirection) {
|
||||
let dir = '';
|
||||
if (state && state.val !== null && state.val !== '' && state.val !== undefined && (typeof state.val === 'number' || parseInt(state.val, 10).toString() === state.val.toString())) {
|
||||
dir = I18n.t('wind_' + Utils.getWindDirection(state.val)).replace('wind_', '');
|
||||
} else {
|
||||
dir = state.val;
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = dir;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else if (id === this.ids.current.date) {
|
||||
let date = '';
|
||||
|
||||
if (state && state.val) {
|
||||
date = Utils.date2string(state.val) || '';
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = date;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else {
|
||||
console.log(id + ' => ' + state.val);
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getHeaderDiv() {
|
||||
if (!this.divs.header.visible) return null;
|
||||
return (<div key="header" className={this.props.classes['header-div']}>{this.name}</div>);
|
||||
}
|
||||
|
||||
getDayIconDiv(d) {
|
||||
const classes = this.props.classes;
|
||||
const temp = this.ids.days[d].temperature && this.state[this.ids.days[d].temperature];
|
||||
const icon = this.ids.days[d].icon && this.state[this.ids.days[d].icon];
|
||||
|
||||
if (!temp && !icon) return null;
|
||||
|
||||
return (<div key={'dayIcon' + d} className={classes['dayIcon-div']}>
|
||||
{icon ? (<img className={classes['dayIcon-icon']} src={icon} alt={this.state[this.ids.days[d].state] || ''}/>) : null}
|
||||
{temp !== null && temp !== undefined ? (<div className={classes['dayIcon-temperature']}>{temp}°</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getDayDateDiv(d) {
|
||||
const classes = this.props.classes;
|
||||
let date = this.ids.days[d].date && this.state[this.ids.days[d].date];
|
||||
if (!date) {
|
||||
const now = new Date();
|
||||
now.setDate(now.getDate() + d);
|
||||
date = Utils.date2string(now);
|
||||
}
|
||||
|
||||
return (<div key={'location' + d} className={classes['dayDate-div']}>
|
||||
<div className={classes['dayDate-date']}>{date}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getDayWindDiv(d) {
|
||||
const classes = this.props.classes;
|
||||
let windChill = this.ids.days[d].windchill && this.state[this.ids.days[d].date];
|
||||
let windDir = this.ids.days[d].windDirection && this.state[this.ids.days[d].windDirection];
|
||||
if (windDir !== null && windDir !== undefined && (typeof windDir === 'number' || parseInt(windDir, 10) === windDir)) {
|
||||
windDir = I18n.t('wind_' + Utils.getWindDirection(windDir)).replace('wind_', '');
|
||||
}
|
||||
let windSpeed = this.ids.days[d].windSpeed && this.state[this.ids.days[d].windSpeed];
|
||||
let windIcon = this.ids.days[d].windIcon && this.state[this.ids.days[d].windIcon];
|
||||
|
||||
let state = this.ids.days[d].state && this.state[this.ids.days[d].state];
|
||||
|
||||
if (!state && !windChill && windChill !== 0 && !windDir && !windSpeed && windSpeed !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (<div key={'dayWind' + d} className={classes['dayState-div']}>
|
||||
|
||||
{windChill !== null && windChill !== undefined ?
|
||||
(<div key={'windChill' + d} className={classes['dayState-windChill']}>
|
||||
<span className={classes['dayState-windChillTitle']}>{I18n.t('Windchill')}: </span>
|
||||
<span className={classes['dayState-windChillValue']}>{windChill}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{(windDir !== null && windDir !== undefined) || (windSpeed !== null && windSpeed !== undefined) ?
|
||||
(<div key={'wind' + d} className={classes['dayState-wind']}>
|
||||
<span key={'windTitle' + d} className={classes['dayState-windTitle']}>{I18n.t('Wind')}:</span>
|
||||
{windIcon ? (<img className={classes['dayState-windIcon']} src={windIcon} alt="state"/>) : null}
|
||||
{windDir ? (<span className={classes['dayState-windDir']}>{windDir}</span>) : null}
|
||||
{windSpeed !== null && windSpeed !== undefined && !isNaN(windSpeed) ? (<span key={'daySpeed' + d} className={classes['dayState-windSpeed']}>{windSpeed}{this.props.windUnit}</span>) : null}
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{state ? (<div key={'state' + d} className={classes['dayState-state']}>{state}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getDayTempDiv(d) {
|
||||
const classes = this.props.classes;
|
||||
let tempMin = this.ids.days[d].temperatureMin && this.state[this.ids.days[d].temperatureMin];
|
||||
let tempMax = this.ids.days[d].temperatureMax && this.state[this.ids.days[d].temperatureMax];
|
||||
let precipitation = this.ids.days[d].precipitation && this.state[this.ids.days[d].precipitation];
|
||||
let pressure = this.ids.days[d].pressure && this.state[this.ids.days[d].pressure];
|
||||
let humidity = this.ids.days[d].humidity && this.state[this.ids.days[d].humidity];
|
||||
|
||||
if (!humidity && humidity !== 0 &&
|
||||
this.ids.current.humidity &&
|
||||
this.props.objects[this.ids.current.humidity] &&
|
||||
this.props.objects[this.ids.current.humidity].common &&
|
||||
this.props.objects[this.ids.current.humidity].common.role &&
|
||||
this.props.objects[this.ids.current.humidity].common.role.indexOf('forecast.0') !== -1) {
|
||||
humidity = this.state[this.ids.current.humidity];
|
||||
}
|
||||
if (!tempMin && tempMin !== 0 &&
|
||||
this.ids.current.temperatureMin) {
|
||||
const obj = this.props.objects[this.ids.current.temperatureMin];
|
||||
if (obj &&
|
||||
obj.common &&
|
||||
obj.common.role &&
|
||||
obj.common.role.indexOf('forecast.0') !== -1) {
|
||||
tempMin = this.state[this.ids.current.temperatureMin];
|
||||
}
|
||||
}
|
||||
if (!tempMax && tempMax !== 0 &&
|
||||
this.ids.current.temperatureMax) {
|
||||
const obj = this.props.objects[this.ids.current.temperatureMax];
|
||||
if (obj &&
|
||||
obj.common &&
|
||||
obj.common.role &&
|
||||
obj.common.role.indexOf('forecast.0') !== -1) {
|
||||
tempMax = this.state[this.ids.current.temperatureMax];
|
||||
}
|
||||
}
|
||||
|
||||
let temp;
|
||||
if (tempMin !== null && tempMin !== undefined &&
|
||||
tempMax !== null && tempMax !== undefined && tempMin !== tempMax) {
|
||||
temp = [
|
||||
(<span key="max" className={classes['dayTemp-temperatureMax']}>{tempMax}°</span>),
|
||||
(<span key="mid"> / </span>),
|
||||
(<span key="min" className={classes['dayTemp-temperatureMin']}>{tempMin}°</span>)
|
||||
];
|
||||
} else if (
|
||||
(tempMin !== null && tempMin !== undefined) ||
|
||||
(tempMax !== null && tempMax !== undefined)) {
|
||||
if (tempMin === null || tempMin === undefined) {
|
||||
tempMin = tempMax;
|
||||
}
|
||||
temp = (<span key="max" className={classes['dayTemp-temperatureMax']}>{tempMin}°</span>);
|
||||
}
|
||||
|
||||
if (!temp &&
|
||||
!precipitation && precipitation !== 0 &&
|
||||
!pressure && pressure !== 0 &&
|
||||
!humidity && humidity !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (<div key={'dayTemp' + d} className={classes['dayTemp-div']}>
|
||||
{temp !== null && temp !== undefined ?
|
||||
(<div key={'temp' + d} className={classes['dayTemp-temperature']}>
|
||||
<span className={classes['dayTemp-temperatureValue']}>{temp}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{precipitation !== null && precipitation !== undefined ?
|
||||
(<div key={'precipitation' + d} className={classes['dayTemp-precipitation']}>
|
||||
<span key={'windTitle' + d} className={classes['dayTemp-precipitationTitle']}>{I18n.t('Precip.')}:</span>
|
||||
<span className={classes['dayTemp-precipitationValue']}>{precipitation}%</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{humidity !== null && humidity !== undefined ?
|
||||
(<div key={'humidity' + d} className={classes['dayTemp-humidity']}>
|
||||
<span key={'windTitle' + d} className={classes['dayTemp-humidityTitle']}>{I18n.t('Humidity')}:</span>
|
||||
<span className={classes['dayTemp-humidityValue']}>{humidity}%</span>
|
||||
</div>)
|
||||
: null}
|
||||
{pressure !== null && pressure !== undefined ?
|
||||
(<div key={'pressure' + d} className={classes['dayTemp-pressure']}>
|
||||
<span key={'windTitle' + d} className={classes['dayTemp-pressureTitle']}>{I18n.t('Pressure')}:</span>
|
||||
<span className={classes['dayTemp-pressureValue']}>{pressure}{this.props.pressureUnit}</span>
|
||||
</div>)
|
||||
: null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getDayDiv(d) {
|
||||
if (!this.ids.days[d]) return null;
|
||||
let parts = [
|
||||
this.getDayIconDiv(d),
|
||||
this.getDayDateDiv(d),
|
||||
this.getDayWindDiv(d),
|
||||
this.getDayTempDiv(d),
|
||||
];
|
||||
if (!parts[0] && !parts[2] && !parts[3]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (<Paper key={'day' + d} className={this.props.classes['day-div']}>{parts}</Paper>);
|
||||
}
|
||||
|
||||
getCurrentIconDiv() {
|
||||
const classes = this.props.classes;
|
||||
let temp;
|
||||
temp = this.props.settings.tempID && this.state[this.props.settings.tempID];
|
||||
if (!temp && temp !== 0) {
|
||||
temp = this.ids.current.temperature && this.state[this.ids.current.temperature];
|
||||
}
|
||||
|
||||
return (<div key="todayIcon" className={classes['currentIcon-div']}>
|
||||
<img className={classes['currentIcon-icon']} src={this.state[this.ids.current.icon]} alt={this.state[this.ids.current.state] || ''}/>
|
||||
{temp !== null && temp !== undefined ? (<div className={classes['currentIcon-temperature']}>{temp}°</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getCurrentDateLocationDiv() {
|
||||
const classes = this.props.classes;
|
||||
let date = this.ids.current.date && this.state[this.ids.current.date];
|
||||
let location = this.props.settings.locationText;
|
||||
location = location || this.state.location;
|
||||
location = location || I18n.t('Weather');
|
||||
date = date || Utils.date2string(new Date());
|
||||
|
||||
return (<div key="location" className={classes['currentDate-div']}>
|
||||
<div className={classes['currentDate-date']}>{date},</div>
|
||||
<div className={classes['currentDate-location']}>{location}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTodayWindDiv() {
|
||||
const classes = this.props.classes;
|
||||
let windChill = this.ids.current.windchill && this.state[this.ids.current.date];
|
||||
let windDir = this.ids.current.windDirection && this.state[this.ids.current.windDirection];
|
||||
if (windDir !== null && windDir !== undefined && (typeof windDir === 'number' || parseInt(windDir, 10) === windDir)) {
|
||||
windDir = I18n.t('wind_' + Utils.getWindDirection(windDir)).replace('wind_', '');
|
||||
}
|
||||
let windSpeed = this.ids.current.windSpeed && this.state[this.ids.current.windSpeed];
|
||||
let windIcon = this.ids.current.windIcon && this.state[this.ids.current.windIcon];
|
||||
let humidity = this.props.settings.humidityID && this.state[this.props.settings.humidityID];
|
||||
if (!humidity && humidity !== 0) {
|
||||
humidity = this.ids.current.humidity && this.state[this.ids.current.humidity];
|
||||
}
|
||||
|
||||
let state = this.ids.current.state && this.state[this.ids.current.state];
|
||||
return (<div key="todayWind" className={classes['todayState-div']}>
|
||||
|
||||
{windChill !== null && windChill !== undefined ?
|
||||
(<div key="windChill" className={classes['todayState-windChill']}>
|
||||
<span className={classes['todayState-windChillTitle']}>{I18n.t('Windchill')}: </span>
|
||||
<span className={classes['todayState-windChillValue']}>{windChill}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{(windDir !== null && windDir !== undefined) || (windSpeed !== null && windSpeed !== undefined) ?
|
||||
(<div key="wind" className={classes['todayState-wind']}>
|
||||
<span key="windTitle" className={classes['todayState-windTitle']}>{I18n.t('Wind')}:</span>
|
||||
{windIcon ? (<img className={classes['todayState-windIcon']} src={windIcon} alt="state"/>) : null}
|
||||
{windDir ? (<span className={classes['todayState-windDir']}>{windDir}</span>) : null}
|
||||
{windSpeed !== null && windSpeed !== undefined && !isNaN(windSpeed) ? (<span key="windSpeed" className={classes['todayState-windSpeed']}>{windSpeed}{this.props.windUnit}</span>) : null}
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{humidity || humidity === 0 ?
|
||||
(<div key="humidity" className={classes['todayState-humidity']}>
|
||||
<span className={classes['todayState-humidityTitle']}>{I18n.t('Humidity')}: </span>
|
||||
<span className={classes['todayState-humidityValue']}>{humidity}%</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{state ? (<div key="state" className={classes['todayState-state']}>{state}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTodayTempDiv() {
|
||||
const classes = this.props.classes;
|
||||
let tempMin = this.ids.current.temperatureMin && this.state[this.ids.current.temperatureMin];
|
||||
let tempMax = this.ids.current.temperatureMax && this.state[this.ids.current.temperatureMax];
|
||||
let precipitation = this.ids.current.precipitation && this.state[this.ids.current.precipitation];
|
||||
let pressure = this.ids.current.pressure && this.state[this.ids.current.pressure];
|
||||
|
||||
let temp;
|
||||
if (tempMin !== null && tempMin !== undefined &&
|
||||
tempMax !== null && tempMax !== undefined) {
|
||||
temp = [
|
||||
(<span key="max" className={classes['todayTemp-temperatureMax']}>{tempMax}°</span>),
|
||||
(<span key="mid"> / </span>),
|
||||
(<span key="min" className={classes['todayTemp-temperatureMin']}>{tempMin}°</span>)
|
||||
];
|
||||
}
|
||||
|
||||
return (<div key="todayTemp" className={classes['todayTemp-div']}>
|
||||
{temp !== null && temp !== undefined ?
|
||||
(<div key="temp" className={classes['todayTemp-temperature']}>
|
||||
<span className={classes['todayTemp-temperatureValue']}>{temp}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{precipitation !== null && precipitation !== undefined ?
|
||||
(<div key="precipitation" className={classes['todayTemp-precipitation']}>
|
||||
<span key="windTitle" className={classes['todayTemp-precipitationTitle']}>{I18n.t('Precip.')}:</span>
|
||||
<span className={classes['todayTemp-precipitationValue']}>{precipitation}%</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{pressure !== null && pressure !== undefined ?
|
||||
(<div key="pressure" className={classes['todayTemp-pressure']}>
|
||||
<span key="windTitle" className={classes['todayTemp-pressureTitle']}>{I18n.t('Pressure')}:</span>
|
||||
<span className={classes['todayTemp-pressureValue']}>{pressure}{this.props.pressureUnit}</span>
|
||||
</div>)
|
||||
: null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getChartDiv() {
|
||||
const classes = this.props.classes;
|
||||
let chart = this.ids.current.chart && this.state[this.ids.current.chart];
|
||||
if (chart && chart.toLowerCase().match(/\.svg$|\.jpg$|\.jpeg$|\.gif$|\.png$/)) {
|
||||
if (chart.indexOf('?') === -1) {
|
||||
chart += '?ts=' + Date.now();
|
||||
} else {
|
||||
chart += '&ts=' + Date.now();
|
||||
}
|
||||
return [
|
||||
(<Paper key="chart" className={this.props.classes['chart-div']} onClick={() => this.setState({chartOpened: true})}>
|
||||
<div className={classes['chart-header']}>{I18n.t('Chart')}</div>
|
||||
<div className={classes['chart-img']} style={{
|
||||
backgroundImage: 'url(' + this.state[this.ids.current.chart] + ')'
|
||||
}}/>
|
||||
</Paper>),
|
||||
this.state.chartOpened ? (<Dialog
|
||||
key="chart-dialog"
|
||||
open={true}
|
||||
classes={{paper: this.props.classes['chart-dialog-paper']}}
|
||||
onClose={() => this.setState({chartOpened: false})}
|
||||
className={this.props.classes['chart-dialog']}
|
||||
aria-labelledby="alert-dialog-title"
|
||||
aria-describedby="alert-dialog-description"
|
||||
>
|
||||
<DialogTitle id="alert-dialog-title">{I18n.t('Chart')}</DialogTitle>
|
||||
<DialogContent className={this.props.classes['chart-dialog-content']}
|
||||
style={{backgroundImage: 'url(' + chart + ')'}}/>
|
||||
<DialogActions>
|
||||
<Button onClick={() => this.setState({chartOpened: false})} color="primary" autoFocus>{I18n.t('Close')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>) : null];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getDaysDiv() {
|
||||
let days = this.ids.days.map(function (day, d) {
|
||||
if (!d && this.props.settings.hideFirstDay) return null;
|
||||
return day && this.getDayDiv(d);
|
||||
}.bind(this));
|
||||
if (this.props.settings.chartLast) {
|
||||
days.push(this.getChartDiv());
|
||||
} else {
|
||||
days.unshift(this.getChartDiv());
|
||||
}
|
||||
days = days.filter(day => day);
|
||||
if (days.length) {
|
||||
return (<div key="allDays" className={this.props.classes['days-div']}>{days}</div>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
onOpenHistory() {
|
||||
if (this.ids.current.chart && this.state[this.ids.current.chart]) {
|
||||
const win = window.open(this.state[this.ids.current.chart], '_blank');
|
||||
win.focus();
|
||||
}
|
||||
}
|
||||
|
||||
getCurrentDiv() {
|
||||
return (
|
||||
<Paper key="current"
|
||||
className={this.props.classes['current-div']}
|
||||
style={this.ids.current.chart && this.state[this.ids.current.chart] ? {cursor: 'pointer'} : {}}
|
||||
onClick={() => this.onOpenHistory()}>
|
||||
{this.getCurrentIconDiv()}
|
||||
{this.getCurrentDateLocationDiv()}
|
||||
{this.getTodayWindDiv()}
|
||||
{this.getTodayTempDiv()}
|
||||
</Paper>);
|
||||
}
|
||||
|
||||
generateContent() {
|
||||
return [
|
||||
this.getHeaderDiv(),
|
||||
this.getCurrentDiv(),
|
||||
this.getDaysDiv()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartDialogWeatherForecast);
|
522
src/src/MenuList.js
Normal file
@ -0,0 +1,522 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 {withStyles} from '@material-ui/core/styles';
|
||||
|
||||
import List from '@material-ui/core/List';
|
||||
import ListItem from '@material-ui/core/ListItem';
|
||||
import ListItemText from '@material-ui/core/ListItemText';
|
||||
import ListItemIcon from '@material-ui/core/ListItemIcon';
|
||||
import ListSubheader from '@material-ui/core/ListSubheader';
|
||||
import Divider from '@material-ui/core/Divider';
|
||||
import Button from '@material-ui/core/Button';
|
||||
import Collapse from '@material-ui/core/Collapse';
|
||||
|
||||
import Utils from './Utils';
|
||||
import I18n from './i18n'
|
||||
import VisibilityButton from './basic-controls/react-visibility-button/VisibilityButton';
|
||||
import Theme from './theme';
|
||||
|
||||
import IconRooms from './icons/IconHome';
|
||||
import IconButton from '@material-ui/core/IconButton';
|
||||
import {MdLightbulbOutline as IconFunctions} from 'react-icons/md';
|
||||
import {MdFavorite as IconFavorites} from 'react-icons/md';
|
||||
import {MdExpandLess as ExpandLess} from 'react-icons/md';
|
||||
import {MdExpandMore as ExpandMore} from 'react-icons/md';
|
||||
import {MdPlayArrow as IconInstances} from 'react-icons/md';
|
||||
|
||||
const styles = {
|
||||
iconsSelected: {
|
||||
backgroundColor: 'rgb(204, 204, 204)',
|
||||
color: 'white',
|
||||
verticalAlign: 'top',
|
||||
},
|
||||
icons: {
|
||||
verticalAlign: 'top',
|
||||
color: 'gray'
|
||||
},
|
||||
menuSelectedBright: {
|
||||
color: '#1c8fe0 !important'
|
||||
},
|
||||
menuSelectedDark: {
|
||||
color: '#3cc1ff !important'
|
||||
},
|
||||
menuTextBright: {
|
||||
color: 'white !important'
|
||||
},
|
||||
menuTextDark: {
|
||||
color: 'black !important'
|
||||
}
|
||||
};
|
||||
const myStyles = () => (styles);
|
||||
|
||||
class MenuList extends Component {
|
||||
static propTypes = {
|
||||
classes: PropTypes.object.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
viewEnum: PropTypes.string,
|
||||
editMode: PropTypes.bool.isRequired,
|
||||
user: PropTypes.string.isRequired,
|
||||
root: PropTypes.string.isRequired,
|
||||
background: PropTypes.string,
|
||||
debug: PropTypes.bool,
|
||||
onSelectedItemChanged: PropTypes.func.isRequired,
|
||||
onRootChanged: PropTypes.func.isRequired,
|
||||
instances: PropTypes.bool // show instances menu
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.settings = {};
|
||||
|
||||
const {enums, roots} = this.fillEnums(this.props.objects);
|
||||
this.enums = enums;
|
||||
|
||||
this.state = {
|
||||
selectedIndex: this.props.defaultValue,
|
||||
editMode: this.props.editMode,
|
||||
background: this.props.background,
|
||||
instances: this.props.instances,
|
||||
root: this.props.root,
|
||||
roots: roots,
|
||||
visibility: {}
|
||||
};
|
||||
this.state.visibility = this.fillVisibility(this.props.root, this.props.objects, this.props.editMode).visibility;
|
||||
}
|
||||
|
||||
fillEnums(objects) {
|
||||
objects = objects || this.props.objects;
|
||||
let enums = [];
|
||||
let reg = new RegExp('^enum\\.');
|
||||
|
||||
const ids = Object.keys(objects);
|
||||
ids.sort();
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
if (ids[i] < 'enum.') continue;
|
||||
if (ids[i] > 'enum.\u9999') break;
|
||||
if (reg.test(ids[i])) {
|
||||
// detect missing steps of enums: e.g. there is enum.rooms.EG.wc, but no enum.rooms.EG;
|
||||
const parts = ids[i].split('.');
|
||||
let index = enums.length;
|
||||
while (parts.length > 2) {
|
||||
parts.pop();
|
||||
const parentId = parts.join('.');
|
||||
if (enums.indexOf(parentId) === -1) {
|
||||
enums.splice(index, 0, parentId);
|
||||
}
|
||||
}
|
||||
|
||||
enums.push(ids[i]);
|
||||
}
|
||||
}
|
||||
|
||||
const roots = {};
|
||||
for (let e = enums.length - 1; e >= 0 ; e--) {
|
||||
const parts = enums[e].split('.');
|
||||
parts.pop();
|
||||
if (parts.length > 2) {
|
||||
const id = parts.join('.');
|
||||
if (roots[id] === undefined) {
|
||||
roots[id] = {
|
||||
expanded: (typeof localStorage !== 'undefined' && localStorage.getItem(id) === '1'),
|
||||
tiles: objects[id] && objects[id].common && objects[id].common.members && objects[id].common.members.length
|
||||
};
|
||||
|
||||
if (this.props.viewEnum && this.props.viewEnum.substring(0, id.length) === id) {
|
||||
roots[id].expanded = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enums.sort();
|
||||
return {enums, roots};
|
||||
}
|
||||
|
||||
fillVisibility(root, objects, editMode) {
|
||||
objects = objects || this.props.objects;
|
||||
editMode = (editMode === undefined) ? this.props.editMode : editMode;
|
||||
|
||||
// first take elements of enum
|
||||
let items = this.getElementsToShow('enum', objects, editMode);
|
||||
let changed = false;
|
||||
const visibility = {};
|
||||
|
||||
items.forEach(function (e) {
|
||||
visibility[e.id] = !(e.settings.enabled === false);
|
||||
if (this.state && this.state.visibility[e.id] !== visibility[e.id]) {
|
||||
changed = true;
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
if (root !== 'enum') {
|
||||
items = this.getElementsToShow(root, objects, editMode);
|
||||
|
||||
items.forEach(function (e) {
|
||||
visibility[e.id] = !(e.settings.enabled === false);
|
||||
if (this.state && this.state.visibility[e.id] !== visibility[e.id]) {
|
||||
changed = true;
|
||||
}
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
return {changed, visibility};
|
||||
}
|
||||
|
||||
componentWillReceiveProps(nextProps) {
|
||||
const newState = {};
|
||||
let wasChanged = false;
|
||||
if (nextProps.editMode !== this.state.editMode) {
|
||||
newState.editMode = nextProps.editMode;
|
||||
wasChanged = true;
|
||||
}
|
||||
if (nextProps.background !== this.state.background) {
|
||||
newState.background = nextProps.background;
|
||||
wasChanged = true;
|
||||
}
|
||||
if (nextProps.instances !== this.state.instances) {
|
||||
newState.instances = nextProps.instances;
|
||||
wasChanged = true;
|
||||
}
|
||||
if (nextProps.root !== this.state.root) {
|
||||
newState.root = nextProps.root;
|
||||
newState.visibility = this.fillVisibility(nextProps.root, nextProps.objects, nextProps.editMode).visibility;
|
||||
wasChanged = true;
|
||||
}
|
||||
if (nextProps.objects) {
|
||||
const {enums, roots} = this.fillEnums(this.props.objects);
|
||||
this.enums = enums;
|
||||
const {changed, visibility} = this.fillVisibility(nextProps.root, nextProps.objects, nextProps.editMode);
|
||||
|
||||
if (changed || JSON.stringify(roots) !== this.state.roots) {
|
||||
wasChanged = true;
|
||||
newState.roots = roots;
|
||||
newState.visibility = visibility;
|
||||
}
|
||||
}
|
||||
if (wasChanged) {
|
||||
this.setState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
getListHeader(useBright) {
|
||||
let items = this.getElementsToShow('enum');
|
||||
|
||||
if (items && items.length) {
|
||||
return (<ListSubheader style={{background: this.state.background || 'white', borderBottom: useBright ? '1px solid rgba(255, 255, 255, 0.12)' : '1px solid rgba(0, 0, 0, 0.12)'}}>{
|
||||
items.map(function (item) {
|
||||
let settings = this.settings[item.id];
|
||||
|
||||
if (!settings || this.props.objects) {
|
||||
this.settings[item.id] = Utils.getSettings(this.props.objects[item.id], {user: this.props.user, language: this.props.language, id: item.id}, true);
|
||||
settings = this.settings[item.id];
|
||||
}
|
||||
|
||||
if (settings.enabled === false && !this.props.editMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
const name = settings.name;
|
||||
const visibilityButton = this.props.editMode ? <VisibilityButton useBright={useBright} visible={this.state.visibility[item.id]} onChange={() => this.onToggleEnabled(null, item.id)}/> : null;
|
||||
let style = {};
|
||||
if (this.props.editMode && !this.state.visibility[item.id]) {
|
||||
style = Object.assign({}, style, {opacity: 0.5});
|
||||
}
|
||||
|
||||
if (item.id === 'enum.rooms') {
|
||||
return (<IconButton
|
||||
key={item.id}
|
||||
className={item.id === this.props.root ? this.props.classes.iconsSelected : this.props.classes.icons}
|
||||
style={style}
|
||||
tooltip={name}
|
||||
onClick={() => this.onRootChanged('enum.rooms')}>
|
||||
<IconRooms name="rooms" width={Theme.iconSize} height={Theme.iconSize} isOn={item.id === this.props.root}/>
|
||||
{visibilityButton}
|
||||
</IconButton>);
|
||||
} else if (item.id === 'enum.functions') {
|
||||
return (<IconButton
|
||||
key={item.id}
|
||||
className={item.id === this.props.root ? this.props.classes.iconsSelected : this.props.classes.icons}
|
||||
style={style}
|
||||
tooltip={name}
|
||||
onClick={() => this.onRootChanged('enum.functions')}>
|
||||
<IconFunctions width={Theme.iconSize} height={Theme.iconSize}/>
|
||||
{visibilityButton}
|
||||
</IconButton>);
|
||||
} else if (item.id === 'enum.favorites') {
|
||||
return (<IconButton
|
||||
key={item.id}
|
||||
className={item.id === this.props.root ? this.props.classes.iconsSelected : this.props.classes.icons}
|
||||
style={style}
|
||||
tooltip={name}
|
||||
onClick={() => this.onRootChanged('enum.favorites')}>
|
||||
<IconFavorites width={Theme.iconSize} height={Theme.iconSize}/>
|
||||
{visibilityButton}
|
||||
</IconButton>);
|
||||
} else {
|
||||
const icon = Utils.getIcon(item.settings, Theme.menuIcon);
|
||||
|
||||
return (<Button
|
||||
variant="outlined"
|
||||
className={item.id === this.props.root ? this.props.classes.iconsSelected : this.props.classes.icons}
|
||||
style={style}
|
||||
key={item.id}
|
||||
onClick={() => this.onRootChanged(item.id)}>
|
||||
{icon}
|
||||
{name}
|
||||
{visibilityButton}
|
||||
</Button>);
|
||||
}
|
||||
}.bind(this))
|
||||
}</ListSubheader>);
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
onRootChanged(id) {
|
||||
let items = this.getElementsToShow(id);
|
||||
let page = items.find(item => {
|
||||
return this.props.objects[item.id] && this.props.objects[item.id].common && this.props.objects[item.id].common.members && this.props.objects[item.id].common.members.length
|
||||
});
|
||||
if (!page) {
|
||||
let pages = items.map(item => {
|
||||
let ids = this.getElementsToShow(item.id);
|
||||
return ids.find(item => {
|
||||
return this.props.objects[item.id] && this.props.objects[item.id].common && this.props.objects[item.id].common.members && this.props.objects[item.id].common.members.length
|
||||
});
|
||||
});
|
||||
page = pages.find(item => pages[0]);
|
||||
}
|
||||
this.props.onRootChanged && this.props.onRootChanged(id, page && page.id, true);
|
||||
}
|
||||
|
||||
getElementsToShow(root, _objects, editMode) {
|
||||
root = root || this.props.root;
|
||||
|
||||
// special case: instances
|
||||
if (root === Utils.INSTANCES) {
|
||||
root = 'enum.rooms';
|
||||
}
|
||||
|
||||
editMode = (editMode === undefined) ? this.props.editMode : editMode;
|
||||
|
||||
let objects = _objects || this.props.objects;
|
||||
let items = [];
|
||||
let reg = root ? new RegExp('^' + root + '\\.') : new RegExp('^[^.]$');
|
||||
let rootParts = root.split('.');
|
||||
|
||||
for (let i = 0; i < this.enums.length; i++) {
|
||||
let id = this.enums[i];
|
||||
if (reg.test(id) &&
|
||||
((objects[id] && objects[id].common && objects[id].common.members && objects[id].common.members.length) || this.state.roots[id])) {
|
||||
let settings = this.settings[id];
|
||||
// if no settings or properties were changed
|
||||
if (!settings || _objects) { // here "_objects" and not objects
|
||||
this.settings[id] = Utils.getSettings(objects[id], {user: this.props.user, language: this.props.language, id}, true);
|
||||
settings = this.settings[id];
|
||||
}
|
||||
|
||||
if (settings.enabled === false && !editMode) {
|
||||
continue;
|
||||
}
|
||||
let parts = id.split('.');
|
||||
parts.splice(rootParts.length + 1);
|
||||
id = parts.join('.');
|
||||
if (!items.find(e => e.id === id)) {
|
||||
items.push({id, settings});
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
static isOpened(path, id) {
|
||||
if (id === path.substring(0, id.length)) return true;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
onToggleEnabled(e, id) {
|
||||
e && e.stopPropagation();
|
||||
|
||||
const visibility = {};
|
||||
for (const id in this.state.visibility) {
|
||||
if (this.state.visibility.hasOwnProperty(id)) {
|
||||
visibility[id] = this.state.visibility[id];
|
||||
}
|
||||
}
|
||||
visibility[id] = !visibility[id];
|
||||
let settings = this.settings[id];
|
||||
if (!settings) {
|
||||
this.settings[id] = Utils.getSettings(this.props.objects[id], {user: this.props.user, language: this.props.language, id}, true);
|
||||
settings = this.settings[id];
|
||||
}
|
||||
|
||||
settings.enabled = visibility[id];
|
||||
this.props.onSaveSettings(id, settings);
|
||||
this.setState({visibility});
|
||||
}
|
||||
|
||||
getListItems(items, level) {
|
||||
level = level || 0;
|
||||
|
||||
if (!items) {
|
||||
items = this.getElementsToShow();
|
||||
} else
|
||||
if (typeof items !== 'object') {
|
||||
items = this.getElementsToShow(items);
|
||||
}
|
||||
|
||||
const icons = items.map(e => Utils.getIcon(e.settings, Theme.menuIcon));
|
||||
const anyIcons = !!icons.find(icon => icon);
|
||||
|
||||
const useBright = Utils.isUseBright(this.state.background, false);
|
||||
|
||||
return items.map(function (item, i) {
|
||||
const icon = icons[i];
|
||||
const children = this.getListItems(item.id, level + 1);
|
||||
|
||||
if (!this.settings[item.id]) {
|
||||
this.settings[item.id] = Utils.getSettings(this.props.objects[item.id], {user: this.props.user, language: this.props.language, id: item.id}, true);
|
||||
}
|
||||
|
||||
if (!this.props.editMode && !this.settings[item.id].enabled) return;
|
||||
|
||||
const visibilityButton = this.props.editMode ? <VisibilityButton
|
||||
big={true}
|
||||
visible={this.state.visibility[item.id]}
|
||||
useBright={useBright}
|
||||
onChange={() => this.onToggleEnabled(null, item.id)}/> : null;
|
||||
|
||||
const style = {opacity: this.props.editMode && !this.state.visibility[item.id] ? 0.5 : 1};
|
||||
style.marginLeft = 16 * level;
|
||||
const expanded = this.state.roots[item.id] && this.state.roots[item.id].expanded;
|
||||
|
||||
return [
|
||||
(<ListItem
|
||||
style={style}
|
||||
button
|
||||
className={this.props.viewEnum === item.id ? 'menu-selected' : ''}
|
||||
key={item.id}
|
||||
onClick={el => this.onSelected(item.id, el)}
|
||||
>
|
||||
{icon ? (<ListItemIcon>{icon}</ListItemIcon>) : (anyIcons ? (<div style={{width: Theme.menuIcon.height + 1}}> </div>) : null)}
|
||||
<ListItemText classes={{
|
||||
primary: this.props.viewEnum === item.id ? (useBright ? this.props.classes.menuSelectedBright : this.props.classes.menuSelectedDark) : (useBright ? this.props.classes.menuTextBright : this.props.classes.menuTextDark)
|
||||
}}
|
||||
primary={item.settings.name}/>
|
||||
{visibilityButton}
|
||||
{children && children.length ? (expanded ?
|
||||
(<ExpandLess style={(useBright ? this.props.classes.menuTextBright : this.props.classes.menuTextDark)} onClick={e => this.onExpandMenu(e, item.id)} />) :
|
||||
(<ExpandMore style={(useBright ? this.props.classes.menuTextBright : this.props.classes.menuTextDark)} onClick={e => this.onExpandMenu(e, item.id)} />)) : ''}
|
||||
</ListItem>),
|
||||
|
||||
children && children.length ?
|
||||
(<Collapse key={'sub_' + item.id} in={expanded} timeout="auto" unmountOnExit>
|
||||
<List component="div" disablePadding>
|
||||
{children}
|
||||
</List>
|
||||
</Collapse>) : null
|
||||
]
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
expandMenu(id, expanded) {
|
||||
const roots = JSON.parse(JSON.stringify(this.state.roots));
|
||||
roots[id].expanded = expanded;
|
||||
this.setState({roots});
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
localStorage.setItem(id, expanded ? '1' : '0');
|
||||
}
|
||||
}
|
||||
|
||||
onSelected(id, el) {
|
||||
if (this.state.roots[id] && !this.state.roots[id].tiles) {
|
||||
this.expandMenu(id, !this.state.roots[id].expanded);
|
||||
} else if (this.state.roots[id] && this.state.roots[id].tiles) {
|
||||
this.props.onSelectedItemChanged && this.props.onSelectedItemChanged(id);
|
||||
} else
|
||||
if (this.props.objects[id] || id === Utils.INSTANCES) {
|
||||
this.props.onSelectedItemChanged && this.props.onSelectedItemChanged(id);
|
||||
}
|
||||
}
|
||||
|
||||
onExpandMenu(e, id) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
this.expandMenu(id, !this.state.roots[id].expanded);
|
||||
}
|
||||
|
||||
getSelectedItem(items) {
|
||||
if (this.props.viewEnum) {
|
||||
return this.props.viewEnum;
|
||||
}
|
||||
items = items || this.getElementsToShow();
|
||||
return items[0].id || '';
|
||||
}
|
||||
|
||||
render() {
|
||||
let items = this.getElementsToShow();
|
||||
|
||||
const style = {width: this.props.width};
|
||||
const useBright = Utils.isUseBright(this.state.background, false);
|
||||
if (this.state.background) {
|
||||
style.background = this.state.background;
|
||||
}
|
||||
const dividerStyle = useBright ? {backgroundColor: 'rgba(255,255,255,0.12)'} : {};
|
||||
if (items && items.length) {
|
||||
const list = this.getListItems(items);
|
||||
if (this.state.instances && (this.props.root === 'enum.rooms' || this.props.root === Utils.INSTANCES)) {
|
||||
list.push((<ListItem
|
||||
button
|
||||
key={Utils.INSTANCES}
|
||||
onClick={el => this.onSelected(Utils.INSTANCES, el)}
|
||||
>
|
||||
<ListItemIcon>
|
||||
<IconInstances style={Object.assign({}, Theme.menuIcon, {color: '#008000'})}/>
|
||||
</ListItemIcon>
|
||||
<ListItemText classes={{
|
||||
primary: this.props.viewEnum === Utils.INSTANCES ? (useBright ? this.props.classes.menuSelectedBright : this.props.classes.menuSelectedDark) : (useBright ? this.props.classes.menuTextBright : this.props.classes.menuTextDark)
|
||||
}} primary={I18n.t('Instances')}/>
|
||||
</ListItem>));
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={style}>
|
||||
<Divider className='divider' style={dividerStyle}/>
|
||||
{this.getListHeader(useBright)}
|
||||
<List style={this.state.background ? {background: this.state.background} : {}}>{list}</List>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<div style={style} >
|
||||
<Divider className='divider' style={dividerStyle}/>
|
||||
{this.getListHeader(useBright)}
|
||||
<Divider className='divider' style={dividerStyle}/>
|
||||
<List >
|
||||
<ListItem key="0" value="0">
|
||||
<ListItemText>{I18n.t('No elements')}</ListItemText>
|
||||
</ListItem>
|
||||
</List>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
export default withStyles(myStyles)(MenuList);
|
331
src/src/SmartTile.js
Normal file
@ -0,0 +1,331 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Paper from '@material-ui/core/Paper';
|
||||
|
||||
import I18n from './i18n';
|
||||
import Theme from './theme';
|
||||
import Types from './States/SmartTypes';
|
||||
import Utils from './Utils';
|
||||
|
||||
import SmartBlinds from './States/SmartBlinds';
|
||||
import SmartButton from './States/SmartButton';
|
||||
import SmartDimmer from './States/SmartDimmer';
|
||||
import SmartGeneric from './States/SmartGeneric';
|
||||
import SmartInfo from './States/SmartInfo';
|
||||
import SmartSlider from './States/SmartSlider';
|
||||
import SmartState from './States/SmartState';
|
||||
import SmartSwitch from './States/SmartSwitch';
|
||||
import SmartThermometer from './States/SmartThermometer';
|
||||
import SmartThermostat from "./States/SmartThermostat";
|
||||
import SmartWindowTilt from './States/SmartWindowTilt';
|
||||
import SmartLock from './States/SmartLock';
|
||||
import SmartInstance from './States/SmartInstance';
|
||||
import SmartMedia from './States/SmartMedia';
|
||||
import SmartVolume from './States/SmartVolume';
|
||||
import SmartWeatherForecast from './States/SmartWeatherForecast';
|
||||
import SmartWarning from './States/SmartWarning';
|
||||
import SmartURL from './States/SmartURL';
|
||||
import SmartColor from './States/SmartColor';
|
||||
|
||||
class SmartTile extends Component {
|
||||
static propTypes = {
|
||||
id: PropTypes.string.isRequired,
|
||||
user: PropTypes.string.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
states: PropTypes.object.isRequired,
|
||||
editMode: PropTypes.bool.isRequired,
|
||||
windowWidth: PropTypes.number,
|
||||
onVisibilityControl: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
onSaveSettings: PropTypes.func,
|
||||
onCollectIds: PropTypes.func,
|
||||
onControl: PropTypes.func,
|
||||
ignoreIndicators: PropTypes.array,
|
||||
enumNames: PropTypes.array,
|
||||
channelInfo: PropTypes.object
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.channelInfo = this.props.channelInfo;
|
||||
this.state = {
|
||||
state: false,
|
||||
isPointer: false,
|
||||
visible: null,
|
||||
colorOn: Theme.tile.tileOn.background,
|
||||
colorOff: Theme.tile.tileOff.background,
|
||||
background: null,
|
||||
bottomBar: false,
|
||||
width: 1
|
||||
};
|
||||
this.stateId = this.channelInfo && this.channelInfo.states.find(state => state.id).id;
|
||||
this.handlers = {
|
||||
onMouseDown: null,
|
||||
onMouseUp: null,
|
||||
onClick: null
|
||||
};
|
||||
this.tileRef = React.createRef();
|
||||
}
|
||||
|
||||
getObjectName(channelName) {
|
||||
return SmartGeneric.getObjectName(this.props.objects, this.stateId, null, channelName, this.props.enumNames);
|
||||
}
|
||||
|
||||
onMouseDown(e) {
|
||||
if (this.handlers.onMouseDown && !this.props.editMode) {
|
||||
//e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.handlers.onMouseDown(e);
|
||||
}
|
||||
}
|
||||
|
||||
onMouseUp(e) {
|
||||
if (this.handlers.onMouseUp && !this.props.editMode) this.handlers.onMouseUp(e);
|
||||
}
|
||||
|
||||
onClick(e) {
|
||||
if (this.handlers.onClick && !this.props.editMode) {
|
||||
this.handlers.onClick(e);
|
||||
}
|
||||
}
|
||||
|
||||
getTileStyle() {
|
||||
let style;
|
||||
if (this.props.editMode) {
|
||||
style = Object.assign(
|
||||
{},
|
||||
Theme.tile.tile,
|
||||
Theme.tile.tileOn,
|
||||
typeof this.state.colorOn === 'object' ? this.state.colorOn : {background: this.state.colorOn},
|
||||
Theme.tile.editEnabled);
|
||||
} else {
|
||||
style = this.state.state ?
|
||||
Object.assign({}, Theme.tile.tile, Theme.tile.tileOn, typeof this.state.colorOn === 'object' ? this.state.colorOn : {background: this.state.colorOn}) :
|
||||
Object.assign({}, Theme.tile.tile, Theme.tile.tileOff, typeof this.state.colorOff === 'object' ? this.state.colorOff : {background: this.state.colorOff});
|
||||
}
|
||||
|
||||
if (this.state.background) {
|
||||
style.backgroundImage = `url(${this.state.background})`;
|
||||
style.backgroundSize = '100% auto';
|
||||
style.backgroundPosition = this.state.bottomBar ? 'center center' : 'center calc(50% - 48px)';
|
||||
if (!this.state.state) {
|
||||
style.filter = 'grayscale(100%)'
|
||||
}
|
||||
delete style.background;
|
||||
}
|
||||
|
||||
style.width = style.width * this.state.width;
|
||||
style.color = Utils.isUseBright(style.background) ? 'white' : 'black';
|
||||
|
||||
if (!this.channelInfo) {
|
||||
style.paddingTop = 50;
|
||||
style.textAlign = 'center'
|
||||
}
|
||||
|
||||
return style;
|
||||
}
|
||||
|
||||
setSize(width) {
|
||||
if (width && width !== this.state.width) {
|
||||
this.setState({width});
|
||||
}
|
||||
}
|
||||
|
||||
setBackgroundImage(url, bottomBar, seemless) {
|
||||
if (this.state.background !== url) {
|
||||
this.setState({background: url, bottomBar: bottomBar || false});
|
||||
}
|
||||
}
|
||||
|
||||
setDelete(enumId) {
|
||||
this.props.onDelete(enumId);
|
||||
}
|
||||
|
||||
setVisibility(isVisible, isDelete) {
|
||||
if (this.state.visible !== isVisible) {
|
||||
this.lastEnabledChange = Date.now();
|
||||
this.setState({visible: isVisible});
|
||||
this.props.onVisibilityControl(this.stateId, isVisible);
|
||||
}
|
||||
}
|
||||
|
||||
setColorOn(color) {
|
||||
if (JSON.stringify(this.state.colorOn) !== JSON.stringify(color)) {
|
||||
this.setState({colorOn: color});
|
||||
}
|
||||
}
|
||||
|
||||
setColorOff(color) {
|
||||
if (JSON.stringify(this.state.colorOff) !== JSON.stringify(color)) {
|
||||
this.setState({colorOff: color});
|
||||
}
|
||||
}
|
||||
|
||||
wrapContent(content) {
|
||||
let style = {cursor: this.state.isPointer ? 'pointer' : 'inherit'};
|
||||
if (!this.props.editMode && !this.state.visible && this.channelInfo) {
|
||||
style.display = 'none';
|
||||
}
|
||||
const hasAnimation = this.props.editMode && Date.now() - this.lastEnabledChange < 500;
|
||||
if (hasAnimation && this.hasAnimation) {
|
||||
this.hasAnimation = this.hasAnimation === 'just-enabled-disabled-1' ? 'just-enabled-disabled-2' : 'just-enabled-disabled-1';
|
||||
} else if (hasAnimation) {
|
||||
this.hasAnimation = 'just-enabled-disabled-1';
|
||||
} else {
|
||||
this.hasAnimation = '';
|
||||
}
|
||||
|
||||
style = Object.assign(this.getTileStyle(), style);
|
||||
|
||||
return (
|
||||
<Paper ref={this.tileRef}
|
||||
style={style}
|
||||
className={this.hasAnimation}
|
||||
onMouseDown={this.onMouseDown.bind(this)}
|
||||
onTouchStart={this.onMouseDown.bind(this)}
|
||||
onMouseUp={this.onMouseUp.bind(this)}
|
||||
onTouchEnd={this.onMouseUp.bind(this)}
|
||||
onClick={this.onClick.bind(this)}
|
||||
>
|
||||
<span style={{display: 'none'}}>{this.channelInfo ? this.channelInfo.states.find(state => state.id).id : 'nothing'}</span>
|
||||
{content}
|
||||
</Paper>);
|
||||
}
|
||||
|
||||
registerHandler(eventName, handler) {
|
||||
this.handlers[eventName] = handler;
|
||||
}
|
||||
|
||||
unregisterHandler(eventName) {
|
||||
if (this.handlers[eventName]) {
|
||||
this.handlers[eventName] = null;
|
||||
}
|
||||
}
|
||||
|
||||
createControl(control, channelInfo, tile) {
|
||||
let Component = control; // This will be used by rendering
|
||||
// ↓
|
||||
return (<Component
|
||||
key={channelInfo.id + '-tile-' + Component.name}
|
||||
enumNames={this.props.enumNames}
|
||||
channelInfo={channelInfo}
|
||||
tile={tile}
|
||||
ignoreIndicators={this.props.ignoreIndicators}
|
||||
editMode={this.props.editMode}
|
||||
states={this.props.states}
|
||||
windowWidth={this.props.windowWidth}
|
||||
objects={this.props.objects}
|
||||
registerHandler={this.registerHandler.bind(this)}
|
||||
onSaveSettings={this.props.onSaveSettings}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
onControl={this.props.onControl}
|
||||
/>);
|
||||
}
|
||||
|
||||
render() {
|
||||
let Control;
|
||||
|
||||
if (this.channelInfo) {
|
||||
switch (this.channelInfo.type) {
|
||||
case Types.light:
|
||||
case Types.socket:
|
||||
Control = SmartSwitch;
|
||||
break;
|
||||
case Types.dimmer:
|
||||
Control = SmartDimmer;
|
||||
break;
|
||||
case Types.blind:
|
||||
Control = SmartBlinds;
|
||||
break;
|
||||
case Types.windowTilt:
|
||||
Control = SmartWindowTilt;
|
||||
break;
|
||||
case Types.button:
|
||||
Control = SmartButton;
|
||||
break;
|
||||
case Types.temperature:
|
||||
Control = SmartThermometer;
|
||||
break;
|
||||
case Types.info:
|
||||
Control = SmartInfo;
|
||||
break;
|
||||
case Types.thermostat:
|
||||
Control = SmartThermostat;
|
||||
break;
|
||||
case Types.slider:
|
||||
Control = SmartSlider;
|
||||
break;
|
||||
case Types.volume:
|
||||
case Types.volumeGroup:
|
||||
Control = SmartVolume;
|
||||
break;
|
||||
case Types.lock:
|
||||
Control = SmartLock;
|
||||
break;
|
||||
case Types.instance:
|
||||
Control = SmartInstance;
|
||||
break;
|
||||
case Types.media:
|
||||
Control = SmartMedia;
|
||||
break;
|
||||
case Types.warning:
|
||||
Control = SmartWarning;
|
||||
break;
|
||||
case Types.window:
|
||||
case Types.fireAlarm:
|
||||
case Types.door:
|
||||
case Types.motion:
|
||||
Control = SmartState;
|
||||
break;
|
||||
case Types.rgbSingle:
|
||||
case Types.hue:
|
||||
case Types.rgb:
|
||||
case Types.ct:
|
||||
Control = SmartColor;
|
||||
break;
|
||||
case Types.weatherForecast:
|
||||
Control = SmartWeatherForecast;
|
||||
break;
|
||||
case Types.url:
|
||||
Control = SmartURL;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
return this.wrapContent((<span>{I18n.t('Nothing here')}</span>));
|
||||
}
|
||||
|
||||
if (!Control) {
|
||||
let name = this.channelInfo.type;
|
||||
Object.keys(Types).forEach(e => {
|
||||
if (Types[e] === this.channelInfo.type) {
|
||||
name = e;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
console.error(`${name} not implemented!`);
|
||||
return null;
|
||||
} else {
|
||||
return this.wrapContent(this.createControl(Control, this.channelInfo, this));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartTile;
|
||||
|
178
src/src/SpeechDialog.js
Normal file
@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Dialog from '@material-ui/core/Dialog';
|
||||
import Button from '@material-ui/core/Button';
|
||||
import I18n from './i18n';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
class SpeechDialog extends Component {
|
||||
static propTypes = {
|
||||
isShow: PropTypes.bool.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
onFinished: PropTypes.func.isRequired,
|
||||
locale: PropTypes.string.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.speech = null;
|
||||
this.state = {
|
||||
interimTranscript: '',
|
||||
finalTranscript: '',
|
||||
isListening: false
|
||||
};
|
||||
this.isShow = null;
|
||||
}
|
||||
|
||||
getVoices() {
|
||||
if (!window.SpeechSynthesisUtterance)
|
||||
return [];
|
||||
|
||||
return speechSynthesis.getVoices();
|
||||
}
|
||||
|
||||
static isSpeechRecognitionSupported() {
|
||||
return !!window.webkitSpeechRecognition;
|
||||
}
|
||||
|
||||
componentDidUpdate() {
|
||||
if (this.isShow !== this.props.isShow) {
|
||||
this.isShow = this.props.isShow;
|
||||
|
||||
if (this.props.isShow) {
|
||||
this.setState({isListening: true});
|
||||
this.startSpeechRecognition();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
startSpeechRecognition() {
|
||||
this.speech = SpeechDialog.isSpeechRecognitionSupported() ? new (window.SpeechRecognition || window.webkitSpeechRecognition)() : null;
|
||||
this.setState({
|
||||
interimTranscript: '',
|
||||
finalTranscript: ''
|
||||
});
|
||||
|
||||
this.locale = this.props.locale;
|
||||
|
||||
if (!this.speech || !this.locale) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.speech.continuous = false;
|
||||
this.speech.interimResults = true;
|
||||
this.speech.lang = this.locale;
|
||||
|
||||
this.speech.onresult = (e) => {
|
||||
let interimTranscript = '';
|
||||
let finalTranscript = '';
|
||||
|
||||
if (typeof (e.results) === 'undefined') {
|
||||
this.speech.onend = null;
|
||||
this.speech.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = e.resultIndex; i < e.results.length; ++i) {
|
||||
let val = e.results[i][0].transcript;
|
||||
if (e.results[i].isFinal) {
|
||||
finalTranscript += ' ' + val;
|
||||
} else {
|
||||
interimTranscript += ' ' + val;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.stopTimer) {
|
||||
clearTimeout(this.stopTimer);
|
||||
this.stopTimer = null;
|
||||
}
|
||||
|
||||
if (finalTranscript) {
|
||||
this.setState({finalTranscript: finalTranscript, interimTranscript: interimTranscript});
|
||||
this.speech && this.speech.stop();
|
||||
console.log(new Date () + ' - Listening final results');
|
||||
} else {
|
||||
this.setState({interimTranscript: interimTranscript});
|
||||
this.stopTimer = setTimeout(() => {
|
||||
if (this.speech) {
|
||||
this.speech.onresult = null;
|
||||
this.speech.end = null;
|
||||
this.speech.stop();
|
||||
this.speech = null;
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
};
|
||||
|
||||
this.speech.onend = (e) => {
|
||||
console.log(new Date () + ' - Listening onend');
|
||||
this.stopSpeechRecognition();
|
||||
};
|
||||
|
||||
this.speech.onerror = (e) => {
|
||||
console.log(new Date () + ' - Listening onend: ' + e.error);
|
||||
this.stopSpeechRecognition();
|
||||
};
|
||||
|
||||
console.log(new Date () + ' - Listening Start');
|
||||
this.speech.start();
|
||||
}
|
||||
|
||||
stopSpeechRecognition(isImmediately) {
|
||||
if (this.speech) {
|
||||
this.speech.onend = null;
|
||||
this.speech.onresult = null;
|
||||
this.speech.stop();
|
||||
this.speech = null;
|
||||
console.log(new Date () + ' - Listening stopSpeechRecognition');
|
||||
}
|
||||
if (this.state.finalTranscript) this.props.onSpeech(this.state.finalTranscript);
|
||||
if (isImmediately) {
|
||||
this.setState({isListening: false});
|
||||
this.props.onFinished && this.props.onFinished();
|
||||
} else {
|
||||
setTimeout(() => {
|
||||
this.setState({isListening: false});
|
||||
this.props.onFinished && this.props.onFinished();
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const actions = [
|
||||
<Button
|
||||
variant="outlined"
|
||||
label="Cancel"
|
||||
primary={true}
|
||||
onClick={() => this.stopSpeechRecognition(true)}
|
||||
/>
|
||||
];
|
||||
|
||||
return (<Dialog
|
||||
title={I18n.t('Speech recognition running...')}
|
||||
actions={actions}
|
||||
modal={true}
|
||||
open={this.props.isShow}
|
||||
>
|
||||
{this.state.finalTranscript ? <span style={{color: '#333333', fontWeight: 'bold'}}>{this.state.finalTranscript}</span> : (this.state.interimTranscript || I18n.t('Listening...'))}
|
||||
</Dialog>);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default SpeechDialog;
|
243
src/src/States/SmartBlinds.js
Normal file
@ -0,0 +1,243 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 CircularProgress from '@material-ui/core/CircularProgress';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Icon from '../icons/Jalousie'
|
||||
import Theme from '../theme';
|
||||
import Dialog from '../Dialogs/SmartDialogSlider';
|
||||
|
||||
const styles = {
|
||||
overlap: {
|
||||
zIndex: 2,
|
||||
position: 'absolute',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
opacity: 0.8,
|
||||
background: '#FFF',
|
||||
width: '100%'
|
||||
}
|
||||
};
|
||||
|
||||
class SmartBlinds extends SmartGeneric {
|
||||
// props = {
|
||||
// objects: OBJECT
|
||||
// tile: parentDiv
|
||||
// states: STATES
|
||||
// onControl: function
|
||||
// };
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state && this.props.objects[state.id]&& this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'STOP');
|
||||
this.stopId = state && state.id;
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
this.max = this.props.objects[this.actualId].common.max;
|
||||
if (this.max === undefined) {
|
||||
this.max = 100;
|
||||
}
|
||||
this.max = parseFloat(this.max);
|
||||
|
||||
this.min = this.props.objects[this.actualId].common.min;
|
||||
if (this.min === undefined) {
|
||||
this.min = 0;
|
||||
}
|
||||
this.min = parseFloat(this.min);
|
||||
|
||||
}
|
||||
this.props.tile.setState({state: true});
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
this.stateRx.setValue = null;
|
||||
this.key = 'smart-blinds-' + this.id + '-';
|
||||
this.doubleState = true; // used in generic: If colors for on and for off
|
||||
|
||||
this.componentReady();
|
||||
if (this.state.settings.toggleOnClick) {
|
||||
this.props.tile.setState({isPointer: true});
|
||||
}
|
||||
}
|
||||
|
||||
realValueToPercent(val) {
|
||||
if (val === undefined) {
|
||||
if (this.props.states[this.actualId]) {
|
||||
val = this.props.states[this.actualId].val || 0;
|
||||
} else {
|
||||
val = 0;
|
||||
}
|
||||
}
|
||||
val = parseFloat(val);
|
||||
val = Math.round((val - this.min) / (this.max - this.min) * 100);
|
||||
if (this.state.settings.inverted) {
|
||||
val = 100 - val;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
percentToRealValue(percent) {
|
||||
percent = parseFloat(percent);
|
||||
if (this.state.settings.inverted) {
|
||||
percent = 100 - percent;
|
||||
}
|
||||
return Math.round((this.max - this.min) * percent / 100);
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
const val = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
if (this.actualId === id || (this.id === id && this.id === this.actualId && state.ack)) {
|
||||
if (!isNaN(val)) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
newState[id] = null;
|
||||
this.setState(newState);
|
||||
|
||||
}
|
||||
|
||||
// hide desired value
|
||||
if (this.state.setValue === newState[id] && state.ack) {
|
||||
this.setState({setValue: null});
|
||||
}
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
} else if (id === this.id) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
setValue(percent) {
|
||||
console.log('Control ' + this.id + ' = ' + this.percentToRealValue(percent));
|
||||
this.setState({executing: true, setValue: percent});
|
||||
this.props.onControl(this.id, this.percentToRealValue(percent));
|
||||
}
|
||||
|
||||
onStop() {
|
||||
this.setState({executing: false});
|
||||
this.stopId && this.props.onControl && this.props.onControl(this.stopId, true);
|
||||
}
|
||||
|
||||
onToggleValue() {
|
||||
if (this.state.settings.toggleOnClick) {
|
||||
let newValue;
|
||||
const percent = this.realValueToPercent();
|
||||
if (percent) {
|
||||
newValue = 0;
|
||||
} else {
|
||||
newValue = 100;
|
||||
}
|
||||
this.setValue(newValue);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
|
||||
const overlapStyle = Object.assign({}, styles.overlap, {height: this.realValueToPercent(this.state[this.id]) + '%'});
|
||||
if (this.state.settings.colorOn) {
|
||||
Object.assign(overlapStyle, {background: this.state.settings.colorOn});
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, /*this.state[this.actualId] !== this.min ? {color: Theme.palette.lampOn} : */{}, {left: '1rem'})} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{zIndex: 3, position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
<div style={overlapStyle} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getDialogSettings () {
|
||||
const settings = super.getDialogSettings();
|
||||
|
||||
settings.unshift({
|
||||
name: 'inverted',
|
||||
value: this.state.settings.inverted || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'toggleOnClick',
|
||||
value: this.state.settings.toggleOnClick || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
saveDialogSettings (settings) {
|
||||
this.props.tile.setState({isPointer: settings.toggleOnClick});
|
||||
super.saveDialogSettings(settings);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.state[this.actualId] === null || this.state[this.actualId] === undefined) {
|
||||
return '---';
|
||||
} else {
|
||||
if (this.workingId && this.state[this.workingId] && this.state.setValue !== null && this.state.setValue !== undefined) {
|
||||
return this.realValueToPercent() + '% → ' + this.state.setValue + '%';
|
||||
} else {
|
||||
return this.realValueToPercent() + '%';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.id, true),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
startValue={this.realValueToPercent()}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
windowWidth={this.props.windowWidth}
|
||||
inverted={this.state.settings.inverted}
|
||||
onStop={this.stopId ? this.onStop.bind(this) : null}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
type={Dialog.types.blinds}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartBlinds;
|
||||
|
123
src/src/States/SmartButton.js
Normal file
@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
|
||||
import {GoDiffModified as IconButton} from 'react-icons/go';
|
||||
import {MdStop as IconStop} from 'react-icons/md';
|
||||
import {MdPlayArrow as IconPlay} from 'react-icons/md';
|
||||
import {MdPause as IconPause} from 'react-icons/md';
|
||||
import {MdReplay as IconReplay} from 'react-icons/md';
|
||||
import {MdShuffle as IconShuffle} from 'react-icons/md';
|
||||
import {MdVolumeMute as IconMute} from 'react-icons/md';
|
||||
import {MdVolumeUp as IconUnmute} from 'react-icons/md';
|
||||
import {MdFastForward as IconForward} from 'react-icons/md';
|
||||
import {MdFastRewind as IconPrev} from 'react-icons/md';
|
||||
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
|
||||
class SmartButton extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
}
|
||||
this.defaultEnabling = false; // used in the SmartGeneric
|
||||
this.stateRx.pressed = false;
|
||||
|
||||
this.icon = IconButton;
|
||||
this.style = {};
|
||||
let name = this.props.objects && this.props.objects[this.id] && this.props.objects[this.id].common && this.props.objects[this.id].name;
|
||||
if (typeof name === 'object') {
|
||||
name = name.en;
|
||||
}
|
||||
let stateName = name + '_' + this.id.split('.').pop();
|
||||
|
||||
if (stateName.match(/play/i)) {
|
||||
this.icon = IconPlay;
|
||||
this.style = {color: 'green'};
|
||||
} else if (stateName.match(/stop/i)) {
|
||||
this.icon = IconStop;
|
||||
this.style = {color: 'red'};
|
||||
} else if (stateName.match(/pause/i)) {
|
||||
this.icon = IconPause;
|
||||
this.style = {color: 'grey'};
|
||||
} else if (stateName.match(/unmute/i)) {
|
||||
this.icon = IconUnmute;
|
||||
this.style = {color: 'blue'};
|
||||
} else if (stateName.match(/mute/i)) {
|
||||
this.icon = IconMute;
|
||||
this.style = {color: 'blue'};
|
||||
} else if (stateName.match(/forw/i)) {
|
||||
this.icon = IconForward;
|
||||
this.style = {color: 'yellow'};
|
||||
} else if (stateName.match(/prev/i)) {
|
||||
this.icon = IconPrev;
|
||||
this.style = {color: 'yellow'};
|
||||
} else if (stateName.match(/replay/i)) {
|
||||
this.icon = IconReplay;
|
||||
} else if (stateName.match(/shuff/i)) {
|
||||
this.icon = IconShuffle;
|
||||
}
|
||||
this.key = 'smart-button-' + this.id + '-';
|
||||
|
||||
this.props.tile.setState({isPointer: true});
|
||||
this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
onTileClick() {
|
||||
this.props.onControl(this.id, true);
|
||||
this.setState({pressed: true});
|
||||
setTimeout(() => this.setState({pressed: false}), 500);
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
const Icon = this.icon;
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.style)} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
return this.state.pressed ? I18n.t('pressed') : '';
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent(this.getStandardContent(null));
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartButton;
|
||||
|
578
src/src/States/SmartColor.js
Normal file
@ -0,0 +1,578 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 CircularProgress from '@material-ui/core/CircularProgress';
|
||||
import { TinyColor } from '@ctrl/tinycolor';
|
||||
|
||||
import {TiLightbulb as Icon} from 'react-icons/ti'
|
||||
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Theme from '../theme';
|
||||
import Dialog from '../Dialogs/SmartDialogColor';
|
||||
import I18n from '../i18n';
|
||||
import UtilsColors from '../UtilsColors';
|
||||
|
||||
class SmartColor extends SmartGeneric {
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
const ids = {
|
||||
red: null,
|
||||
green: null,
|
||||
blue: null,
|
||||
|
||||
rgb: null,
|
||||
|
||||
hue: null,
|
||||
saturation: null,
|
||||
brightness: null,
|
||||
|
||||
temperature: null,
|
||||
dimmer: null,
|
||||
on: null
|
||||
};
|
||||
let colorMode;
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'RED');
|
||||
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
ids.red = {id: state.id};
|
||||
colorMode = Dialog.COLOR_MODES.R_G_B;
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.red.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.red.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.red.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.red.max = 255;
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'GREEN');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
ids.green = {id: state.id};
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.green.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.green.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.green.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.green.max = 255;
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'BLUE');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
ids.blue = {id: state.id};
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.blue.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.blue.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.blue.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.blue.max = 255;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'RGB');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
colorMode = Dialog.COLOR_MODES.RGB;
|
||||
ids.rgb = {id: state.id};
|
||||
this.id = this.id || state.id;
|
||||
} else {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUE');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
colorMode = Dialog.COLOR_MODES.HUE;
|
||||
ids.hue = {id: state.id};
|
||||
this.id = this.id || state.id;
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.hue.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.hue.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.hue.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.hue.max = 360;
|
||||
}
|
||||
if (this.props.objects[state.id].common.unit !== undefined) {
|
||||
ids.hue.unit = this.props.objects[state.id].common.unit;
|
||||
} else {
|
||||
ids.hue.unit = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMPERATURE');
|
||||
ids.temperature = state && state.id ? {id: state.id} : null;
|
||||
if (ids.temperature) {
|
||||
this.id = this.id || state.id;
|
||||
colorMode = colorMode || Dialog.COLOR_MODES.TEMPERATURE;
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.temperature.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.temperature.min = 2200;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.temperature.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.temperature.max = 6500;
|
||||
}
|
||||
if (this.props.objects[state.id].common.unit !== undefined) {
|
||||
ids.temperature.unit = this.props.objects[state.id].common.unit;
|
||||
} else {
|
||||
ids.temperature.unit = '';
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DIMMER');
|
||||
ids.dimmer = state && state.id ? {id: state.id} : null;
|
||||
if (ids.dimmer) {
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.dimmer.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.dimmer.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.dimmer.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.dimmer.max = 100;
|
||||
}
|
||||
if (this.props.objects[state.id].common.unit !== undefined) {
|
||||
ids.dimmer.unit = this.props.objects[state.id].common.unit;
|
||||
} else {
|
||||
ids.dimmer.unit = '%';
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'BRIGHTNESS');
|
||||
ids.brightness = state && state.id ? {id: state.id} : null;
|
||||
if (ids.brightness) {
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.brightness.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.brightness.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.brightness.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.brightness.max = 100;
|
||||
}
|
||||
if (this.props.objects[state.id].common.unit !== undefined) {
|
||||
ids.brightness.unit = this.props.objects[state.id].common.unit;
|
||||
} else {
|
||||
ids.brightness.unit = '%';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'SATURATION');
|
||||
ids.saturation = state && state.id ? {id: state.id} : null;
|
||||
if (ids.saturation) {
|
||||
if (this.props.objects[state.id].common.min !== undefined) {
|
||||
ids.saturation.min = parseFloat(this.props.objects[state.id].common.min);
|
||||
} else {
|
||||
ids.saturation.min = 0;
|
||||
}
|
||||
if (this.props.objects[state.id].common.max !== undefined) {
|
||||
ids.saturation.max = parseFloat(this.props.objects[state.id].common.max);
|
||||
} else {
|
||||
ids.saturation.max = 100;
|
||||
}
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ON_LIGHT');
|
||||
if (!state) {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ON');
|
||||
}
|
||||
|
||||
ids.on = state && state.id ? {id: state.id} : null;
|
||||
if (ids.on) {
|
||||
this.props.tile.setState({isPointer: true});
|
||||
this.props.tile.registerHandler('onClick', this.onToggle.bind(this));
|
||||
}
|
||||
}
|
||||
this.ids = ids;
|
||||
|
||||
this.key = 'smart-dimmer-' + this.id + '-';
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
this.stateRx.setValue = null;
|
||||
this.stateRx.colorMode = colorMode;
|
||||
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
realValueToPercent(props, val) {
|
||||
if (val === undefined) {
|
||||
if (this.states[props.id]) {
|
||||
val = this.states[props.id].val || 0;
|
||||
} else {
|
||||
val = 0;
|
||||
}
|
||||
}
|
||||
val = parseFloat(val);
|
||||
return (val - props.min) / (props.max - props.min) * 100;
|
||||
}
|
||||
|
||||
percentToRealValue(props, percent) {
|
||||
percent = parseFloat(percent);
|
||||
if (props) {
|
||||
let real = (props.max - props.min) * percent / 100 + props.min;
|
||||
if (props.max - props.min > 50) {
|
||||
real = Math.round(real);
|
||||
}
|
||||
return real;
|
||||
} else {
|
||||
return percent;
|
||||
}
|
||||
}
|
||||
|
||||
updateBackgroundColor(states) {
|
||||
states = states || this.state;
|
||||
const color = this.getColor(states);
|
||||
if (color !== undefined) {
|
||||
this.props.tile.setColorOn(color);
|
||||
this.props.tile.setColorOff(UtilsColors.hexToRgbA(color, 0.5));
|
||||
} else {
|
||||
this.props.tile.setColorOn(Theme.tile.tileOn.background);
|
||||
this.props.tile.setColorOff(Theme.tile.tileOff.background);
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
let props;
|
||||
if (this.ids.red && this.ids.red.id === id) {
|
||||
props = this.ids.red;
|
||||
} else if (this.ids.green && this.ids.green.id === id) {
|
||||
props = this.ids.green;
|
||||
} else if (this.ids.blue && this.ids.blue.id === id) {
|
||||
props = this.ids.blue;
|
||||
} else if (this.ids.hue && this.ids.hue.id === id) {
|
||||
props = this.ids.hue;
|
||||
} else if (this.ids.temperature && this.ids.temperature.id === id) {
|
||||
props = this.ids.temperature;
|
||||
} else if (this.ids.saturation && this.ids.saturation.id === id) {
|
||||
props = this.ids.saturation;
|
||||
} else if (this.ids.dimmer && this.ids.dimmer.id === id) {
|
||||
props = this.ids.dimmer;
|
||||
}
|
||||
|
||||
if (props) {
|
||||
const val = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
if (!isNaN(val)) {
|
||||
newState[id] = this.realValueToPercent(props, val);
|
||||
this.setState(newState);
|
||||
} else {
|
||||
newState[id] = null;
|
||||
this.setState(newState);
|
||||
}
|
||||
this.updateBackgroundColor(Object.assign({}, this.state, newState));
|
||||
} else if (this.ids.on && this.ids.on.id === id) {
|
||||
let val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON' || state.val === 'ein' || state.val === 'EIN';
|
||||
newState[id] = val;
|
||||
|
||||
this.setState(newState);
|
||||
|
||||
this.props.tile.setState({state: val});
|
||||
} else
|
||||
if (this.ids.rgb && this.ids.rgb.id === id) {
|
||||
newState[id] = state.val;
|
||||
this.setState(newState);
|
||||
this.updateBackgroundColor(Object.assign({}, this.state, newState));
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
onRgbChange(rgb, temperature, colorMode) {
|
||||
const newValue = {};
|
||||
if (colorMode !== undefined) {
|
||||
newValue.colorMode = colorMode;
|
||||
}
|
||||
|
||||
if (temperature && this.ids.temperature) {
|
||||
newValue[this.ids.temperature.id] = this.realValueToPercent(this.ids.temperature, temperature);
|
||||
this.props.onControl(this.ids.temperature.id, this.percentToRealValue(this.ids.temperature, newValue[this.ids.temperature.id]));
|
||||
} else
|
||||
if (this.ids.rgb) {
|
||||
newValue[this.ids.rgb.id] = rgb;
|
||||
this.props.onControl(this.ids.rgb.id, rgb);
|
||||
} else
|
||||
if (this.ids.red) {
|
||||
let [r, g, b] = UtilsColors.hex2array(rgb);
|
||||
|
||||
r = this.realValueToPercent({min: 0, max: 255}, r);
|
||||
g = this.realValueToPercent({min: 0, max: 255}, g);
|
||||
b = this.realValueToPercent({min: 0, max: 255}, b);
|
||||
|
||||
newValue[this.ids.red.id] = r;
|
||||
newValue[this.ids.green.id] = g;
|
||||
newValue[this.ids.blue.id] = b;
|
||||
|
||||
r = this.percentToRealValue(this.ids.red, r);
|
||||
g = this.percentToRealValue(this.ids.green, g);
|
||||
b = this.percentToRealValue(this.ids.blue, b);
|
||||
|
||||
this.props.onControl(this.ids.red.id, r);
|
||||
this.props.onControl(this.ids.green.id, g);
|
||||
this.props.onControl(this.ids.blue.id, b);
|
||||
} else
|
||||
if (this.ids.hue) {
|
||||
let [r, g, b] = UtilsColors.hex2array(rgb);
|
||||
let [h, s, l] = UtilsColors.rgbToHsl(r, g, b);
|
||||
h = this.realValueToPercent({min: 0, max: 1}, h);
|
||||
s = this.realValueToPercent({min: 0, max: 1}, s);
|
||||
l = this.realValueToPercent({min: 0, max: 1}, l);
|
||||
newValue[this.ids.hue.id] = h;
|
||||
if (this.ids.saturation) {
|
||||
newValue[this.ids.saturation.id] = s;
|
||||
}
|
||||
if (this.ids.brightness) {
|
||||
newValue[this.ids.brightness.id] = l;
|
||||
}
|
||||
h = this.percentToRealValue(this.ids.hue, h);
|
||||
s = this.percentToRealValue(this.ids.saturation, s);
|
||||
l = this.percentToRealValue(this.ids.brightness, l);
|
||||
|
||||
this.props.onControl(this.ids.hue.id, h);
|
||||
this.ids.saturation && this.props.onControl(this.ids.saturation.id, s);
|
||||
this.ids.brightness && this.props.onControl(this.ids.brightness.id, l);
|
||||
} else
|
||||
if (this.ids.temperature) {
|
||||
newValue[this.ids.rgb.id] = rgb;
|
||||
const _rgb = UtilsColors.hex2array(rgb);
|
||||
this.props.onControl(this.ids.temperature.id, UtilsColors.rgb2temperature(_rgb[0], _rgb[1], _rgb[2]));
|
||||
}
|
||||
|
||||
if (this.ids.on && !this.state[this.ids.on.id]) {
|
||||
newValue[this.ids.on.id] = true;
|
||||
this.props.onControl(this.ids.on.id, true);
|
||||
}
|
||||
if (this.ids.dimmer) {
|
||||
if (this.state[this.ids.dimmer.id] === 0) {
|
||||
newValue[this.ids.dimmer.id] = 100;
|
||||
this.props.onControl(this.ids.dimmer.id, 100);
|
||||
} else {
|
||||
this.props.onControl(this.ids.dimmer.id, this.state[this.ids.dimmer.id]);
|
||||
}
|
||||
}
|
||||
|
||||
this.setState(newValue);
|
||||
|
||||
}
|
||||
|
||||
onDimmerChange(dimmer) {
|
||||
this.setState({dimmer});
|
||||
this.props.onControl(this.ids.dimmer.id, this.percentToRealValue(this.ids.dimmer, dimmer));
|
||||
}
|
||||
|
||||
getDialogSettings() {
|
||||
const settings = super.getDialogSettings();
|
||||
|
||||
settings.unshift({
|
||||
name: 'colorMode',
|
||||
value: this.state.settings.colorMode || 'RGB/Kelvin',
|
||||
options: [
|
||||
{value: 'RGB/Kelvin', label: I18n.t('RGB/Kelvin')},
|
||||
{value: 'RGB', label: I18n.t('RGB')},
|
||||
{value: 'Kelvin', label: I18n.t('Kelvin')}
|
||||
],
|
||||
type: 'select'
|
||||
});
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
onToggle(value) {
|
||||
if (this.ids.on) {
|
||||
const newValue = value === undefined || typeof value === 'object' ? !this.state[this.ids.on.id] : value;
|
||||
this.setState({[this.ids.on.id]: newValue});
|
||||
this.props.onControl(this.ids.on.id, newValue);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.state[this.actualId] !== this.min ? {color: Theme.palette.lampOn} : {})} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getColor(states) {
|
||||
states = states || this.state;
|
||||
|
||||
let color;
|
||||
if (this.ids.rgb && this.state.colorMode === Dialog.COLOR_MODES.RGB) {
|
||||
color = states[this.ids.rgb.id];
|
||||
} else
|
||||
if (this.ids.red && this.state.colorMode === Dialog.COLOR_MODES.R_G_B) {
|
||||
let r = states[this.ids.red.id];
|
||||
let g = states[this.ids.green.id];
|
||||
let b = states[this.ids.blue.id];
|
||||
if (r !== null && g !== null && b !== null &&
|
||||
r !== undefined && g !== undefined && b !== undefined) {
|
||||
r = this.percentToRealValue({min: 0, max: 255}, r);
|
||||
g = this.percentToRealValue({min: 0, max: 255}, g);
|
||||
b = this.percentToRealValue({min: 0, max: 255}, b);
|
||||
color = UtilsColors.rgb2string([r, g, b]);
|
||||
}
|
||||
} else
|
||||
if (this.ids.hue && this.state.colorMode === Dialog.COLOR_MODES.HUE) {
|
||||
let hue = states[this.ids.hue.id];
|
||||
let saturation = this.ids.saturation ? states[this.ids.saturation.id] : 100;
|
||||
let brightness = this.ids.brightness ? states[this.ids.brightness.id] : 50;
|
||||
if (hue !== null && saturation !== null && brightness !== null &&
|
||||
hue !== undefined && saturation !== undefined && brightness !== undefined) {
|
||||
hue = this.percentToRealValue({min: 0, max: 1}, hue);
|
||||
saturation = this.percentToRealValue({min: 0, max: 1}, saturation);
|
||||
brightness = this.percentToRealValue({min: 0, max: 1}, brightness);
|
||||
color = UtilsColors.rgb2string(UtilsColors.hslToRgb(hue, saturation, brightness));
|
||||
}
|
||||
} else
|
||||
if (this.ids.temperature && this.state.colorMode === Dialog.COLOR_MODES.TEMPERATURE) {
|
||||
let temperature = this.percentToRealValue(this.ids.temperature, states[this.ids.temperature.id]);
|
||||
color = UtilsColors.rgb2string(UtilsColors.temperatureToRGB(temperature));
|
||||
if (this.state.dimmer !== undefined) {
|
||||
color = new TinyColor(color).darken(100 - this.state.dimmer).toString();
|
||||
}
|
||||
} else
|
||||
if (this.ids.rgb) {
|
||||
color = states[this.ids.rgb.id];
|
||||
} else
|
||||
if (this.ids.red) {
|
||||
let r = states[this.ids.red.id];
|
||||
let g = states[this.ids.green.id];
|
||||
let b = states[this.ids.blue.id];
|
||||
if (r !== null && g !== null && b !== null &&
|
||||
r !== undefined && g !== undefined && b !== undefined) {
|
||||
r = this.percentToRealValue({min: 0, max: 255}, r);
|
||||
g = this.percentToRealValue({min: 0, max: 255}, g);
|
||||
b = this.percentToRealValue({min: 0, max: 255}, b);
|
||||
color = UtilsColors.rgb2string([r, g, b]);
|
||||
}
|
||||
} else
|
||||
if (this.ids.hue) {
|
||||
let hue = states[this.ids.hue.id];
|
||||
let saturation = this.ids.saturation ? states[this.ids.saturation.id] : 100;
|
||||
let brightness = this.ids.brightness ? states[this.ids.brightness.id] : 50;
|
||||
if (hue !== null && saturation !== null && brightness !== null &&
|
||||
hue !== undefined && saturation !== undefined && brightness !== undefined) {
|
||||
hue = this.percentToRealValue({min: 0, max: 1}, hue);
|
||||
saturation = this.percentToRealValue({min: 0, max: 1}, saturation);
|
||||
brightness = this.percentToRealValue({min: 0, max: 1}, brightness);
|
||||
color = UtilsColors.rgb2string(UtilsColors.hslToRgb(hue, saturation, brightness));
|
||||
}
|
||||
} else if (this.ids.temperature) {
|
||||
let temperature = states[this.ids.temperature.id];
|
||||
temperature = this.percentToRealValue(this.ids.temperature, temperature);
|
||||
color = UtilsColors.rgb2string(UtilsColors.temperatureToRGB(temperature));
|
||||
color = new TinyColor(color).darken(100 - this.state.dimmer).toString();
|
||||
}
|
||||
|
||||
if (color && color[0] !== '#' && color.match(/^rgb/)) {
|
||||
color = '#' + color;
|
||||
}
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.ids.on) {
|
||||
if (this.ids.dimmer) {
|
||||
return this.state[this.ids.dimmer.id] + this.ids.dimmer.unit;
|
||||
} else {
|
||||
return this.state[this.ids.on.id] ? I18n.t('On') : I18n.t('Off');
|
||||
}
|
||||
} else if (this.ids.dimmer) {
|
||||
return this.state[this.ids.dimmer.id] + this.ids.dimmer.unit;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.showDialog) {
|
||||
this.props.tile.unregisterHandler('onClick');
|
||||
} else {
|
||||
this.props.tile.registerHandler('onClick', this.onToggle.bind(this));
|
||||
}
|
||||
|
||||
let modeRGB = !this.ids.temperature || !!(this.ids.rgb || this.ids.red || this.ids.hue);
|
||||
let modeTemperature = !!this.ids.temperature;
|
||||
if (this.state.settings.colorMode === 'RGB') {
|
||||
modeRGB = true;
|
||||
modeTemperature = false;
|
||||
} else
|
||||
if (this.state.settings.colorMode === 'Kelvin') {
|
||||
modeRGB = false;
|
||||
modeTemperature = true;
|
||||
}
|
||||
const color = this.getColor() || '#000000';
|
||||
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.id, true),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
windowWidth={this.props.windowWidth}
|
||||
ids={this.ids}
|
||||
|
||||
modeRGB={modeRGB}
|
||||
modeTemperature={modeTemperature}
|
||||
|
||||
startModeTemp={this.state.colorMode === Dialog.COLOR_MODES.TEMPERATURE}
|
||||
temperatureMin={(this.ids.temperature && this.ids.temperature.min) || 2200}
|
||||
temperatureMax={(this.ids.temperature && this.ids.temperature.max) || 6500}
|
||||
|
||||
startRGB={color}
|
||||
onRgbChange={this.onRgbChange.bind(this)}
|
||||
startTemp={(this.ids.temperature && this.state[this.ids.temperature.id]) ? this.percentToRealValue(this.ids.temperature, this.state[this.ids.temperature.id]) : UtilsColors.rgb2temperature(color)}
|
||||
|
||||
startOn={this.ids.on && this.state[this.ids.on.id]}
|
||||
useOn={!!this.ids.on}
|
||||
onToggle={this.ids.on && this.onToggle.bind(this)}
|
||||
|
||||
startDimmer={this.ids.dimmer && this.state[this.ids.dimmer.id]}
|
||||
useDimmer={!!this.ids.dimmer}
|
||||
onDimmerChange={this.onDimmerChange.bind(this)}
|
||||
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartColor;
|
||||
|
56
src/src/States/SmartDetector.js
Normal file
@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Theme from '../theme';
|
||||
|
||||
import {TiCogOutline as IconWorking} from 'react-icons/ti';
|
||||
import {MdPermScanWifi as IconUnreach} from 'react-icons/md';
|
||||
import {MdPriorityHigh as IconMaintain} from 'react-icons/md';
|
||||
import {MdBatteryAlert as IconLowbat} from 'react-icons/md';
|
||||
import {MdError as IconError} from 'react-icons/md';
|
||||
|
||||
const additionalParameters = {
|
||||
'WORKING': {icon: IconWorking, color: Theme.tile.tileIndicatorsIcons.working},
|
||||
'UNREACH': {icon: IconUnreach, color: Theme.tile.tileIndicatorsIcons.unreach},
|
||||
'LOWBAT': {icon: IconLowbat, color: Theme.tile.tileIndicatorsIcons.lowbat},
|
||||
'MAINTAIN': {icon: IconMaintain, color: Theme.tile.tileIndicatorsIcons.maintain},
|
||||
'ERROR': {icon: IconError, color: Theme.tile.tileIndicatorsIcons.error},
|
||||
'DIRECTION': { color: Theme.tile.tileIndicatorsIcons.direction},
|
||||
'CONNECTED': {icon: IconUnreach, color: Theme.tile.tileIndicatorsIcons.connected},
|
||||
};
|
||||
|
||||
class IOBChannelDetector {
|
||||
constructor() {
|
||||
this.detector = new window.ChannelDetector();
|
||||
}
|
||||
|
||||
detect(/*objects, keys, id, usedIds, ignoreIndicators*/) {
|
||||
const result = this.detector.detect.apply(this.detector, arguments);
|
||||
|
||||
if (result) {
|
||||
result.forEach(one => {
|
||||
one.states.forEach(state => {
|
||||
if (state.id && additionalParameters[state.name]) {
|
||||
Object.assign(state, additionalParameters[state.name]);
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export default IOBChannelDetector;
|
230
src/src/States/SmartDimmer.js
Normal file
@ -0,0 +1,230 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 CircularProgress from '@material-ui/core/CircularProgress';
|
||||
|
||||
import {TiLightbulb as Icon} from 'react-icons/ti'
|
||||
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Theme from '../theme';
|
||||
import Dialog from '../Dialogs/SmartDialogSlider';
|
||||
import I18n from '../i18n';
|
||||
|
||||
class SmartDimmer extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ON_SET');
|
||||
this.onId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ON_ACTUAL');
|
||||
this.onActualId = state ? state.id : this.onId;
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
this.max = this.props.objects[this.actualId].common.max;
|
||||
if (this.max === undefined) {
|
||||
this.max = 100;
|
||||
}
|
||||
this.max = parseFloat(this.max);
|
||||
|
||||
this.min = this.props.objects[this.actualId].common.min;
|
||||
if (this.min === undefined) {
|
||||
this.min = 0;
|
||||
}
|
||||
this.min = parseFloat(this.min);
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
}
|
||||
|
||||
this.key = 'smart-dimmer-' + this.id + '-';
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
this.stateRx.setValue = null;
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
realValueToPercent(val) {
|
||||
if (val === undefined) {
|
||||
if (this.props.states[this.actualId]) {
|
||||
val = this.props.states[this.actualId].val || 0;
|
||||
} else {
|
||||
val = 0;
|
||||
}
|
||||
}
|
||||
val = parseFloat(val);
|
||||
return Math.round((val - this.min) / (this.max - this.min) * 100);
|
||||
}
|
||||
|
||||
percentToRealValue(percent) {
|
||||
percent = parseFloat(percent);
|
||||
return Math.round((this.max - this.min) * percent / 100);
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
|
||||
if (this.onActualId === id || (this.onId === id && this.onId === this.onActualId && state.ack)) {
|
||||
let val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON' || state.val === 'ein' || state.val === 'EIN';
|
||||
newState[id] = val;
|
||||
|
||||
this.setState(newState);
|
||||
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
} else
|
||||
if (this.actualId === id || (this.id === id && this.id === this.actualId && state.ack)) {
|
||||
const val = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
if (!isNaN(val)) {
|
||||
newState[id] = this.realValueToPercent(val);
|
||||
this.setState(newState);
|
||||
|
||||
if (!this.onActualId) {
|
||||
const tileState = val !== this.min;
|
||||
this.props.tile.setState({
|
||||
state: tileState
|
||||
});
|
||||
}
|
||||
} else {
|
||||
newState[id] = null;
|
||||
this.setState(newState);
|
||||
if (!this.onActualId) {
|
||||
this.props.tile.setState({
|
||||
state: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// hide desired value
|
||||
if (this.state.setValue === newState[id] && state.ack) {
|
||||
this.setState({setValue: null});
|
||||
}
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
} else if (id === this.id) {
|
||||
newState[id] = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
this.setState(newState);
|
||||
} else if (id === this.onId) {
|
||||
newState[id] = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON' || state.val === 'ein' || state.val === 'EIN';
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
setValue(percent) {
|
||||
if (percent) {
|
||||
this.lastNotNullPercent = percent;
|
||||
} else {
|
||||
const p = this.realValueToPercent();
|
||||
if (p) {
|
||||
this.lastNotNullPercent = p;
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Control ' + this.id + ' = ' + this.percentToRealValue(percent));
|
||||
this.setState({executing: true, setValue: percent});
|
||||
this.props.onControl(this.id, this.percentToRealValue(percent));
|
||||
}
|
||||
|
||||
onToggleValue() {
|
||||
if (this.onId) {
|
||||
this.props.onControl(this.onId, !this.state[this.onActualId]);
|
||||
} else {
|
||||
let newValue;
|
||||
const percent = this.realValueToPercent();
|
||||
if (percent) {
|
||||
newValue = 0;
|
||||
} else {
|
||||
newValue = this.lastNotNullPercent || 100;
|
||||
}
|
||||
this.setValue(newValue);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.state[this.actualId] !== this.min ? {color: Theme.palette.lampOn} : {})} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.onActualId && this.state[this.onActualId] === false) {
|
||||
return I18n.t('Off');
|
||||
}
|
||||
if (this.state[this.actualId] === null || this.state[this.actualId] === undefined) {
|
||||
return '---';
|
||||
} else {
|
||||
if (this.workingId && this.state[this.workingId] && this.state.setValue !== null && this.state.setValue !== undefined) {
|
||||
return this.realValueToPercent(this.state[this.actualId]) + '% → ' + this.state.setValue + '%';
|
||||
} else {
|
||||
return this.realValueToPercent(this.state[this.actualId]) + '%';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.id, true),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
windowWidth={this.props.windowWidth}
|
||||
startValue={this.realValueToPercent()}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
startToggleValue={this.onActualId ? this.state[this.onActualId] : false}
|
||||
onToggle={this.onId && this.onToggleValue.bind(this)}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
type={Dialog.types.dimmer}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartDimmer;
|
||||
|
758
src/src/States/SmartGeneric.js
Normal file
@ -0,0 +1,758 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Utils from '../Utils';
|
||||
import I18n from '../i18n';
|
||||
import Theme from '../theme';
|
||||
|
||||
import {MdVisibility as IconCheck} from 'react-icons/md';
|
||||
import {MdRemove as IconRemoved} from 'react-icons/md';
|
||||
import {MdEdit as IconEdit} from 'react-icons/md';
|
||||
import {MdArrowUpward as IconDirectionUp} from 'react-icons/md';
|
||||
import {MdArrowDownward as IconDirectionDown} from 'react-icons/md';
|
||||
import {MdSwapVert as IconDirection} from 'react-icons/md';
|
||||
|
||||
import Dialog from '../Dialogs/SmartDialogSettings';
|
||||
|
||||
class SmartGeneric extends Component {
|
||||
static propTypes = {
|
||||
objects: PropTypes.object.isRequired,
|
||||
states: PropTypes.object.isRequired,
|
||||
tile: PropTypes.object.isRequired,
|
||||
channelInfo: PropTypes.object.isRequired,
|
||||
ignoreIndicators: PropTypes.array,
|
||||
enumNames: PropTypes.array,
|
||||
windowWidth: PropTypes.number,
|
||||
user: PropTypes.string
|
||||
};
|
||||
|
||||
constructor(props, noSubscribe) {
|
||||
super(props);
|
||||
this.channelInfo = this.props.channelInfo;
|
||||
this.subscribes = null;
|
||||
this.subscribed = false;
|
||||
this.defaultIcon = null;
|
||||
|
||||
this.width = Theme.tile.width;
|
||||
this.height = Theme.tile.height;
|
||||
this.doubleState = false; // has on/off or only info
|
||||
|
||||
this.showCorner = false; // set it to true to show the corner
|
||||
this.stateRx = {
|
||||
executing: false,
|
||||
settings: {},
|
||||
showSettings: false,
|
||||
editMode: null,
|
||||
ignoreIndicators: this.props.ignoreIndicators || []
|
||||
};
|
||||
this.defaultEnabling = true; // overload this property to hide element by default
|
||||
|
||||
this.editMode = this.props.editMode;
|
||||
|
||||
this.lastEnabledChange = 0;
|
||||
|
||||
if (typeof noSubscribe !== 'boolean' || !noSubscribe) {
|
||||
if (this.channelInfo.states) {
|
||||
let ids = [];
|
||||
this.channelInfo.states.forEach(function (state) {
|
||||
if (!state.id) return;
|
||||
|
||||
if (state.id.startsWith('system.adapter.')) {
|
||||
ids.push(state.id);
|
||||
} else
|
||||
if (!state.noSubscribe &&
|
||||
this.props.objects[state.id] &&
|
||||
this.props.objects[state.id].type === 'state' &&
|
||||
ids.indexOf(state.id) === -1)
|
||||
{
|
||||
const pos = state.id.lastIndexOf('.');
|
||||
if (pos !== -1 && this.stateRx.ignoreIndicators.indexOf(state.id.substring(pos + 1)) !== -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
ids.push(state.id);
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
if (ids.length) {
|
||||
this.subscribes = ids;
|
||||
|
||||
// do not want to mutate via setState, because it is constructor
|
||||
ids.forEach(id => this.stateRx[id] = this.props.states[id] ? this.props.states[id].val : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.channelInfo && this.channelInfo.states) {
|
||||
this.indicators = {};
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'WORKING');
|
||||
this.indicators.workingId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'UNREACH');
|
||||
this.indicators.unreachId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'LOWBAT');
|
||||
this.indicators.lowbatId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'MAINTAIN');
|
||||
this.indicators.maintainId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ERROR');
|
||||
this.indicators.errorId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DIRECTION');
|
||||
this.indicators.directionId = state && state.id;
|
||||
|
||||
if (this.indicators.directionId) {
|
||||
this.direction = {
|
||||
undef: true,
|
||||
up: 'unused',
|
||||
down: 'unused'
|
||||
};
|
||||
const obj = this.props.objects[this.indicators.directionId];
|
||||
if (obj && obj.common) {
|
||||
if (obj.common.type === 'number') {
|
||||
if (obj.common.states) {
|
||||
for (const index in obj.common.states) {
|
||||
if (!obj.common.states.hasOwnProperty(index)) continue;
|
||||
if (obj.common.states[index].match(/up/i)) {
|
||||
this.direction.up = index.toString();
|
||||
} else if (obj.common.states[index].match(/down/i)) {
|
||||
this.direction.down = index.toString();
|
||||
} else if (obj.common.states[index].match(/undef/i)) {
|
||||
this.direction.undef = index.toString();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.direction.undef = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.indicators.errorId) {
|
||||
this.errorText = '';
|
||||
}
|
||||
}
|
||||
|
||||
// will be done in componentReady
|
||||
// this.state = stateRx;
|
||||
}
|
||||
|
||||
componentReady () {
|
||||
if (this.id && this.props.objects[this.id]) {
|
||||
this.settingsId = this.id;
|
||||
} else
|
||||
if (this.instanceId !== undefined) {
|
||||
this.settingsId = this.instanceId;
|
||||
}
|
||||
|
||||
if (this.stateRx.showDialog !== undefined) {
|
||||
this.showCorner = true;
|
||||
this.onMouseUpBind = this.onMouseUp.bind(this);
|
||||
this.props.tile.registerHandler('onMouseDown', this.onTileMouseDown.bind(this));
|
||||
}
|
||||
|
||||
if (this.settingsId) {
|
||||
if (this.props.objects[this.settingsId] && this.props.objects[this.settingsId].type === 'instance') {
|
||||
this.stateRx.settings = {
|
||||
enabled: true,
|
||||
name: this.props.objects[this.settingsId].common.name + '.' + this.instanceNumber
|
||||
}
|
||||
} else {
|
||||
this.stateRx.settings = Utils.getSettings(
|
||||
this.props.objects[this.settingsId],
|
||||
{
|
||||
user: this.props.user,
|
||||
language: I18n.getLanguage(),
|
||||
name: this.getObjectNameCh()
|
||||
},
|
||||
this.defaultEnabling
|
||||
);
|
||||
}
|
||||
if (this.stateRx.settings.background) {
|
||||
this.props.tile.setBackgroundImage(this.stateRx.settings.background || '', true);
|
||||
}
|
||||
}
|
||||
|
||||
this.stateRx.nameStyle = {fontSize: SmartGeneric.getNameFontSize(this.stateRx.settings.name)};
|
||||
|
||||
this.props.tile.setVisibility(this.stateRx.settings.enabled);
|
||||
|
||||
this.props.tile.setColorOn(this.stateRx.settings.colorOn || Theme.tile.tileOn.background);
|
||||
this.props.tile.setColorOff(this.stateRx.settings.colorOff || Theme.tile.tileOff.background);
|
||||
|
||||
if (this.stateRx.settings && this.stateRx.settings.doubleSize) {
|
||||
this.width = 2;
|
||||
}
|
||||
|
||||
if (this.width > 1) {
|
||||
this.props.tile.setSize(this.width);
|
||||
}
|
||||
|
||||
// ↓ ignore error here
|
||||
// eslint-disable-next-line react/no-direct-mutation-state
|
||||
this.state = this.stateRx;
|
||||
delete this.stateRx;
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
if (this.state.settings.enabled && this.subscribes && !this.subscribed) {
|
||||
this.subscribed = true;
|
||||
this.props.onCollectIds(this, this.subscribes, true);
|
||||
}
|
||||
}
|
||||
|
||||
static getObjectName(objects, id, label, channelName, enumNames) {
|
||||
let name;
|
||||
if (label) {
|
||||
name = label;
|
||||
} else
|
||||
if (!id) {
|
||||
name = 'No elements';
|
||||
} else {
|
||||
//if (objects[enumName]) {
|
||||
// enumName = SmartGeneric.getObjectName(objects, enumName);
|
||||
//}
|
||||
|
||||
let item = objects[id];
|
||||
if (item && item.common && item.common.name) {
|
||||
name = Utils.getObjectName(objects, id, null, {language: I18n.getLanguage()});
|
||||
|
||||
if (enumNames) {
|
||||
if (typeof enumNames === 'object') {
|
||||
enumNames.forEach(e => {
|
||||
let reg = new RegExp('\\b' + e + '\\b');
|
||||
const newName = name.replace(reg, ' ').replace(/\s\s/g, '').trim();
|
||||
if (newName) {
|
||||
name = newName;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let reg = new RegExp('\\b' + enumNames + '\\b');
|
||||
const newName = name.replace(reg, ' ').replace(/\s\s/g, '').trim();
|
||||
if (newName) {
|
||||
name = newName;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (channelName) {
|
||||
let reg = new RegExp(channelName + '[.: ]?');
|
||||
const newName = name.replace(reg, ' ').trim();
|
||||
if (newName) {
|
||||
name = newName;
|
||||
}
|
||||
}
|
||||
|
||||
if (name && name === name.toUpperCase()) {
|
||||
name = name[0] + name.substring(1).toLowerCase();
|
||||
}
|
||||
} else {
|
||||
let pos = id.lastIndexOf('.');
|
||||
name = id.substring(pos + 1).replace(/_/g, ' ');
|
||||
name = Utils.CapitalWords(name);
|
||||
|
||||
if (enumNames) {
|
||||
if (typeof enumNames === 'object') {
|
||||
enumNames.forEach(e => {
|
||||
let reg = new RegExp('\\b' + e + '\\b');
|
||||
name = name.replace(reg, ' ').replace(/\s\s/g, '').trim();
|
||||
});
|
||||
} else {
|
||||
let reg = new RegExp('\\b' + enumNames + '\\b');
|
||||
name = name.replace(reg, ' ').replace(/\s\s/g, '').trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (channelName) {
|
||||
let reg = new RegExp(channelName + '[.: ]?');
|
||||
name = I18n.t(name.replace(reg, ' ').trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
return name.trim();
|
||||
}
|
||||
|
||||
static getParentId(id) {
|
||||
const pos = id.lastIndexOf('.');
|
||||
if (pos !== -1) {
|
||||
return id.substring(0, pos);
|
||||
} else {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
|
||||
getObjectNameCh() {
|
||||
const channelId = SmartGeneric.getParentId(this.id);
|
||||
if (this.props.objects[channelId] && (this.props.objects[channelId].type === 'channel' || this.props.objects[channelId].type === 'device')) {
|
||||
return SmartGeneric.getObjectName(this.props.objects, channelId, null, null, this.props.enumNames) || ' ';
|
||||
} else {
|
||||
return SmartGeneric.getObjectName(this.props.objects, this.id, null, null, this.props.enumNames) || ' ';
|
||||
}
|
||||
}
|
||||
|
||||
// default handler
|
||||
updateState(id, state) {
|
||||
// update indicators
|
||||
let val;
|
||||
if (this.indicators && id === this.indicators.directionId) {
|
||||
val = (state.val !== null && state.val !== undefined) ? state.val.toString() : '';
|
||||
} else if (this.indicators && id === this.indicators.errorId) {
|
||||
if (typeof state.val === 'string' ) {
|
||||
let i = parseInt(state.val.trim(), 10);
|
||||
if (i.toString() === state.val.trim()) {
|
||||
val = i;
|
||||
} else {
|
||||
val = state.val === 'true' || state.val === 'on' || state.val === 'ON';
|
||||
}
|
||||
} else {
|
||||
val = typeof state.val === 'number' ? state.val : state.val === true || state.val === 'true' || state.val === 'on' || state.val === 'ON';
|
||||
}
|
||||
const obj = this.props.objects[id];
|
||||
if (obj && obj.common) {
|
||||
if (obj.common.min !== undefined && obj.common.min === val) {
|
||||
val = false;
|
||||
this.errorText = '';
|
||||
} else if (obj.common.states && obj.common.states[val] !== undefined) {
|
||||
this.errorText = I18n.t(obj.common.states[val]);
|
||||
val = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON';
|
||||
}
|
||||
const newState = {};
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
}
|
||||
|
||||
// default handler
|
||||
onControl(id, val) {
|
||||
|
||||
}
|
||||
|
||||
// default handler
|
||||
onLongClick(e) {
|
||||
if (e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
}
|
||||
this.setState({showDialog: true});
|
||||
}
|
||||
|
||||
onDialogClose() {
|
||||
this.setState({showDialog: false});
|
||||
}
|
||||
|
||||
onMouseUp() {
|
||||
document.removeEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true});
|
||||
document.removeEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true});
|
||||
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer);
|
||||
this.timer = null;
|
||||
this.onToggleValue && this.onToggleValue();
|
||||
}
|
||||
}
|
||||
|
||||
onTileMouseDown(e) {
|
||||
if (this.state.showDialog) return;
|
||||
//e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
this.timer = setTimeout(this.onLongClick.bind(this), 500);
|
||||
|
||||
document.addEventListener('mouseup', this.onMouseUpBind, {passive: false, capture: true});
|
||||
document.addEventListener('touchend', this.onMouseUpBind, {passive: false, capture: true});
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.props.onCollectIds && this.subscribed) {
|
||||
this.props.onCollectIds(this, this.subscribes, false);
|
||||
this.subscribed = null;
|
||||
}
|
||||
}
|
||||
|
||||
saveSettings(newSettings, cb) {
|
||||
const settings = newSettings || this.state.settings;
|
||||
if (this.props.onSaveSettings && this.settingsId) {
|
||||
this.props.onSaveSettings(this.settingsId, settings, {enabled: this.defaultEnabling}, () => {
|
||||
// subscribe if enabled and was not subscribed
|
||||
if (this.subscribes && settings.enabled && !this.subscribed) {
|
||||
this.subscribed = true;
|
||||
this.props.onCollectIds(this, this.subscribes, true);
|
||||
} else
|
||||
// unsubscribe if disabled and was subscribed
|
||||
if (!settings.enabled && this.subscribed) {
|
||||
this.subscribed = false;
|
||||
this.props.onCollectIds(this, this.subscribes, false);
|
||||
}
|
||||
|
||||
this.props.tile.setColorOn(settings.colorOn || Theme.tile.tileOn);
|
||||
this.props.tile.setColorOff(settings.colorOff || Theme.tile.tileOff);
|
||||
this.props.tile.setVisibility(settings.enabled);
|
||||
this.width = settings.doubleSize ? 2 : 1;
|
||||
this.props.tile.setSize(this.width);
|
||||
cb && cb(settings);
|
||||
});
|
||||
} else if (this.customSettings) {
|
||||
// custom URL
|
||||
const enumSettings = Utils.getSettings(this.props.objects[this.customSettings.settingsId], {user: this.props.user});
|
||||
let pos = -1;
|
||||
|
||||
if (enumSettings) {
|
||||
enumSettings.URLs.forEach((e, i) => {
|
||||
if (e.id === this.id) {
|
||||
pos = i;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (pos !== -1) {
|
||||
if (newSettings) {
|
||||
newSettings = Object.assign({}, this.customSettings, newSettings);
|
||||
enumSettings.URLs[pos] = newSettings;
|
||||
} else {
|
||||
enumSettings.URLs.splice(pos, 1);
|
||||
}
|
||||
const enumId = (newSettings && newSettings.settingsId) || this.customSettings.settingsId;
|
||||
this.props.onSaveSettings && this.props.onSaveSettings(enumId, enumSettings, function () {
|
||||
if (!newSettings) {
|
||||
this.props.tile.setDelete(enumId);
|
||||
} else {
|
||||
|
||||
}
|
||||
cb && cb(newSettings);
|
||||
}.bind(this));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toggleEnabled() {
|
||||
let settings = JSON.parse(JSON.stringify(this.state.settings));
|
||||
settings.enabled = !settings.enabled;
|
||||
|
||||
this.saveSettings(settings, () => this.setState({settings}));
|
||||
}
|
||||
|
||||
componentWillReceiveProps(nextProps) {
|
||||
if (nextProps.editMode !== this.state.editMode) {
|
||||
this.setState({editMode: nextProps.editMode});
|
||||
//this.props.tile.setVisibility(nextProps.editMode || this.state.settings.enabled);
|
||||
}
|
||||
if (JSON.stringify(nextProps.ignoreIndicators) !== JSON.stringify(this.state.ignoreIndicators)) {
|
||||
this.setState({ignoreIndicators: nextProps.ignoreIndicators});
|
||||
}
|
||||
}
|
||||
|
||||
roundValue(value, decimals) {
|
||||
if (decimals !== undefined || typeof this.state.settings.decimals !== 'undefined') {
|
||||
return value.toFixed(decimals !== undefined ? decimals : this.state.settings.decimals);
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
// following indicators are supported
|
||||
// indicator.working
|
||||
// indicator.lowbat
|
||||
// indicator.maintenance.lowbat
|
||||
// indicator.maintenance.unreach
|
||||
// indicator.maintenance
|
||||
// indicator.error
|
||||
getIndicators() {
|
||||
let result = [];
|
||||
const that = this;
|
||||
let titles = [];
|
||||
this.channelInfo.states.forEach(state => {
|
||||
if (state.indicator && state.id) {
|
||||
const pos = state.id.lastIndexOf('.');
|
||||
if (pos !== -1 && this.state.ignoreIndicators.indexOf(state.id.substring(pos + 1)) !== -1) {
|
||||
return;
|
||||
}
|
||||
let Icon = state.icon;
|
||||
if (state.id === that.indicators.directionId) {
|
||||
const strVal = that.state[state.id];
|
||||
if (strVal === that.direction.up) {
|
||||
Icon = IconDirectionUp;
|
||||
} else if (strVal === that.direction.down) {
|
||||
Icon = IconDirectionDown;
|
||||
} else if (strVal === that.direction.undef) {
|
||||
Icon = IconDirection;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
} else if ((!that.state[state.id] && !state.inverted) || (that.state[state.id] && state.inverted)) {
|
||||
return;
|
||||
}
|
||||
|
||||
titles.push(I18n.t(state.id.split('.').pop()));
|
||||
|
||||
result.push((<Icon
|
||||
key={that.key + 'indicator-' + state.name.toLowerCase()}
|
||||
className={'indicator-' + state.name.toLowerCase()}
|
||||
style={Object.assign({}, Theme.tile.tileIndicator, {color: state.color})}
|
||||
/>));
|
||||
}
|
||||
});
|
||||
|
||||
if (result.length) {
|
||||
if (this.errorText) {
|
||||
titles.push(this.errorText)
|
||||
}
|
||||
return (<div key={this.key + 'indicators'} style={Theme.tile.tileIndicators} title={titles.join(', ')}>{result}</div>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getDefaultIcon() {
|
||||
if (this.defaultIcon !== null) {
|
||||
return this.defaultIcon;
|
||||
}
|
||||
if (this.id) {
|
||||
let icon = Utils.getObjectIcon(this.id, this.props.objects[this.id]);
|
||||
if (!icon) {
|
||||
let parentId = SmartGeneric.getParentId(this.id);
|
||||
if (this.props.objects[parentId] && this.props.objects[parentId].type === 'channel') {
|
||||
icon = Utils.getObjectIcon(parentId, this.props.objects[parentId]);
|
||||
if (!icon) {
|
||||
parentId = SmartGeneric.getParentId(parentId);
|
||||
if (this.props.objects[parentId] && this.props.objects[parentId].type === 'device') {
|
||||
icon = Utils.getObjectIcon(parentId, this.props.objects[parentId]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (icon) {
|
||||
this.defaultIcon = icon;
|
||||
} else {
|
||||
this.defaultIcon = '';
|
||||
}
|
||||
} else {
|
||||
this.defaultIcon = '';
|
||||
}
|
||||
return this.defaultIcon;
|
||||
}
|
||||
|
||||
getDialogSettings(settings) {
|
||||
settings = settings || [];
|
||||
|
||||
settings.unshift({
|
||||
name: 'background',
|
||||
value: this.state.settings.background || '',
|
||||
aspect: this.state.settings.doubleSize ? 2 : 1,
|
||||
type: 'image'
|
||||
});
|
||||
|
||||
if (this.doubleState) {
|
||||
settings.unshift({
|
||||
name: 'iconOff',
|
||||
value: this.state.settings.iconOff || '',
|
||||
type: 'icon'
|
||||
});
|
||||
}
|
||||
settings.unshift({
|
||||
name: 'icon',
|
||||
value: this.state.settings.icon || '',
|
||||
type: 'icon'
|
||||
});
|
||||
// If colors for on and for off
|
||||
if (this.doubleState) {
|
||||
settings.unshift({
|
||||
name: 'colorOff',
|
||||
value: this.state.settings.colorOff || '',
|
||||
type: 'color'
|
||||
});
|
||||
}
|
||||
|
||||
settings.unshift({
|
||||
name: 'doubleSize',
|
||||
value: this.state.settings.doubleSize || '',
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'colorOn',
|
||||
value: this.state.settings.colorOn || '',
|
||||
type: 'color'
|
||||
});
|
||||
settings.unshift({
|
||||
name: 'name',
|
||||
value: this.state.settings.name || '',
|
||||
type: 'string'
|
||||
});
|
||||
if (this.id) {
|
||||
/*settings.unshift({
|
||||
name: 'useCommon',getObjectIcon
|
||||
value: this.state.settings.useCommon || false,
|
||||
type: 'boolean'
|
||||
});*/
|
||||
let icon = this.getDefaultIcon();
|
||||
if (icon) {
|
||||
settings.unshift({
|
||||
name: 'useDefaultIcon',
|
||||
value: this.state.settings.useDefaultIcon || '',
|
||||
type: 'boolean',
|
||||
icon
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
saveDialogSettings(settings, cb) {
|
||||
if (settings) {
|
||||
settings.enabled = this.state.settings.enabled;
|
||||
if (settings.background && typeof settings.background === 'object') {
|
||||
settings.background.name = this.settingsId.replace(/[\s*?./\\]/g, '_') + '.' + settings.background.name.toLowerCase().split('.').pop();
|
||||
}
|
||||
}
|
||||
|
||||
this.saveSettings(settings, newSettings => {
|
||||
if (settings.background) {
|
||||
this.props.tile.setBackgroundImage(settings.background + '?ts=' + Date.now(), true);
|
||||
} else {
|
||||
this.props.tile.setBackgroundImage('', false);
|
||||
}
|
||||
cb && cb(newSettings);
|
||||
});
|
||||
}
|
||||
|
||||
showSettings() {
|
||||
this.setState({showSettings: true});
|
||||
}
|
||||
|
||||
onSettingsClose() {
|
||||
this.setState({showSettings: false});
|
||||
}
|
||||
|
||||
getAdditionalName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
// following function used
|
||||
// getStateText
|
||||
// getIcon
|
||||
// getFirstName
|
||||
// getAdditionalName
|
||||
//
|
||||
getStandardContent(stateId, noPointerEvents) {
|
||||
let styleState;
|
||||
let styleName;
|
||||
let styleText;
|
||||
if (this.width === 2) {
|
||||
styleText = Object.assign({}, Theme.tile.tileText2);
|
||||
styleName = Object.assign({}, Theme.tile.tileName2, this.state.nameStyle || {});
|
||||
styleState = this.getStateText ? Object.assign(
|
||||
{},
|
||||
Theme.tile.tileState2,
|
||||
stateId ? (this.state[stateId] ? Theme.tile.tileStateOn : Theme.tile.tileStateOff) : {}
|
||||
) : null;
|
||||
} else {
|
||||
styleText = Object.assign({}, Theme.tile.tileText);
|
||||
styleName = Object.assign({}, Theme.tile.tileName, this.state.nameStyle || {});
|
||||
styleState = this.getStateText ? Object.assign(
|
||||
{},
|
||||
Theme.tile.tileState,
|
||||
stateId ? (this.state[stateId] ? Theme.tile.tileStateOn : Theme.tile.tileStateOff) : {}
|
||||
) : null;
|
||||
if (this.state.settings.background) {
|
||||
styleName.marginTop = 4;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.state.settings.background) {
|
||||
styleText.color = 'black';
|
||||
styleText.background = 'rgba(255,255,255,0.7)';
|
||||
}
|
||||
|
||||
return [
|
||||
this.getIcon ? (<div key={this.key + 'tile-icon'} style={noPointerEvents ? {pointerEvents: 'none'} : {}}>{this.getIcon()}</div>): null,
|
||||
(<div key={this.key + 'tile-text'} style={styleText}>
|
||||
<div style={styleName}>{this.getFirstName ? this.getFirstName() : this.state.settings.name}{this.getAdditionalName()}</div>
|
||||
{this.getStateText ? (<div style={styleState}>{this.getStateText()}</div>) : null}
|
||||
</div>)
|
||||
];
|
||||
}
|
||||
|
||||
wrapContent(content) {
|
||||
if (this.state.editMode) {
|
||||
return [
|
||||
(<div key={this.key + 'type'} style={{display: 'none'}}>{this.channelInfo.type}</div>),
|
||||
(<div key={this.key + 'wrapper'}>
|
||||
{this.state.settings.enabled ?
|
||||
[(<div onClick={this.toggleEnabled.bind(this)} key={this.key + 'icon-check'} style={Theme.tile.editMode.checkIcon} className="edit-buttons">
|
||||
<IconCheck size={'50%'} style={Theme.tile.editMode.buttonIcon}/>
|
||||
</div>),
|
||||
(<div onClick={this.showSettings.bind(this)} key={this.key + 'icon-edit'} style={Theme.tile.editMode.editIcon} className="edit-buttons">
|
||||
<IconEdit size={'50%'} style={Object.assign({}, Theme.tile.editMode.buttonIcon, {width: '80%', marginLeft: '20%'})}/>
|
||||
</div>
|
||||
)]
|
||||
:
|
||||
(<div onClick={this.toggleEnabled.bind(this)} key={this.key + '.icon-check'} style={Theme.tile.editMode.removeIcon}>
|
||||
<IconRemoved size={'100%'} style={Theme.tile.editMode.buttonIconRemoved}/>
|
||||
</div>)
|
||||
}
|
||||
{content}
|
||||
</div>),
|
||||
this.state.showSettings ? (
|
||||
<Dialog key={this.key + 'settings'}
|
||||
windowWidth={this.props.windowWidth}
|
||||
name={this.state.settings.name}
|
||||
dialogKey={this.key + 'settings'}
|
||||
settings={this.getDialogSettings()}
|
||||
objects={this.props.objects}
|
||||
settingsId={this.settingsId}
|
||||
onSave={this.saveDialogSettings.bind(this)}
|
||||
onClose={this.onSettingsClose.bind(this)}
|
||||
/>): null];
|
||||
} else if (this.state.settings.enabled) {
|
||||
return [
|
||||
(<div key={this.key + 'type'} style={{display: 'none'}}>{this.channelInfo.type}</div>),
|
||||
(<div key={this.key + 'wrapper'} >
|
||||
{this.showCorner ? (<div key={this.key + 'corner'} onMouseDown={this.onLongClick.bind(this)} className="corner" style={Theme.tile.tileCorner}/>) : null}
|
||||
{this.getIndicators()}
|
||||
{content}
|
||||
</div>)
|
||||
];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static getNameFontSize(name) {
|
||||
return name && name.length >= 15 ? 12 : (name && name.length > 10 ? 14 : 16);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.state.editMode && !this.state.settings.enabled) {
|
||||
return null;
|
||||
} else {
|
||||
return this.wrapContent(this.settings.name || this.getObjectNameCh());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartGeneric;
|
||||
|
244
src/src/States/SmartInfo.js
Normal file
@ -0,0 +1,244 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import IconThermometer from '../icons/ThermometerSimple';
|
||||
import IconHydro from '../icons/Humidity';
|
||||
import {MdInfo as IconInfo} from 'react-icons/md';
|
||||
import Utils from '../Utils';
|
||||
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
import Dialog from '../Dialogs/SmartDialogInfo';
|
||||
import PropTypes from 'prop-types';
|
||||
|
||||
const invisibleDefaultRoles = [
|
||||
/^timer.off$/,
|
||||
/^inhibit$/,
|
||||
];
|
||||
|
||||
class SmartInfo extends SmartGeneric {
|
||||
// expected:
|
||||
static propTypes = {
|
||||
tile: PropTypes.object.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
states: PropTypes.object.isRequired,
|
||||
onCollectIds: PropTypes.func,
|
||||
onControl: PropTypes.func
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
let hasControls = false;
|
||||
if (this.channelInfo.states) {
|
||||
let infoIDs = this.channelInfo.states.filter(state => state.id && state.name === 'ACTUAL').map(state => state.id);
|
||||
// place numbers first
|
||||
if (infoIDs.length > 1) {
|
||||
infoIDs.sort((a, b) => {
|
||||
const objA = this.props.objects[a];
|
||||
const objB = this.props.objects[b];
|
||||
const typeA = objA && objA.common && objA.common.type;
|
||||
const typeB = objB && objB.common && objB.common.type;
|
||||
if (typeA && !typeB) return 1;
|
||||
if (!typeA && typeB) return -1;
|
||||
if (typeA === 'number' && typeB !== 'number') return -1;
|
||||
if (typeA !== 'number' && typeB === 'number') return 1;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
if (infoIDs[0]) {
|
||||
this.id = infoIDs[0];
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
if (infoIDs[1]) {
|
||||
this.secondary = {
|
||||
id: infoIDs[1]
|
||||
};
|
||||
}
|
||||
const name = this.getObjectNameCh();
|
||||
this.infos = infoIDs.map(id => SmartInfo.getObjectAttributes(this.props.objects, id, name));
|
||||
hasControls = !!this.infos.find(item => item.common && item.common.write);
|
||||
}
|
||||
|
||||
if (!this.infos.find(state => !invisibleDefaultRoles.find(test => !test.test(state.role)))) {
|
||||
this.defaultEnabling = false;
|
||||
}
|
||||
|
||||
// make tile with opacity 1
|
||||
this.props.tile.state.state = true;
|
||||
|
||||
if (this.infos && (this.infos.length > 2 || hasControls)) {
|
||||
this.stateRx.showDialog = false; // support dialog in this tile (used in generic class)
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: this.showCorner
|
||||
});
|
||||
|
||||
this.key = 'smart-info-' + this.id + '-';
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
static getObjectAttributes(objects, id, channelName) {
|
||||
if (!id || !objects[id] || !objects[id].common) return null;
|
||||
const role = objects[id].common.role || '';
|
||||
const unit = objects[id].common.unit || '';
|
||||
let title = objects[id].common.name || id.split('.').pop();
|
||||
if (!title) {
|
||||
title = id.split('.').pop();
|
||||
}
|
||||
if (typeof title === 'object') {
|
||||
title = title[I18n.getLanguage()] || title.en || id.split('.').pop();
|
||||
}
|
||||
|
||||
title = title.replace(/[._]/g, ' ').trim();
|
||||
if (title.toUpperCase() !== channelName.toUpperCase()) {
|
||||
title = title.replace(channelName, '').trim();
|
||||
}
|
||||
|
||||
title = Utils.splitCamelCase(title);
|
||||
|
||||
if (role.match(/humidity/i)) {
|
||||
return {
|
||||
id: id,
|
||||
icon: IconHydro,
|
||||
iconStyle: {color: '#0056c3'},
|
||||
unit: unit ? ' ' + unit : ' %',
|
||||
role: role,
|
||||
name: title,
|
||||
common: objects[id].common
|
||||
}
|
||||
} else if (role.match(/temperature/i)) {
|
||||
return {
|
||||
id: id,
|
||||
icon: IconThermometer,
|
||||
iconStyle: {color: '#e54100'},
|
||||
unit: unit ? ' ' + unit : '°',
|
||||
name: title,
|
||||
role: role,
|
||||
common: objects[id].common
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
id: id,
|
||||
unit: unit ? ' ' + unit : '',
|
||||
icon: Utils.getObjectIcon(id, objects[id]),
|
||||
name: title,
|
||||
role: role,
|
||||
common: objects[id].common
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (this.infos && this.infos.find(e => e.id === id)) {
|
||||
const newState = {};
|
||||
newState[id] = state.val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt=" " style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt=" " style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
const Icon = this.infos[0].icon || IconInfo;
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.infos[0].iconStyle || {})} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
const state = this.state[this.id];
|
||||
return state === undefined || state === null ? '?' : state + this.infos[0].unit;
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
if (!this.infos || !this.infos[1] || !this.infos[1].id || this.state[this.infos[1].id] === undefined || this.state[this.infos[1].id] === null) {
|
||||
return null;
|
||||
}
|
||||
let val = this.state[this.infos[1].id];
|
||||
const icon = this.infos[1].icon;
|
||||
let Icon;
|
||||
if (icon) {
|
||||
if (typeof icon === 'object') {
|
||||
Icon = icon;
|
||||
Icon = (<Icon style={Object.assign({}, Theme.tile.secondary.icon, this.infos[1].iconStyle || {})} />);
|
||||
} else {
|
||||
Icon = (<img alt={' '} src={icon} style={Object.assign({}, Theme.tile.secondary.icon, this.infos[1].iconStyle || {})}/>)
|
||||
}
|
||||
}
|
||||
|
||||
return (<div key={this.key + 'tile-secondary'} className="tile-text-second" style={Theme.tile.secondary.div} title={this.infos[1].name}>
|
||||
{Icon}
|
||||
<span style={Theme.tile.secondary.text}>{val + this.infos[1].unit}</span>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getNumberOfValuesIndicator() {
|
||||
if (this.infos.length <= 2) return null;
|
||||
return (<div key={this.key + 'tile-number'} style={Theme.tile.tileNumber} title={I18n.t('Show %s values', this.infos.length)}>{this.infos.length}</div>);
|
||||
}
|
||||
|
||||
getFirstName() {
|
||||
this.firstName = this.firstName || I18n.t(Utils.CapitalWords(this.id.split('.').pop()));
|
||||
|
||||
return [(<span key={this.key + 'tile-name'}>{this.state.settings.name} </span>),(<span key={this.key + 'tile-first-name'} style={Theme.tile.tileNameSmall}>{this.firstName}</span>)];
|
||||
}
|
||||
|
||||
setValue(id, value) {
|
||||
console.log('Control ' + id + ' = ' + value);
|
||||
this.props.onControl(id, value);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.actualId),
|
||||
this.getSecondaryDiv(),
|
||||
this.getNumberOfValuesIndicator(),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
dialogKey={this.key + 'dialog'}
|
||||
windowWidth={this.props.windowWidth}
|
||||
points={this.infos}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
name={this.state.settings.name}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
objects={this.props.objects}
|
||||
states={this.props.states}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartInfo;
|
||||
|
173
src/src/States/SmartInstance.js
Normal file
@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Button from '@material-ui/core/Button';
|
||||
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
|
||||
import {MdPlayArrow as IconPlay} from 'react-icons/md';
|
||||
import {MdPause as IconPause} from 'react-icons/md';
|
||||
//import IconChecked from 'react-icons/lib/md/check-circle';
|
||||
//import IconUnchecked from 'react-icons/lib/md/cancel';
|
||||
|
||||
class SmartInstance extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'ALIVE');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
const parts = this.id.split('.');
|
||||
parts.pop();
|
||||
|
||||
this.instanceNumber = parts[parts.length - 1];
|
||||
this.instanceId = parts.join('.');
|
||||
|
||||
if (this.props.objects[this.instanceId].type !== 'instance') {
|
||||
this.id = '';
|
||||
this.componentReady();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.props.objects[this.instanceId].common.onlyWWW) {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'UNREACH');
|
||||
this.connectedId = state ? state.id : this.id;
|
||||
}
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: false
|
||||
});
|
||||
this.key = 'smart-instance-' + this.id + '-';
|
||||
|
||||
// this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
updateState(id, state) {
|
||||
const newState = {};
|
||||
const val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON';
|
||||
if (id === this.id) {
|
||||
newState[id] = val;
|
||||
if (this.connectedId) {
|
||||
if (val) {
|
||||
newState[this.connectedId] = !this.connectedState;
|
||||
} else {
|
||||
newState[this.connectedId] = false;
|
||||
}
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
} else if (id === this.connectedId) {
|
||||
this.connectedState = state.val;
|
||||
if (this.state[this.id]) {
|
||||
state.val = !state.val;
|
||||
} else {
|
||||
state.val = false;
|
||||
}
|
||||
super.updateState(id, state);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
toggle() {
|
||||
this.props.onControl(this.instanceId, !this.props.objects[this.instanceId].common.enabled, 'common.enabled');
|
||||
}
|
||||
|
||||
onTileClick() {
|
||||
this.toggle();
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
const img = '/' + this.props.objects[this.instanceId].common.name + '.admin/' + this.props.objects[this.instanceId].common.icon;
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon)} className="tile-icon">
|
||||
<img height={'100%'} src={img} alt={'i' || this.state.settings.name}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
const common = this.props.objects[this.instanceId].common;
|
||||
if (common.onlyWWW) {
|
||||
return common.enabled ? I18n.t('enabled') : I18n.t('disabled');
|
||||
} else {
|
||||
return this.state[this.id] ? I18n.t('running') : I18n.t('stopped');
|
||||
}
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
let Icon;
|
||||
let text;
|
||||
let color;
|
||||
|
||||
if (this.props.objects[this.instanceId].common.enabled) {
|
||||
Icon = IconPause;
|
||||
text = I18n.t('disable adapter');
|
||||
color = '#90ee90';
|
||||
} else {
|
||||
Icon = IconPlay;
|
||||
text = I18n.t('enable adapter');
|
||||
color = '#f99';
|
||||
}
|
||||
|
||||
return (<div key={this.key + 'tile-secondary'} className="tile-text-second"
|
||||
style={Theme.tile.secondary.button} title={text}>
|
||||
<Button variant="fab" mini onClick={this.toggle.bind(this)} style={{background: color, boxShadow: 'none'}} aria-label={text}>
|
||||
<Icon />
|
||||
</Button>
|
||||
</div>);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.props.objects[this.instanceId].type !== 'instance') {
|
||||
return null;
|
||||
}
|
||||
const style = Object.assign(
|
||||
{},
|
||||
this.state[this.id] ? Theme.tile.tileStateOn : Theme.tile.tileStateOff,
|
||||
{
|
||||
color: this.state[this.id] ? Theme.palette.instanceRunning : Theme.palette.instanceStopped,
|
||||
position: 'absolute',
|
||||
bottom: 0
|
||||
}
|
||||
);
|
||||
|
||||
return this.wrapContent([
|
||||
(<div key={this.key + 'tile-icon'} className="tile-icon">{this.getIcon()}</div>),
|
||||
this.getSecondaryDiv(),
|
||||
(<div key={this.key + 'tile-text'}
|
||||
className="tile-text"
|
||||
style={Object.assign({}, Theme.tile.tileText, {minHeight: 56})}>
|
||||
<div className="tile-channel-name" style={Object.assign({}, Theme.tile.tileName, this.state.nameStyle)}>{this.state.settings.name}</div>
|
||||
<div className="tile-state-text" style={Object.assign({}, Theme.tile.tileState, style)}>{this.getStateText()}</div>
|
||||
</div>)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartInstance;
|
||||
|
186
src/src/States/SmartLock.js
Normal file
@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Moment from 'react-moment';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import {MdLock as IconLockClosed} from 'react-icons/md';
|
||||
import {MdLockOpen as IconLockOpened} from 'react-icons/md';
|
||||
import {MdClose as IconClose} from 'react-icons/md'
|
||||
import IconDoorOpened from '../icons/DoorOpened';
|
||||
|
||||
import Dialog from '@material-ui/core/Dialog';
|
||||
import DialogActions from '@material-ui/core/DialogActions';
|
||||
import DialogTitle from '@material-ui/core/DialogTitle';
|
||||
import Button from '@material-ui/core/Button';
|
||||
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
|
||||
const style = {
|
||||
icon: {
|
||||
fontSize: 32
|
||||
}
|
||||
};
|
||||
|
||||
class SmartLock extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'OPEN');
|
||||
this.openId = state && state.id;
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
|
||||
this.stateRx.dialog = false;
|
||||
|
||||
this.key = 'smart-lock-' + this.id + '-';
|
||||
this.iconColorOn = Theme.palette.lampOn;
|
||||
this.iconColorOff = '';
|
||||
this.textOn = 'opened';
|
||||
this.textOff = 'closed';
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.actualId) {
|
||||
const val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON';
|
||||
const newState = {};
|
||||
newState[id] = val;
|
||||
|
||||
if (this.showTime && state.lc) {
|
||||
this.lastChange = state.lc;
|
||||
} else {
|
||||
this.lastChange = 0;
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
const isOn = this.state[this.id] === '1' || this.state[this.id] === 1 || this.state[this.id] === true || this.state[this.id] === 'true' || this.state[this.id] === 'on' || this.state[this.id] === 'ON';
|
||||
const color = isOn ? this.iconColorOn : this.iconColorOff;
|
||||
let style = color ? {color} : {};
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={isOn ? this.state.settings.icon : this.state.settings.iconOff || this.state.settings.icon} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
const Icon = isOn ? IconLockOpened : IconLockClosed;
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex:1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, style)} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
const state = this.state[this.id];
|
||||
if (state === undefined || state === null || !this.lastChange || !this.showTime) {
|
||||
const isOn = this.state[this.id] === '1' || this.state[this.id] === 1 || this.state[this.id] === true || this.state[this.id] === 'true' || this.state[this.id] === 'on' || this.state[this.id] === 'ON';
|
||||
return isOn ? I18n.t(this.textOn) : I18n.t(this.textOff);
|
||||
} else {
|
||||
return (<Moment style={{fontSize: 12}} date={this.lastChange} interval={15} fromNow locale={I18n.getLanguage()}/>);
|
||||
}
|
||||
}
|
||||
|
||||
onTileClick() {
|
||||
this.setState({dialog: true});
|
||||
}
|
||||
|
||||
onAction(action) {
|
||||
switch (action) {
|
||||
case 'openLock':
|
||||
this.props.onControl(this.id, true);
|
||||
break;
|
||||
|
||||
case 'closeLock':
|
||||
this.props.onControl(this.id, false);
|
||||
break;
|
||||
|
||||
case 'openDoor':
|
||||
this.props.onControl(this.openId, true);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
// No idea why direct control does not work
|
||||
setTimeout(() => {
|
||||
this.setState({dialog: false});
|
||||
}, 0);
|
||||
}
|
||||
|
||||
getDialog() {
|
||||
return (<Dialog
|
||||
key={this.key + 'tile-dialog'}
|
||||
style={{zIndex: 2101}}
|
||||
open={this.state.dialog}
|
||||
aria-labelledby={I18n.t('Lock state')}
|
||||
aria-describedby={I18n.t('Select action!')}
|
||||
onEscapeKeyDown={() => this.setState({dialog: false})}
|
||||
>
|
||||
<DialogTitle id="alert-dialog-title" style={{textAlign: 'center'}}>
|
||||
{I18n.t('Select action')}
|
||||
<Button style={style.icon} onClick={() => this.onAction('close')}><IconClose/></Button>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogActions>
|
||||
<Button style={style.icon} title={I18n.t('Open lock')} onClick={() => this.onAction('openLock')} color="primary"><IconLockOpened/></Button>
|
||||
<Button style={style.icon} title={I18n.t('Close lock')} onClick={() => this.onAction('closeLock')} color="secondary" autoFocus><IconLockClosed/></Button>
|
||||
{this.openId ? (<Button style={style.icon} title={I18n.t('Open door')} onClick={() => this.onAction('openDoor')} color="secondary"><IconDoorOpened width={32} height={32}/></Button>) : null}
|
||||
</DialogActions>
|
||||
</Dialog>);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.actualId),
|
||||
this.state.dialog ? this.getDialog() : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartLock;
|
||||
|
373
src/src/States/SmartMedia.js
Normal file
@ -0,0 +1,373 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import Button from '@material-ui/core/Button';
|
||||
|
||||
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 Theme from '../theme';
|
||||
// import cover from '../assets/cover.png';
|
||||
import Dialog from '../Dialogs/SmartDialogMedia';
|
||||
|
||||
const style = {
|
||||
info: {
|
||||
div: {
|
||||
background: 'rgba(0,0,0,0.55)',
|
||||
position: 'absolute',
|
||||
bottom: 50,
|
||||
width: 'calc(100% + 1rem)',
|
||||
left: '-0.5rem',
|
||||
paddingLeft: '1.2rem'
|
||||
},
|
||||
name: {
|
||||
fontSize: 10,
|
||||
fontWeight: 'normal',
|
||||
color: 'white'
|
||||
},
|
||||
artist: {
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal',
|
||||
color: 'white'
|
||||
},
|
||||
album: {
|
||||
fontSize: 16,
|
||||
fontWeight: 'normal',
|
||||
color: 'white'
|
||||
},
|
||||
title: {
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal',
|
||||
color: 'white'
|
||||
}
|
||||
},
|
||||
control: {
|
||||
div: {
|
||||
background: 'rgba(255,255,255,0.9)',
|
||||
position: 'absolute',
|
||||
width: 'calc(100% + 1rem)',
|
||||
bottom: 0,
|
||||
left: '-0.5rem',
|
||||
height: 48,
|
||||
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,
|
||||
minHeight: 24,
|
||||
marginLeft: 3,
|
||||
verticalAlign: 'middle',
|
||||
boxShadow: 'none',
|
||||
background: 'rgba(255,255,255,1)'
|
||||
},
|
||||
play: {
|
||||
|
||||
},
|
||||
pause: {
|
||||
background: '#40EE40'
|
||||
},
|
||||
name: {
|
||||
position: 'absolute',
|
||||
left: '1.2rem',
|
||||
bottom: 2,
|
||||
fontSize: 14,
|
||||
color: 'rgba(0,0,0,0.6)'
|
||||
}
|
||||
},
|
||||
time: {
|
||||
div: {
|
||||
|
||||
},
|
||||
elapsed: {
|
||||
|
||||
},
|
||||
duration: {
|
||||
|
||||
},
|
||||
slider: {
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class SmartMedia extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.ids = {
|
||||
info: {
|
||||
cover: null,
|
||||
artist: null,
|
||||
album: null,
|
||||
title: null
|
||||
},
|
||||
buttons: {
|
||||
play: null,
|
||||
pause: null,
|
||||
stop: null,
|
||||
prev: null,
|
||||
next: null
|
||||
},
|
||||
control: {
|
||||
state: null,
|
||||
elapsed: null,
|
||||
duration: null,
|
||||
seek: null
|
||||
},
|
||||
volume: {
|
||||
set: null,
|
||||
actual: null,
|
||||
mute: null
|
||||
},
|
||||
mode: {
|
||||
repeat: null,
|
||||
shuffle: null
|
||||
}
|
||||
};
|
||||
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'STATE');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
this.ids.control.state = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'COVER');
|
||||
this.ids.info.cover = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ARTIST');
|
||||
this.ids.info.artist = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ALBUM');
|
||||
this.ids.info.album = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TITLE');
|
||||
this.ids.info.title = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PLAY');
|
||||
this.ids.buttons.play = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PAUSE');
|
||||
this.ids.buttons.pause = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'STOP');
|
||||
this.ids.buttons.stop = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'NEXT');
|
||||
this.ids.buttons.next = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PREV');
|
||||
this.ids.buttons.prev = state && state.id;
|
||||
|
||||
// no automatic subscription
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DURATION');
|
||||
this.ids.control.duration = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'SEEK');
|
||||
this.ids.control.seek = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ELAPSED');
|
||||
this.ids.control.elapsed = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'VOLUME');
|
||||
this.ids.volume.set = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'VOLUME_ACTUAL');
|
||||
this.ids.volume.actual = state ? state.id : this.ids.volume.set;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'MUTE');
|
||||
this.ids.volume.mute = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'SHUFFLE');
|
||||
this.ids.mode.shuffle = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'REPEAT');
|
||||
this.ids.mode.repeat = state && state.id;
|
||||
}
|
||||
|
||||
this.width = 2;
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
this.key = 'smart-switch-' + this.id + '-';
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
|
||||
// this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.ids.info.cover) {
|
||||
let url = state && state.val;
|
||||
if (url) {
|
||||
// url = cover;
|
||||
if (url.match(/\?.+$/)) {
|
||||
url += '&ts=' + Date.now();
|
||||
} else {
|
||||
url += '?ts=' + Date.now();
|
||||
}
|
||||
}
|
||||
this.props.tile.setBackgroundImage(url || '');
|
||||
this.setState({[id]: url});
|
||||
} else
|
||||
if (id === this.ids.info.album) {
|
||||
this.setState({[id]: state.val});
|
||||
} else
|
||||
if (id === this.ids.info.artist) {
|
||||
this.setState({[id]: state.val});
|
||||
} else
|
||||
if (id === this.ids.info.title) {
|
||||
this.setState({[id]: state.val});
|
||||
} else
|
||||
if (this.id === id && state.ack) {
|
||||
const val =
|
||||
state.val === 'true' ||
|
||||
state.val === true ||
|
||||
state.val === 'PLAY' ||
|
||||
state.val === 'play' ||
|
||||
state.val === 1 ||
|
||||
state.val === '1';
|
||||
this.setState({[id]: val});
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
if (this.state[this.ids.info.cover]) {
|
||||
return null;
|
||||
} else {
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%'}}/>);
|
||||
} else {
|
||||
customIcon = (<IconNote width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Theme.tile.tileIcon} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
onButton(id) {
|
||||
this.props.onControl(id, true);
|
||||
}
|
||||
|
||||
getDialogSettings() {
|
||||
const settings = super.getDialogSettings();
|
||||
|
||||
// remove doubleSize from list
|
||||
settings.forEach((item, i) => {
|
||||
if (item.name === 'doubleSize') {
|
||||
settings.splice(i, 1);
|
||||
return false
|
||||
}
|
||||
});
|
||||
|
||||
if (this.ids.buttons.stop) {
|
||||
settings.unshift({
|
||||
name: 'showStop',
|
||||
value: this.state.settings.showStop || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
getControlsDiv() {
|
||||
return (<div key={this.key + 'tile-control'} style={style.control.div}>
|
||||
<div style={style.control.name} title={this.state.settings.name}>{this.state.settings.name}</div>
|
||||
{this.ids.buttons.prev ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.prev)} style={style.control.prev} aria-label="prev"><IconPrev/></Button>) : null}
|
||||
<Button variant="fab" mini
|
||||
onClick={() => this.onButton(this.state[this.id] ? this.ids.buttons.pause : this.ids.buttons.play)}
|
||||
style={this.state[this.id] ? style.control.pause : style.control.play} aria-label="play pause">
|
||||
{this.state[this.id] ? (<IconPause/>) : (<IconPlay/>)}
|
||||
</Button>
|
||||
{this.state.settings.showStop && this.ids.buttons.stop ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.stop)} style={style.control.stop} aria-label="stop"><IconStop/></Button>) : null}
|
||||
{this.ids.buttons.next ? (<Button variant="fab" mini onClick={() => this.onButton(this.ids.buttons.next)} style={style.control.prev} aria-label="netx"><IconNext/></Button>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getInfoDiv() {
|
||||
return (<div key={this.key + 'tile-info'} style={style.info.div}>
|
||||
{this.ids.info.artist && this.state[this.ids.info.artist] ? (<div style={style.info.artist}>{this.state[this.ids.info.artist]}</div>) : null}
|
||||
{this.ids.info.album && this.state[this.ids.info.album] ? (<div style={style.info.album}>{this.state[this.ids.info.album]}</div>) : null}
|
||||
{this.ids.info.title && this.state[this.ids.info.title] ? (<div style={style.info.title}>{this.state[this.ids.info.title]}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
(<div key={this.key + 'tile-icon'} className="tile-icon">{this.getIcon()}</div>),
|
||||
this.getInfoDiv(),
|
||||
this.getControlsDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog dialogKey={this.key + 'dialog'}
|
||||
key={this.key + 'dialog'}
|
||||
name={this.state.settings.name}
|
||||
enumNames={this.props.enumNames}
|
||||
settings={this.state.settings}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
ids={this.ids}
|
||||
windowWidth={this.props.windowWidth}
|
||||
onControl={this.props.onControl}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartMedia;
|
||||
|
173
src/src/States/SmartSlider.js
Normal file
@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 CircularProgress from '@material-ui/core/CircularProgress';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import {TiLightbulb as Icon} from 'react-icons/ti';
|
||||
import Theme from '../theme';
|
||||
import Dialog from '../Dialogs/SmartDialogSlider';
|
||||
|
||||
class SmartSlider extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
this.max = this.props.objects[this.actualId].common.max;
|
||||
this.min = this.props.objects[this.actualId].common.min;
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
|
||||
this.unit = this.props.objects[this.actualId].common.unit;
|
||||
this.unit = this.unit ? ' ' + this.unit : '';
|
||||
}
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
this.stateRx.setValue = null;
|
||||
this.key = 'smart-slider-' + this.id + '-';
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.icon = Icon;
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
const val = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
|
||||
if (this.actualId === id || (this.id === id && this.id === this.actualId && state.ack)) {
|
||||
if (!isNaN(val)) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
|
||||
const tileState = val !== this.min;
|
||||
this.props.tile.setState({state: tileState});
|
||||
} else {
|
||||
newState[id] = null;
|
||||
this.setState(newState);
|
||||
this.props.tile.setState({state: false});
|
||||
}
|
||||
|
||||
// hide desired value
|
||||
if (this.state.setValue === newState[id] && state.ack) {
|
||||
this.setState({setValue: null});
|
||||
}
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
} else if (id === this.id) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
setValue(value) {
|
||||
console.log('Control ' + this.id + ' = ' + value);
|
||||
if (this.actualId !== this.id) {
|
||||
this.setState({executing: true, setValue: value});
|
||||
}
|
||||
this.props.onControl(this.id, value);
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%'}}/>);
|
||||
} else {
|
||||
let IconCustom = this.icon;
|
||||
if (IconCustom) {
|
||||
customIcon = (<IconCustom width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (customIcon) {
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.state[this.actualId] !== this.min ? {color: Theme.palette.lampOn} : {})} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
getDialogSettings () {
|
||||
const settings = super.getDialogSettings();
|
||||
settings.push({
|
||||
name: 'decimals',
|
||||
value: this.state.settings.decimals || 0,
|
||||
type: 'number',
|
||||
min: 0,
|
||||
max: 6
|
||||
});
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.state[this.actualId] === null || this.state[this.actualId] === undefined) {
|
||||
return '---';
|
||||
} else {
|
||||
if (this.workingId && this.state[this.workingId] && this.state.setValue !== null && this.state.setValue !== undefined) {
|
||||
return this.roundValue(this.state[this.id]) + this.unit + ' → ' + this.state.setValue + this.unit;
|
||||
} else {
|
||||
return this.roundValue(this.state[this.id]) + this.unit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(null, true),
|
||||
this.state.showDialog ?
|
||||
<Dialog dialogKey={this.key + 'dialog'}
|
||||
key={this.key + 'dialog'}
|
||||
startValue={this.state[this.id]}
|
||||
windowWidth={this.props.windowWidth}
|
||||
min={this.min}
|
||||
max={this.max}
|
||||
unit={this.unit}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
type={Dialog.types.value}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartSlider;
|
||||
|
263
src/src/States/SmartState.js
Normal file
@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 Moment from 'react-moment';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import IconWindowOpened from '../icons/WindowOpened';
|
||||
import IconWindowClosed from '../icons/WindowClosed';
|
||||
import IconMotionOn from '../icons/MotionOn';
|
||||
import IconMotionOff from '../icons/MotionOff';
|
||||
import IconFireOn from '../icons/FireOn';
|
||||
import IconFireOff from '../icons/FireOff';
|
||||
import IconFloodOn from '../icons/FloodOn';
|
||||
import IconFloodOff from '../icons/FloodOff';
|
||||
import IconDoorOpened from '../icons/DoorOpened';
|
||||
import IconDoorClosed from '../icons/DoorClosed';
|
||||
import {MdBrightness1 as IconSun1} from 'react-icons/md';
|
||||
import {MdBrightness2 as IconSun2} from 'react-icons/md';
|
||||
import {MdBrightness3 as IconSun3} from 'react-icons/md';
|
||||
import {MdBrightness4 as IconSun4} from 'react-icons/md';
|
||||
import {MdBrightness5 as IconSun5} from 'react-icons/md';
|
||||
import {MdBrightness6 as IconSun6} from 'react-icons/md';
|
||||
import {MdBrightness7 as IconSun7} from 'react-icons/md';
|
||||
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
import Types from '../States/SmartTypes';
|
||||
// import IconLockOpened from "react-icons/lib/md/lock-open";
|
||||
// import IconLockClosed from "react-icons/lib/md/lock";
|
||||
|
||||
const IconSuns = [IconSun1, IconSun2, IconSun3, IconSun4, IconSun5, IconSun6, IconSun7];
|
||||
|
||||
class SmartState extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'SECOND');
|
||||
if (state) {
|
||||
this.secondary = {
|
||||
id: state.id
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (this.secondary && this.props.objects[this.secondary.id] && this.props.objects[this.secondary.id].common) {
|
||||
// detect type of secondary info
|
||||
const secondary = this.props.objects[this.secondary.id].common;
|
||||
if (secondary.role.match(/brightness/i)) {
|
||||
this.secondary.icon = val => {
|
||||
if (val > this.secondary.max) {
|
||||
return IconSuns[IconSuns.length - 1];
|
||||
} else
|
||||
if (val < this.secondary.min) {
|
||||
return IconSuns[0];
|
||||
} else {
|
||||
const num = (val - this.secondary.min) / (this.secondary.max - this.secondary.min);
|
||||
return IconSuns[Math.round((IconSuns.length - 1) * num)];
|
||||
}
|
||||
};
|
||||
this.secondary.iconStyle = {color: '#c3c300'};
|
||||
} else {
|
||||
this.secondary.iconStyle = {};
|
||||
}
|
||||
this.secondary.title = secondary.name || this.secondary.id.split('.').pop();
|
||||
if (typeof this.secondary.title === 'object') {
|
||||
this.secondary.title = this.secondary.title[I18n.getLanguage()] || this.secondary.title.en;
|
||||
}
|
||||
this.secondary.min = secondary.min === undefined ? 0 : secondary.min;
|
||||
this.secondary.max = secondary.max === undefined ? 100 : secondary.max;
|
||||
this.secondary.unit = secondary.unit || '';
|
||||
}
|
||||
|
||||
if (this.channelInfo.type === Types.window) {
|
||||
this.iconOn = IconWindowOpened;
|
||||
this.iconOff = IconWindowClosed;
|
||||
this.textOn = 'opened';
|
||||
this.textOff = 'closed';
|
||||
this.showTime = true;
|
||||
this.style = {
|
||||
width: 60,
|
||||
height: 60,
|
||||
top: '0.2rem',
|
||||
left: '0.2rem'
|
||||
};
|
||||
} if (this.channelInfo.type === Types.door) {
|
||||
this.iconOn = IconDoorOpened;
|
||||
this.iconOff = IconDoorClosed;
|
||||
this.textOn = 'opened';
|
||||
this.textOff = 'closed';
|
||||
this.showTime = true;
|
||||
this.style = {
|
||||
left: '1rem'
|
||||
};
|
||||
} else if (this.channelInfo.type === Types.motion) {
|
||||
this.iconOn = IconMotionOn;
|
||||
this.iconOff = IconMotionOff;
|
||||
this.iconColorOn = 'green';
|
||||
this.iconColorOff = 'grey';
|
||||
this.textOn = 'motion';
|
||||
this.showTime = true;
|
||||
this.textOff = '-';
|
||||
} else if (this.channelInfo.type === Types.fireAlarm) {
|
||||
this.iconOn = IconFireOn;
|
||||
this.iconOff = IconFireOff;
|
||||
this.iconColorOn = 'red';
|
||||
this.iconColorOff = 'grey';
|
||||
this.textOn = 'fire';
|
||||
this.showTime = true;
|
||||
this.textOff = '-';
|
||||
this.hideOnFalse = true;
|
||||
} else if (this.channelInfo.type === Types.floodAlarm) {
|
||||
this.iconOn = IconFloodOn;
|
||||
this.iconOff = IconFloodOff;
|
||||
this.iconColorOn = 'blue';
|
||||
this.iconColorOff = 'grey';
|
||||
this.textOn = 'flood';
|
||||
this.textOff = '-';
|
||||
this.showTime = true;
|
||||
this.hideOnFalse = true;
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: false
|
||||
});
|
||||
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.key = 'smart-state-' + this.id + '-';
|
||||
|
||||
//this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.id) {
|
||||
let val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON';
|
||||
const newState = {};
|
||||
if (this.state.settings.inverted) {
|
||||
val = !val;
|
||||
}
|
||||
newState[id] = val;
|
||||
|
||||
if (this.showTime && state.lc) {
|
||||
this.lastChange = state.lc;
|
||||
} else {
|
||||
this.lastChange = 0;
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
|
||||
if (this.hideOnFalse) {
|
||||
let someIndicator = false;
|
||||
if (this.indicators) {
|
||||
const ids = Object.keys(this.indicators).filter(_id => this.indicators[_id]);
|
||||
someIndicator = !!ids.find(_id => this.state[this.indicators[_id]]);
|
||||
}
|
||||
|
||||
this.props.tile.setVisibility(val || someIndicator);
|
||||
}
|
||||
} else if (this.secondary && this.secondary.id === id) {
|
||||
const newState = {};
|
||||
newState[id] = state.val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getDialogSettings () {
|
||||
const settings = super.getDialogSettings();
|
||||
|
||||
settings.unshift({
|
||||
name: 'inverted',
|
||||
value: this.state.settings.inverted || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
return settings;
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
const isOn = this.state[this.id] === '1' || this.state[this.id] === 1 || this.state[this.id] === true || this.state[this.id] === 'true' || this.state[this.id] === 'on' || this.state[this.id] === 'ON';
|
||||
const color = isOn ? this.iconColorOn : this.iconColorOff;
|
||||
let style = color ? {color} : {};
|
||||
if (this.style) {
|
||||
style = Object.assign(style, this.style);
|
||||
}
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img src={this.getDefaultIcon()} alt="icon" style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={isOn ? this.state.settings.icon : this.state.settings.iconOff || this.state.settings.icon} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
const Icon = isOn ? this.iconOn : this.iconOff;
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, style)} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
const state = this.state[this.id];
|
||||
if (state === undefined || state === null || !this.lastChange || !this.showTime) {
|
||||
const isOn = this.state[this.id] === '1' || this.state[this.id] === 1 || this.state[this.id] === true || this.state[this.id] === 'true' || this.state[this.id] === 'on' || this.state[this.id] === 'ON';
|
||||
return isOn ? I18n.t(this.textOn) : I18n.t(this.textOff);
|
||||
} else {
|
||||
return (<Moment style={{fontSize: 12}} date={this.lastChange} interval={15} fromNow locale={I18n.getLanguage()}/>);
|
||||
}
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
if (!this.secondary || !this.secondary.id || this.state[this.secondary.id] === undefined || this.state[this.secondary.id] === null) {
|
||||
return null;
|
||||
}
|
||||
let val = this.state[this.secondary.id];
|
||||
const Icon = (typeof this.secondary.icon === 'function') ? this.secondary.icon.call(this, val) : this.secondary.icon;
|
||||
if (typeof val === 'number') {
|
||||
val = Math.round(val * 100) / 100;
|
||||
}
|
||||
return (<div key={this.key + 'tile-secondary'} className="tile-text-second" style={Theme.tile.secondary.div} title={this.secondary.title}>
|
||||
{Icon ? (<Icon style={Object.assign({}, Theme.tile.secondary.icon, this.secondary.iconStyle)} />) : null}
|
||||
<span style={Theme.tile.secondary.text}>{val + (this.secondary.unit ? ' ' + this.secondary.unit : '')}</span>
|
||||
</div>);
|
||||
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.actualId),
|
||||
this.getSecondaryDiv()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartState;
|
||||
|
150
src/src/States/SmartSwitch.js
Normal file
@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
|
||||
import {TiLightbulb as IconLight} from 'react-icons/ti';
|
||||
import {MdCheck as IconCheck} from 'react-icons/md';
|
||||
import {MdCancel as IconCancel} from 'react-icons/md';
|
||||
import IconSwitch from '../icons/Socket';
|
||||
|
||||
import Types from './SmartTypes';
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
import CircularProgress from '@material-ui/core/CircularProgress';
|
||||
|
||||
class SmartSwitch extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
}
|
||||
if (this.channelInfo) {
|
||||
switch (this.channelInfo.type) {
|
||||
case Types.light:
|
||||
this.iconOn = IconLight;
|
||||
this.iconOff = IconLight;
|
||||
this.colorOn = Theme.palette.lampOn;
|
||||
this.colorOff = 'inherit';
|
||||
this.style = {};
|
||||
break;
|
||||
|
||||
case Types.socket:
|
||||
default:
|
||||
if (this.props.objects[this.id] && this.props.objects[this.id].common && this.props.objects[this.id].common.role ==='switch.active') {
|
||||
this.iconOn = IconCheck;
|
||||
this.iconOff = IconCancel;
|
||||
} else {
|
||||
this.iconOn = IconSwitch;
|
||||
this.iconOff = IconSwitch;
|
||||
}
|
||||
this.colorOn = Theme.palette.lampOn;
|
||||
this.colorOff = 'inherit';
|
||||
this.backOn = Theme.palette.lampOn;
|
||||
this.backOff = 'gray';
|
||||
this.style = {left: '1rem'};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
this.key = 'smart-switch-' + this.id + '-';
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
const newState = {};
|
||||
const val = typeof state.val === 'number' ? !!state.val : state.val === true || state.val === 'true' || state.val === '1' || state.val === 'on' || state.val === 'ON';
|
||||
if (id === this.actualId || (this.id === id && this.id === this.actualId && state.ack)) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
state: val
|
||||
});
|
||||
} else if (id === this.id) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
toggle() {
|
||||
if (this.actualId !== this.id) {
|
||||
this.setState({executing: true});
|
||||
}
|
||||
this.props.onControl(this.id, !this.state[this.actualId]);
|
||||
}
|
||||
|
||||
onTileClick() {
|
||||
this.toggle();
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
const state = !!this.state[this.actualId];
|
||||
let style = state ? {color: this.colorOn} : {color: this.colorOff};
|
||||
if (this.style) {
|
||||
style = Object.assign(style, this.style);
|
||||
}
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={state ? this.state.settings.icon : this.state.settings.iconOff || this.state.settings.icon} style={{height: '100%'}}/>);
|
||||
} else {
|
||||
const Icon = this.state[this.actualId] ? this.iconOn : this.iconOff;
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, style)} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{zIndex: 3, position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
return this.state[this.id] ? I18n.t('On') : I18n.t('Off')
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent(this.getStandardContent(this.actualId));
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartSwitch;
|
||||
|
141
src/src/States/SmartThermometer.js
Normal file
@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import IconThermometer from '../icons/Thermometer';
|
||||
import IconHydro from '../icons/Humidity';
|
||||
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
|
||||
class SmartThermometer extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'SECOND');
|
||||
if (state) {
|
||||
this.secondary = {
|
||||
id: state.id
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
this.props.tile.state.state = true;
|
||||
|
||||
if (this.secondary && this.props.objects[this.secondary.id] && this.props.objects[this.secondary.id].common) {
|
||||
// detect type of secondary info
|
||||
const secondary = this.props.objects[this.secondary.id].common;
|
||||
if (secondary.role.match(/humidity/i)) {
|
||||
this.secondary.icon = IconHydro;
|
||||
this.secondary.iconStyle = {color: '#0056c3'};
|
||||
} else {
|
||||
this.secondary.iconStyle = {};
|
||||
}
|
||||
this.secondary.title = secondary.name || this.secondary.id.split('.').pop();
|
||||
if (typeof this.secondary.title === 'object') {
|
||||
this.secondary.title = this.secondary.title[I18n.getLanguage()] || this.secondary.title.en;
|
||||
}
|
||||
this.secondary.unit = secondary.unit ? ' ' + secondary.unit : '';
|
||||
}
|
||||
|
||||
if (this.id && this.props.objects[this.id] && this.props.objects[this.id] && this.props.objects[this.id].common.unit) {
|
||||
this.unit = ' ' + this.props.objects[this.id].common.unit;
|
||||
} else {
|
||||
this.unit = '';
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: false
|
||||
});
|
||||
|
||||
this.key = 'smart-thermometer-' + this.id + '-';
|
||||
|
||||
//this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.id) {
|
||||
const newState = {};
|
||||
newState[id] = state.val;
|
||||
|
||||
this.setState(newState);
|
||||
} else if (this.secondary && this.secondary.id === id) {
|
||||
const newState = {};
|
||||
newState[id] = state.val;
|
||||
this.setState(newState);
|
||||
} else{
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={this.state.settings.icon} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
customIcon = (<IconThermometer width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, {})} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
const state = this.state[this.id];
|
||||
return state === undefined || state === null ? '?' : state + this.unit;
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
if (!this.secondary || !this.secondary.id || this.state[this.secondary.id] === undefined || this.state[this.secondary.id] === null) {
|
||||
return null;
|
||||
}
|
||||
let val = this.state[this.secondary.id];
|
||||
const Icon = this.secondary.icon;
|
||||
if (typeof val === 'number') {
|
||||
val = Math.round(val * 100) / 100;
|
||||
}
|
||||
return (<div key={this.key + 'tile-secondary'} className="tile-text-second" style={Theme.tile.secondary.div} title={this.secondary.title}>
|
||||
{Icon ? (<Icon style={Object.assign({}, Theme.tile.secondary.icon, this.secondary.iconStyle)} />) : null}
|
||||
<span style={Theme.tile.secondary.text}>{val + this.secondary.unit}</span>
|
||||
</div>);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.actualId),
|
||||
this.getSecondaryDiv()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartThermometer;
|
||||
|
201
src/src/States/SmartThermostat.js
Normal file
@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import Icon from '../icons/Thermometer'
|
||||
import IconThermometer from '../icons/ThermometerSimple';
|
||||
import IconHydro from '../icons/Humidity';
|
||||
import Theme from '../theme';
|
||||
import Dialog from '../Dialogs/SmartDialogThermostat';
|
||||
import I18n from '../i18n';
|
||||
|
||||
class SmartThermostat extends SmartGeneric {
|
||||
// props = {
|
||||
// objects: OBJECT
|
||||
// tile: parentDiv
|
||||
// states: STATES
|
||||
// onControl: function
|
||||
// };
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state && this.props.objects[state.id]&& this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'BOOST');
|
||||
this.boostId = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUMIDITY');
|
||||
this.humidityId = state && state.id;
|
||||
}
|
||||
|
||||
if (this.humidityId) {
|
||||
const common = this.props.objects[this.humidityId] && this.props.objects[this.humidityId].common;
|
||||
this.humUnit = common.unit || '%';
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
const common = this.props.objects[this.id] && this.props.objects[this.id].common;
|
||||
this.max = common.max;
|
||||
if (this.max === undefined) {
|
||||
this.max = 30;
|
||||
}
|
||||
this.max = parseFloat(this.max);
|
||||
|
||||
this.min = common.min;
|
||||
if (this.min === undefined) {
|
||||
this.min = 12;
|
||||
}
|
||||
this.min = parseFloat(this.min);
|
||||
|
||||
this.unit = common.unit || '°C';
|
||||
|
||||
if (this.unit === 'C') {
|
||||
this.unit = '°C';
|
||||
} else
|
||||
if (this.unit === 'C°') {
|
||||
this.unit = '°C';
|
||||
}
|
||||
if (this.unit === 'F') {
|
||||
this.unit = '°F';
|
||||
} else
|
||||
if (this.unit === 'F°') {
|
||||
this.unit = '°F';
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
}
|
||||
|
||||
this.unit = this.unit || '°C';
|
||||
|
||||
this.stateRx.showDialog = false;
|
||||
this.props.tile.setState({state: true});
|
||||
this.key = 'smart-thermostat-' + this.id + '-';
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
if (this.actualId === id || id === this.id || id === this.humidityId) {
|
||||
newState[id] = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
if (isNaN(newState[id])) {
|
||||
newState[id] = null;
|
||||
}
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
setValue(degrees) {
|
||||
console.log('Control ' + this.id + ' = ' + degrees);
|
||||
const newValue = {};
|
||||
newValue[this.id] = degrees;
|
||||
this.setState(newValue);
|
||||
this.props.onControl(this.id, degrees);
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={this.state.settings.icon} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, {}, {left: '0.5rem'})} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.state[this.id] === null) {
|
||||
return '?';
|
||||
} else {
|
||||
return this.state[this.id] + this.unit;
|
||||
}
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
if (this.actualId === this.id && !this.humidityId) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'tile-secondary'} className="tile-text-second"
|
||||
style={Object.assign({}, Theme.tile.secondary.div, {top: '1rem'})} title={I18n.t('Environment values')}>
|
||||
{this.actualId !== this.id ?
|
||||
[
|
||||
(<IconThermometer key={this.key + 'tile-secondary-icon-0'} style={Object.assign({}, Theme.tile.secondary.icon)} />),
|
||||
(<span key={this.key + 'tile-secondary-text-0'} style={Theme.tile.secondary.text}>{this.state[this.actualId] === null ? '?' : this.state[this.actualId] + this.unit}</span>),
|
||||
(<br key={this.key + 'tile-secondary-br-0'} />)
|
||||
] : null}
|
||||
{this.humidityId ?
|
||||
[
|
||||
(<IconHydro key={this.key + 'tile-secondary-icon-1'} style={Object.assign({}, Theme.tile.secondary.icon)} />),
|
||||
(<span key={this.key + 'tile-secondary-text-1'} style={Theme.tile.secondary.text}>{this.state[this.humidityId] === null ? '?' : this.state[this.humidityId] + this.humUnit}</span>)
|
||||
] : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
onBoostToggle(boostOn) {
|
||||
if (boostOn === undefined) {
|
||||
boostOn = !this.state[this.boostId];
|
||||
}
|
||||
const newValue = {};
|
||||
newValue[this.boostId] = boostOn;
|
||||
this.setState(newValue);
|
||||
this.props.onControl(this.boostId, boostOn);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(this.id, true),
|
||||
this.getSecondaryDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
dialogKey={this.key + 'dialog'}
|
||||
startValue={this.state[this.id]}
|
||||
windowWidth={this.props.windowWidth}
|
||||
actualValue={this.state[this.actualId]}
|
||||
boostValue={this.boostId ? this.state[this.boostId] : null}
|
||||
onBoostToggle={this.onBoostToggle.bind(this)}
|
||||
min={this.min}
|
||||
max={this.max}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartThermostat;
|
||||
|
16
src/src/States/SmartTypes.js
Normal file
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
export default window.Types;
|
333
src/src/States/SmartURL.js
Normal file
@ -0,0 +1,333 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 {FaVideo as IconCam} from 'react-icons/fa';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Dialog from '../Dialogs/SmartDialogURL';
|
||||
import Theme from '../theme';
|
||||
import Utils from '../Utils';
|
||||
import Icon from "../icons/Thermometer";
|
||||
|
||||
const styles = {
|
||||
'title-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
fontWeight: 'bold',
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
height: 48,
|
||||
background: 'rgba(255,255,255,0.45)',
|
||||
color: 'rgba(0, 0, 0, 0.6)',
|
||||
width: '100%',
|
||||
textAlign: 'left'
|
||||
},
|
||||
'title-text': {
|
||||
paddingLeft: 16,
|
||||
paddingTop: 16,
|
||||
},
|
||||
iframe: {
|
||||
position: 'absolute',
|
||||
zIndex: 0,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
border: 0
|
||||
}
|
||||
};
|
||||
|
||||
class SmartURL extends SmartGeneric {
|
||||
static propTypes = {
|
||||
classes: PropTypes.object.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.ids = {
|
||||
url: null,
|
||||
};
|
||||
|
||||
this.collectState = null;
|
||||
this.collectTimer = null;
|
||||
|
||||
if (this.channelInfo.states) {
|
||||
// Actual
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'URL');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
this.ids.url = state.id;
|
||||
const settingsId = state.settingsId;
|
||||
if (settingsId) {
|
||||
const settings = Utils.getSettingsCustomURLs(this.props.objects[settingsId], null, {user: this.props.user});
|
||||
if (settings) {
|
||||
const tile = settings.find(e => e.id === state.id);
|
||||
if (tile) {
|
||||
this.stateRx.settings = JSON.parse(JSON.stringify(tile));
|
||||
this.customSettings = this.stateRx.settings;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
const m = this.id.match(/^_custom_(\d+)$/);
|
||||
if (m && Date.now() - m[1] < 500) {
|
||||
this.stateRx.showSettings = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.image = this.isImage();
|
||||
if (this.image) {
|
||||
this.props.tile.setBackgroundImage(this.customSettings.background || '', true);
|
||||
}
|
||||
|
||||
this.width = 2;
|
||||
this.props.tile.setState({isPointer: false});
|
||||
this.props.tile.setState({state: true});
|
||||
this.key = 'smart-warning-' + this.id + '-';
|
||||
this.props.tile.setVisibility(this.id && !!this.stateRx.settings);
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
|
||||
this.interval = null;
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
isImage() {
|
||||
return this.customSettings.isImage || (this.customSettings.background && this.customSettings.background.toLowerCase().match(/\.png|\.jpg|\.gif|\.jpeg/));
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateUrl() {
|
||||
if (!this.customSettings.background) return;
|
||||
|
||||
if (this.image) {
|
||||
if (this.customSettings.background.indexOf('?') !== -1) {
|
||||
this.props.tile.setBackgroundImage(this.customSettings.background + '&ts=' + Date.now(), true, true);
|
||||
} else {
|
||||
this.props.tile.setBackgroundImage(this.customSettings.background + '?ts=' + Date.now(), true, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
if (this.customSettings && this.customSettings.update) {
|
||||
this.interval = setInterval(() => this.updateUrl(), this.customSettings.update);
|
||||
}
|
||||
}
|
||||
|
||||
onUpdateTimer() {
|
||||
this.collectTimer = null;
|
||||
if (this.collectState) {
|
||||
if (this.collectState[this.id] !== undefined) {
|
||||
this.props.tile.setVisibility(!!this.collectState[this.id]);
|
||||
}
|
||||
this.setState(this.collectState);
|
||||
this.collectState = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.ids.url) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else {
|
||||
console.log(id + ' => ' + state.val);
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getDialogSettings() {
|
||||
const settings = super.getDialogSettings();
|
||||
|
||||
settings.unshift({
|
||||
name: 'hideIcon',
|
||||
value: this.state.settings.hideIcon || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'fullWidth',
|
||||
value: this.state.settings.fullWidth || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'updateInDialog',
|
||||
value: this.state.settings.updateInDialog || 0,
|
||||
type: 'number'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'update',
|
||||
value: this.state.settings.update || 0,
|
||||
type: 'number'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'title',
|
||||
value: (this.state.settings.title === undefined) ? '' : this.state.settings.title,
|
||||
type: 'text'
|
||||
});
|
||||
|
||||
settings.unshift({
|
||||
name: 'isImage',
|
||||
value: this.state.settings.isImage || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
|
||||
settings.forEach((e, i) => {
|
||||
if (e.name === 'background') {
|
||||
e.type = 'text';
|
||||
settings.splice(i, 1);
|
||||
settings.unshift(e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
// remove name from list
|
||||
settings.forEach((e, i) => {
|
||||
if (e.name === 'name') {
|
||||
settings.splice(i, 1);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
settings.unshift({
|
||||
type: 'delete'
|
||||
});
|
||||
return settings;
|
||||
}
|
||||
|
||||
saveDialogSettings(settings) {
|
||||
if (settings) {
|
||||
settings.update = parseInt(settings.update, 10) || 0;
|
||||
if (settings.update && settings.update < 500) {
|
||||
settings.update = 500;
|
||||
}
|
||||
settings.updateInDialog = parseInt(settings.updateInDialog, 10) || 0;
|
||||
if (settings.updateInDialog && settings.updateInDialog < 500) {
|
||||
settings.updateInDialog = 500;
|
||||
}
|
||||
}
|
||||
|
||||
super.saveDialogSettings(settings, function (newSettings) {
|
||||
this.customSettings = newSettings;
|
||||
|
||||
this.componentDidMount();
|
||||
this.image = this.isImage();
|
||||
if (this.image && newSettings) {
|
||||
this.props.tile.setBackgroundImage((this.state.settings && this.state.settings.background) || '', true);
|
||||
}
|
||||
this.setState({settings: newSettings});
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
getIconDiv() {
|
||||
let customIcon;
|
||||
if (this.state.settings.hideIcon) return null;
|
||||
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img src={this.state.settings.icon} alt="icon" style={{height: '100%', zIndex: 1, color: 'white'}}/>);
|
||||
} else {
|
||||
customIcon = (<IconCam width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size, color: 'white'}}/>);
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, {opacity: 0.7})} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getIFrameDiv() {
|
||||
if (!this.image && this.state.settings.background) {
|
||||
return (<iframe key="iframe" title={this.state.settings.name} className={this.props.classes['iframe']} src={this.state.settings.background}/>)
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
getTitleDiv() {
|
||||
const classes = this.props.classes;
|
||||
let title = this.state.settings.title;
|
||||
|
||||
if (title) {
|
||||
return (<div key="title" className={classes['title-div']}>
|
||||
<div className={classes['title-text']}>{title}</div>
|
||||
</div>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
onDialogClose() {
|
||||
super.onDialogClose();
|
||||
// start timer again
|
||||
this.componentDidMount();
|
||||
}
|
||||
|
||||
onLongClick(e) {
|
||||
super.onLongClick(e);
|
||||
// Stop update timer
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getIFrameDiv(),
|
||||
this.getIconDiv(),
|
||||
this.getTitleDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog dialogKey={this.key + 'dialog'}
|
||||
key={this.key + 'dialog'}
|
||||
name={this.state.settings.name}
|
||||
enumNames={this.props.enumNames}
|
||||
settings={this.state.settings}
|
||||
objects={this.props.objects}
|
||||
image={this.image}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
ids={this.ids}
|
||||
windowWidth={this.props.windowWidth}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartURL);
|
248
src/src/States/SmartVolume.js
Normal file
@ -0,0 +1,248 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 CircularProgress from '@material-ui/core/CircularProgress';
|
||||
import Button from '@material-ui/core/Button';
|
||||
|
||||
import {MdVolumeMute as IconVolume0} from 'react-icons/md';
|
||||
import {MdVolumeDown as IconVolume50} from 'react-icons/md';
|
||||
import {MdVolumeUp as IconVolume100} from 'react-icons/md';
|
||||
|
||||
import Theme from '../theme';
|
||||
import SmartGeneric from './SmartGeneric';
|
||||
import Types from './SmartTypes';
|
||||
//import Dialog from './SmartDialogSlider';
|
||||
import Dialog from '../Dialogs/SmartDialogKnob';
|
||||
|
||||
import I18n from '../i18n';
|
||||
import Icon from "../icons/Thermometer";
|
||||
|
||||
const style = {
|
||||
mute: {
|
||||
fontSize: 'smaller',
|
||||
fontWeight: 'normal',
|
||||
paddingLeft: 10
|
||||
},
|
||||
groupText: {
|
||||
fontSize: 10,
|
||||
paddingLeft: 5
|
||||
}
|
||||
};
|
||||
|
||||
class SmartVolume extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'SET');
|
||||
if (state && this.props.objects[state.id] && this.props.objects[state.id].common) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
this.actualId = state ? state.id : this.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'MUTE');
|
||||
this.muteId = state && state.id;
|
||||
|
||||
if (this.channelInfo.type === Types.volumeGroup) {
|
||||
this.group = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (this.id) {
|
||||
this.max = this.props.objects[this.actualId].common.max;
|
||||
this.min = this.props.objects[this.actualId].common.min;
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: true
|
||||
});
|
||||
|
||||
this.unit = this.props.objects[this.actualId].common.unit;
|
||||
this.unit = this.unit ? ' ' + this.unit : '';
|
||||
}
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
this.stateRx.setValue = null;
|
||||
this.key = 'smart-slider-' + this.id + '-';
|
||||
this.doubleState = true; // used in generic
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let newState = {};
|
||||
|
||||
if (this.actualId === id || (this.id === id && this.id === this.actualId && state.ack)) {
|
||||
const val = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
if (!isNaN(val)) {
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
|
||||
const tileState = val !== this.min;
|
||||
this.props.tile.setState({
|
||||
state: tileState
|
||||
});
|
||||
} else {
|
||||
newState[id] = null;
|
||||
this.setState(newState);
|
||||
this.props.tile.setState({
|
||||
state: false
|
||||
});
|
||||
}
|
||||
|
||||
// hide desired value
|
||||
if (this.state.setValue === newState[id] && state.ack) {
|
||||
this.setState({setValue: null});
|
||||
}
|
||||
|
||||
if (state.ack && this.state.executing) {
|
||||
this.setState({executing: false});
|
||||
}
|
||||
} else if (id === this.id) {
|
||||
newState[id] = typeof state.val === 'number' ? state.val : parseFloat(state.val);
|
||||
this.setState(newState);
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
setValue(value) {
|
||||
console.log('Control ' + this.id + ' = ' + value);
|
||||
if (this.actualId !== this.id) {
|
||||
this.setState({executing: true, setValue: value});
|
||||
}
|
||||
if (this.max - this.min > 9) {
|
||||
value = Math.round(value);
|
||||
}
|
||||
this.props.onControl(this.id, value);
|
||||
}
|
||||
|
||||
toggle() {
|
||||
this.props.onControl(this.muteId, !this.state[this.muteId]);
|
||||
}
|
||||
|
||||
getSecondaryDiv() {
|
||||
let Icon;
|
||||
let text;
|
||||
let color;
|
||||
|
||||
if (this.state[this.muteId]) {
|
||||
Icon = IconVolume0;
|
||||
text = I18n.t('mute');
|
||||
color = '#f99';
|
||||
} else {
|
||||
Icon = IconVolume100;
|
||||
text = I18n.t('unmute');
|
||||
color = 'inherit'
|
||||
}
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
|
||||
return (<div key={this.key + 'tile-secondary'} className="tile-text-second"
|
||||
style={Theme.tile.secondary.button} title={text}>
|
||||
<Button variant="fab" mini onClick={this.toggle.bind(this)} style={{background: color, boxShadow: 'none'}} aria-label={text}>
|
||||
{customIcon}
|
||||
</Button>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{height: '100%'}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={this.state.settings.icon} style={{height: '100%'}}/>);
|
||||
} else {
|
||||
let IconCustom;
|
||||
const val = Math.round((this.state[this.actualId] - this.min) / (this.max - this.min) * 100);
|
||||
if (val < 25) {
|
||||
IconCustom = IconVolume0;
|
||||
} else if (val < 75) {
|
||||
IconCustom = IconVolume50;
|
||||
} else {
|
||||
IconCustom = IconVolume100;
|
||||
}
|
||||
customIcon = (<IconCustom width={Theme.tile.tileIconSvg.size} height={Theme.tile.tileIconSvg.size} style={{zIndex: 1, height: Theme.tile.tileIconSvg.size, width: Theme.tile.tileIconSvg.size}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, this.state[this.actualId] !== this.min ? {color: Theme.palette.lampOn} : {})} className="tile-icon">
|
||||
{customIcon}
|
||||
{this.state.executing ? <CircularProgress style={{position: 'absolute', top: 0, left: 0}} size={Theme.tile.tileIcon.width}/> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
let result = '';
|
||||
if (this.state[this.actualId] === null || this.state[this.actualId] === undefined) {
|
||||
result = '---';
|
||||
} else {
|
||||
if (this.workingId && this.state[this.workingId] && this.state.setValue !== null && this.state.setValue !== undefined) {
|
||||
if (this.max - this.min > 9) {
|
||||
result = Math.round(this.state[this.id]) + this.unit + ' → ' + Math.round(this.state.setValue) + this.unit;
|
||||
} else {
|
||||
result = this.roundValue(this.state[this.id], 1) + this.unit + ' → ' + this.roundValue(this.state.setValue, 1) + this.unit;
|
||||
}
|
||||
} else if (this.max - this.min > 9) {
|
||||
result = Math.round(this.state[this.id]) + this.unit;
|
||||
} else {
|
||||
result = this.roundValue(this.state[this.id], 1) + this.unit;
|
||||
}
|
||||
}
|
||||
if (this.muteId && this.state[this.muteId]) {
|
||||
result = [(<span key="value">{result}</span>), (<span key="muted" style={style.mute}>({I18n.t('muted')})</span>)];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
getAdditionalName() {
|
||||
return this.group ? (<span style={style.groupText}>{I18n.t('group')}</span>) : null;
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getStandardContent(null, true),
|
||||
this.muteId && this.getSecondaryDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog key={this.key + 'dialog'}
|
||||
startValue={this.state[this.id]}
|
||||
startMuteValue={this.muteId ? this.state[this.muteId] : false}
|
||||
onMute={this.muteId ? this.toggle.bind(this) : null}
|
||||
windowWidth={this.props.windowWidth}
|
||||
min={this.min}
|
||||
max={this.max}
|
||||
unit={this.unit}
|
||||
onValueChange={this.setValue.bind(this)}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
// type={Dialog.types.value}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartVolume;
|
||||
|
252
src/src/States/SmartWarning.js
Normal file
@ -0,0 +1,252 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import Dialog from '../Dialogs/SmartDialogWarning';
|
||||
|
||||
const styles = {
|
||||
'icon-div': {
|
||||
position: 'absolute',
|
||||
width: 90,
|
||||
height: 90,
|
||||
zIndex: 0,
|
||||
left: 10,
|
||||
top: 24,
|
||||
backgroundSize: 'contain',
|
||||
backgroundRepeat: 'no-repeat',
|
||||
backgroundPosition: 'center center'
|
||||
},
|
||||
'date-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 2rem - 90px)',
|
||||
top: 16,
|
||||
right: 16
|
||||
},
|
||||
'date-start': {
|
||||
fontWeight: 'normal',
|
||||
textAlign: 'left',
|
||||
width: '100%'
|
||||
},
|
||||
'date-end': {
|
||||
textAlign: 'right',
|
||||
fontWeight: 'normal',
|
||||
width: '100%'
|
||||
},
|
||||
'title-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
fontWeight: 'bold',
|
||||
top: 55,
|
||||
width: 'calc(100% - 2rem - 90px)',
|
||||
right: 16,
|
||||
textAlign: 'left'
|
||||
},
|
||||
'title-text': {
|
||||
},
|
||||
'info-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
maxWidth: 'calc(100% - 2rem - 90px)',
|
||||
fontWeight: 'normal',
|
||||
top: 75,
|
||||
right: 16,
|
||||
textAlign: 'left'
|
||||
},
|
||||
'info-text': {
|
||||
overflow: 'hidden',
|
||||
fontSize: 14
|
||||
}
|
||||
};
|
||||
|
||||
class SmartWeatherForecast extends SmartGeneric {
|
||||
static propTypes = {
|
||||
classes: PropTypes.object.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.ids = {
|
||||
warning: null,
|
||||
title: null,
|
||||
info: null,
|
||||
start: null,
|
||||
end: null,
|
||||
icon: null,
|
||||
description: null
|
||||
};
|
||||
|
||||
this.collectState = null;
|
||||
this.collectTimer = null;
|
||||
|
||||
if (this.channelInfo.states) {
|
||||
// Actual
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'LEVEL');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
this.ids.warning = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TITLE');
|
||||
this.ids.title = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'INFO');
|
||||
this.ids.info = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'START');
|
||||
this.ids.start = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'END');
|
||||
this.ids.end = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ICON');
|
||||
this.ids.icon = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DESC');
|
||||
this.ids.description = state && state.id;
|
||||
}
|
||||
|
||||
this.width = 2;
|
||||
this.props.tile.setState({isPointer: false});
|
||||
this.props.tile.setState({state: true});
|
||||
this.key = 'smart-warning-' + this.id + '-';
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
onUpdateTimer() {
|
||||
this.collectTimer = null;
|
||||
if (this.collectState) {
|
||||
if (this.collectState[this.id] !== undefined) {
|
||||
this.props.tile.setVisibility(!!this.collectState[this.id]);
|
||||
}
|
||||
this.setState(this.collectState);
|
||||
this.collectState = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.ids.title ||
|
||||
id === this.ids.info ||
|
||||
id === this.ids.icon) {
|
||||
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.start ||
|
||||
id === this.ids.end) {
|
||||
this.collectState = this.collectState || {};
|
||||
if (typeof state.val === 'string') {
|
||||
const year = new Date().getFullYear();
|
||||
state.val = state.val.replace(year.toString(), '').replace((year + 1).toString(), '')
|
||||
}
|
||||
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else
|
||||
if (id === this.ids.warning) {
|
||||
const val = parseInt(state.val, 10) || 0;
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else {
|
||||
console.log(id + ' => ' + state.val);
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getDialogSettings() {
|
||||
const settings = super.getDialogSettings();
|
||||
// remove doubleSize from list
|
||||
settings.forEach((item, i) => {
|
||||
if (item.name === 'doubleSize') {
|
||||
settings.splice(i, 1);
|
||||
return false
|
||||
}
|
||||
});
|
||||
return settings;
|
||||
}
|
||||
|
||||
getIconDiv() {
|
||||
const classes = this.props.classes;
|
||||
if (!this.ids.icon || !this.state[this.ids.icon]) return null;
|
||||
|
||||
return (<div key="icon" className={classes['icon-div']} style={{
|
||||
backgroundImage: 'url(' + this.state[this.ids.icon] + ')'
|
||||
}} />);
|
||||
}
|
||||
|
||||
getDateDiv() {
|
||||
const classes = this.props.classes;
|
||||
let start = this.ids.start && this.state[this.ids.start];
|
||||
let end = this.ids.end && this.state[this.ids.end];
|
||||
|
||||
return (<div key="date" className={classes['date-div']}>
|
||||
<div className={classes['date-start']}>{start}</div>
|
||||
{end ? (<div className={classes['date-end']}>-{end}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTitleDiv() {
|
||||
const classes = this.props.classes;
|
||||
let title = this.ids.title && this.state[this.ids.title];
|
||||
|
||||
return (<div key="title" className={classes['title-div']}>
|
||||
<div className={classes['title-text']}>{title}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getInfoDiv() {
|
||||
const classes = this.props.classes;
|
||||
let info = this.ids.info && this.state[this.ids.info];
|
||||
|
||||
return (<div key="info" className={classes['info-div']}>
|
||||
<div className={classes['info-text']}>{info}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getIconDiv(),
|
||||
this.getDateDiv(),
|
||||
this.getTitleDiv(),
|
||||
this.getInfoDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog dialogKey={this.key + 'dialog'}
|
||||
key={this.key + 'dialog'}
|
||||
name={this.state.settings.name}
|
||||
enumNames={this.props.enumNames}
|
||||
settings={this.state.settings}
|
||||
objects={this.props.objects}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
ids={this.ids}
|
||||
windowWidth={this.props.windowWidth}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartWeatherForecast);
|
606
src/src/States/SmartWeatherForecast.js
Normal file
@ -0,0 +1,606 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import Utils from '../Utils';
|
||||
import Dialog from '../Dialogs/SmartDialogWeatherForecast';
|
||||
import I18n from '../i18n';
|
||||
|
||||
const styles = {
|
||||
'currentIcon-div': {
|
||||
position: 'absolute',
|
||||
width: 90,
|
||||
height: 90,
|
||||
zIndex: 0,
|
||||
left: 3,
|
||||
top: 24
|
||||
},
|
||||
'currentIcon-icon': {
|
||||
width: '100%',
|
||||
zIndex: 0
|
||||
},
|
||||
'currentIcon-temperature': {
|
||||
position: 'absolute',
|
||||
width: '100%',
|
||||
fontSize: 40,
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
textAlign: 'right',
|
||||
color: '#9c9c9c',
|
||||
top: 8,
|
||||
right: -50
|
||||
},
|
||||
'currentDate-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 2rem)',
|
||||
top: 16,
|
||||
left: 16
|
||||
},
|
||||
'currentDate-date': {
|
||||
fontWeight: 'normal',
|
||||
display: 'inline-block',
|
||||
},
|
||||
'currentDate-location': {
|
||||
display: 'inline-block',
|
||||
position: 'absolute',
|
||||
textOverflow: 'ellipsis',
|
||||
width: 'calc(100% - 78px)',
|
||||
whiteSpace: 'nowrap',
|
||||
right: 0,
|
||||
textAlign: 'right'
|
||||
},
|
||||
'todayTemp-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
fontWeight: 'normal',
|
||||
top: 35,
|
||||
maxWidth: 'calc(100% - 2rem - 90px)',
|
||||
right: 16,
|
||||
textAlign: 'right'
|
||||
},
|
||||
'todayTemp-temperature': {
|
||||
},
|
||||
'todayTemp-temperatureMin': {
|
||||
},
|
||||
'todayTemp-temperatureMax': {
|
||||
fontWeight: 'bold'
|
||||
},
|
||||
'todayTemp-temperatureTitle': {
|
||||
},
|
||||
'todayTemp-temperatureValue': {
|
||||
},
|
||||
'todayTemp-precipitation': {
|
||||
},
|
||||
'todayTemp-precipitationTitle': {
|
||||
},
|
||||
'todayTemp-precipitationValue': {
|
||||
paddingLeft: 2
|
||||
},
|
||||
'todayState-div': {
|
||||
position: 'absolute',
|
||||
zIndex: 1,
|
||||
width: 'calc(100% - 90px)',
|
||||
fontWeight: 'normal',
|
||||
bottom: 16,
|
||||
left: 80,
|
||||
textAlign: 'left'
|
||||
},
|
||||
'todayState-wind': {
|
||||
whiteSpace: 'nowrap',
|
||||
overflow: 'hidden',
|
||||
fontSize: 14
|
||||
},
|
||||
'todayState-windTitle': {
|
||||
},
|
||||
'todayState-windDir': {
|
||||
marginLeft: 2,
|
||||
},
|
||||
'todayState-windSpeed': {
|
||||
marginLeft: 2
|
||||
},
|
||||
'todayState-windIcon': {
|
||||
display: 'inline-block',
|
||||
marginLeft: 5,
|
||||
width: 16,
|
||||
maxHeight: 16
|
||||
},
|
||||
'todayState-windChill': {
|
||||
},
|
||||
'todayState-windChillTitle': {
|
||||
paddingRight: 5
|
||||
},
|
||||
'todayState-windChillValue': {
|
||||
},
|
||||
'todayState-state': {
|
||||
fontSize: 14
|
||||
}
|
||||
};
|
||||
|
||||
class SmartWeatherForecast extends SmartGeneric {
|
||||
static propTypes = {
|
||||
classes: PropTypes.object.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.ids = {
|
||||
current: {
|
||||
date: null,
|
||||
location: null,
|
||||
icon: null,
|
||||
state: null,
|
||||
temperature: null,
|
||||
humidity: null,
|
||||
windChill: null,
|
||||
windSpeed: null,
|
||||
windIcon: null,
|
||||
windDirection: null,
|
||||
pressure: null,
|
||||
precipitation: null
|
||||
},
|
||||
days: [
|
||||
{
|
||||
date: null,
|
||||
icon: null,
|
||||
state: null,
|
||||
temperature: null,
|
||||
temperatureMin: null,
|
||||
temperatureMax: null,
|
||||
humidity: null,
|
||||
humidityMin: null,
|
||||
humidityMax: null,
|
||||
windSpeed: null,
|
||||
windIcon: null,
|
||||
windDirection: null,
|
||||
precipitation: null,
|
||||
pressure: null
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
this.collectState = null;
|
||||
this.collectTimer = null;
|
||||
|
||||
if (this.channelInfo.states) {
|
||||
//console.log(JSON.stringify(this.channelInfo.states, null, 2));
|
||||
|
||||
// Actual
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'ICON');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
this.ids.current.icon = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP');
|
||||
this.ids.current.temperature = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'STATE');
|
||||
this.ids.current.state = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DATE');
|
||||
this.ids.current.date = state && state.id;
|
||||
|
||||
if (!this.ids.current.date) {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DOW');
|
||||
this.ids.current.date = state && state.id;
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.filter(state => state.id && state.name === 'LOCATION').map(state => state.id);
|
||||
this.ids.current.location = state && state.length && state;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUMIDITY');
|
||||
this.ids.current.humidity = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PRESSURE');
|
||||
this.ids.current.pressure = state && state.id;
|
||||
this.pressureUnit = '';
|
||||
if (this.ids.current.pressure) {
|
||||
const obj = this.props.objects[this.ids.current.pressure];
|
||||
if (obj && obj.common && obj.common.unit) {
|
||||
this.pressureUnit = ' ' + I18n.t(obj.common.unit);
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_SPEED');
|
||||
this.ids.current.windSpeed = state && state.id;
|
||||
this.windUnit = '';
|
||||
if (this.ids.current.windSpeed) {
|
||||
const obj = this.props.objects[this.ids.current.windSpeed];
|
||||
if (obj && obj.common && obj.common.unit) {
|
||||
this.windUnit = ' ' + I18n.t(obj.common.unit);
|
||||
}
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_CHILL');
|
||||
this.ids.current.windChill = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'FEELS_LIKE');
|
||||
if (!this.ids.current.windChill) {
|
||||
this.ids.current.windChill = state && state.id;
|
||||
} else if (state) {
|
||||
const pos = this.subscribes.indexOf(state.id);
|
||||
this.subscribes.splice(pos, 1);
|
||||
state.id = null;
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_ICON');
|
||||
this.ids.current.windIcon = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_DIRECTION');
|
||||
this.ids.current.windDirection = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_DIRECTION_STR');
|
||||
if (!this.ids.current.windDirection) {
|
||||
this.ids.current.windDirection = state && state.id;
|
||||
} else if (state) {
|
||||
const pos = this.subscribes.indexOf(state.id);
|
||||
this.subscribes.splice(pos, 1);
|
||||
state.id = null;
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP_MIN');
|
||||
this.ids.current.temperatureMin = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP_MAX');
|
||||
this.ids.current.temperatureMax = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PRECIPITATION_CHANCE');
|
||||
this.ids.current.precipitation = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HISTORY_CHART');
|
||||
this.ids.current.history = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'FORECAST_CHART');
|
||||
this.ids.current.chart = state && state.id;
|
||||
|
||||
for (let d = 0; d < 6; d++) {
|
||||
this.ids.days[d] = this.ids.days[d] || {};
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DATE' + d);
|
||||
this.ids.days[d].date = state && state.id;
|
||||
|
||||
if (!this.ids.days[d].date) {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'DOW' + d);
|
||||
this.ids.days[d].date = state && state.id;
|
||||
}
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'ICON' + d);
|
||||
this.ids.days[d].icon = state && (state.id !== this.id) && state.id ;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'STATE' + d);
|
||||
this.ids.days[d].state = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP_MIN' + d);
|
||||
this.ids.days[d].temperatureMin = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP_MAX' + d);
|
||||
this.ids.days[d].temperatureMax = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'TEMP' + d);
|
||||
this.ids.days[d].temperature = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUMIDITY' + d);
|
||||
this.ids.days[d].humidity = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUMIDITY_MIN' + d);
|
||||
this.ids.days[d].humidityMin = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'HUMIDITY_MAX' + d);
|
||||
this.ids.days[d].humidityMax = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_SPEED' + d);
|
||||
this.ids.days[d].windSpeed = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_ICON' + d);
|
||||
this.ids.days[d].windIcon = state && state.id;
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_DIRECTION' + d);
|
||||
this.ids.days[d].windDirection = state && state.id;
|
||||
|
||||
if (!this.ids.days[d].windDirection) {
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'WIND_DIRECTION_STR' + d);
|
||||
this.ids.days[d].windDirection = state && state.id;
|
||||
}
|
||||
|
||||
state = this.channelInfo.states.find(state => state.id && state.name === 'PRECIPITATION_CHANCE' + d);
|
||||
this.ids.days[d].precipitation = state && state.id;
|
||||
|
||||
let isEmpty = true;
|
||||
for (const id in this.ids.days[d]) {
|
||||
if (this.ids.days[d].hasOwnProperty(id) && this.ids.days[d][id]) {
|
||||
isEmpty = false;
|
||||
break
|
||||
}
|
||||
}
|
||||
if (isEmpty) {
|
||||
this.ids.days[d] = null;
|
||||
}
|
||||
}
|
||||
|
||||
let max = this.ids.days.length - 1;
|
||||
while (!this.ids.days[max] && max >= 0) {
|
||||
max--;
|
||||
}
|
||||
if (max < this.ids.days.length && !this.ids.days[max + 1]) {
|
||||
this.ids.days.splice(max + 1, this.ids.days.length - max - 1);
|
||||
}
|
||||
}
|
||||
|
||||
this.width = 2;
|
||||
this.props.tile.setState({isPointer: false});
|
||||
this.props.tile.setState({state: true});
|
||||
this.key = 'smart-weather-' + this.id + '-';
|
||||
|
||||
this.stateRx.showDialog = false; // support dialog in this tile used in generic class)
|
||||
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
applySettings(settings) {
|
||||
settings = settings || (this.state && this.state.settings);
|
||||
if (settings) {
|
||||
if (settings.tempID && (!this.subscribes || this.subscribes.indexOf(settings.tempID) === -1)) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
this.subscribes.push(settings.tempID);
|
||||
}
|
||||
if (settings.humidityID && (!this.subscribes || this.subscribes.indexOf(settings.humidityID) === -1)) {
|
||||
this.subscribes = this.subscribes || [];
|
||||
this.subscribes.push(settings.humidityID);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onUpdateTimer() {
|
||||
this.collectTimer = null;
|
||||
if (this.collectState) {
|
||||
this.setState(this.collectState);
|
||||
this.collectState = null;
|
||||
}
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
if (id === this.ids.current.temperature ||
|
||||
id === this.ids.current.humidity ||
|
||||
id === this.ids.current.windChill ||
|
||||
id === this.ids.current.windSpeed ||
|
||||
id === this.state.settings.tempID ||
|
||||
id === this.state.settings.humidityID ||
|
||||
id === this.ids.current.temperatureMin ||
|
||||
id === this.ids.current.temperatureMax ||
|
||||
id === this.ids.current.precipitation ||
|
||||
id === this.ids.current.pressure) {
|
||||
const val = Math.round(parseFloat(state.val));
|
||||
if (!isNaN(val)) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = val;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
}
|
||||
} else
|
||||
if (id === this.ids.current.icon ||
|
||||
id === this.ids.current.state ||
|
||||
id === this.ids.current.windIcon) {
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = state.val || '';
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else
|
||||
if (this.ids.current.location && this.ids.current.location.indexOf(id) !== -1) {
|
||||
this.collectState = this.collectState || {};
|
||||
if (state.val && state.val.replace(/[,.-]/g, '').trim()) {
|
||||
this.collectState.location = state.val || '';
|
||||
}
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else if (id === this.ids.current.windDirection || id === this.ids.current.windDegrees) {
|
||||
let dir = '';
|
||||
if (state && state.val !== null && state.val !== '' && state.val !== undefined && (typeof state.val === 'number' || parseInt(state.val, 10).toString() === state.val.toString())) {
|
||||
dir = I18n.t('wind_' + Utils.getWindDirection(state.val)).replace('wind_', '');
|
||||
} else {
|
||||
dir = state.val;
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = dir;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else if (id === this.ids.current.date) {
|
||||
let date = '';
|
||||
|
||||
if (state && state.val) {
|
||||
date = Utils.date2string(state.val) || '';
|
||||
}
|
||||
|
||||
this.collectState = this.collectState || {};
|
||||
this.collectState[id] = date;
|
||||
this.collectTimer && clearTimeout(this.collectTimer);
|
||||
this.collectTimer = setTimeout(() => this.onUpdateTimer(), 200);
|
||||
} else {
|
||||
console.log(id + ' => ' + state.val);
|
||||
super.updateState(id, state);
|
||||
}
|
||||
}
|
||||
|
||||
getDialogSettings() {
|
||||
const settings = super.getDialogSettings();
|
||||
settings.push({
|
||||
name: 'chartLast',
|
||||
value: this.state.settings.chartLast || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
settings.push({
|
||||
name: 'tempID',
|
||||
value: this.state.settings.tempID || '',
|
||||
type: 'string'
|
||||
});
|
||||
settings.push({
|
||||
name: 'humidityID',
|
||||
value: this.state.settings.humidityID || '',
|
||||
type: 'string'
|
||||
});
|
||||
settings.push({
|
||||
name: 'locationText',
|
||||
value: this.state.settings.locationText || '',
|
||||
type: 'string'
|
||||
});
|
||||
settings.push({
|
||||
name: 'hideFirstDay',
|
||||
value: this.state.settings.hideFirstDay || false,
|
||||
type: 'boolean'
|
||||
});
|
||||
// remove doubleSize from list
|
||||
settings.forEach((item, i) => {
|
||||
if (item.name === 'doubleSize') {
|
||||
settings.splice(i, 1);
|
||||
return false
|
||||
}
|
||||
});
|
||||
return settings;
|
||||
}
|
||||
|
||||
getCurrentIconDiv() {
|
||||
const classes = this.props.classes;
|
||||
let temp;
|
||||
temp = this.state.settings.tempID && this.state[this.state.settings.tempID];
|
||||
if (!temp && temp !== 0) {
|
||||
temp = this.ids.current.temperature && this.state[this.ids.current.temperature];
|
||||
}
|
||||
return (<div key="todayIcon" className={classes['currentIcon-div']}>
|
||||
<img className={classes['currentIcon-icon']} src={this.state[this.ids.current.icon]} alt={this.state[this.ids.current.state] || ''}/>
|
||||
{temp !== null && temp !== undefined ? (<div className={classes['currentIcon-temperature']}>{temp}°</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getCurrentDateLocationDiv() {
|
||||
const classes = this.props.classes;
|
||||
let date = this.ids.current.date && this.state[this.ids.current.date];
|
||||
let location = this.state.settings.locationText;
|
||||
location = location || this.state.location;
|
||||
|
||||
location = location || I18n.t('Weather');
|
||||
date = date || Utils.date2string(new Date());
|
||||
|
||||
return (<div key="location" className={classes['currentDate-div']}>
|
||||
<div className={classes['currentDate-date']}>{date},</div>
|
||||
<div className={classes['currentDate-location']}>{location}</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTodayWindDiv() {
|
||||
const classes = this.props.classes;
|
||||
let windChill = this.ids.current.windchill && this.state[this.ids.current.date];
|
||||
let windDir = this.ids.current.windDirection && this.state[this.ids.current.windDirection];
|
||||
if (windDir !== null && windDir !== undefined && (typeof windDir === 'number' || parseInt(windDir, 10) === windDir)) {
|
||||
windDir = I18n.t('wind_' + Utils.getWindDirection(windDir)).replace('wind_', '');
|
||||
}
|
||||
let windSpeed = this.ids.current.windSpeed && this.state[this.ids.current.windSpeed];
|
||||
let windIcon = this.ids.current.windIcon && this.state[this.ids.current.windIcon];
|
||||
|
||||
let state = this.ids.current.state && this.state[this.ids.current.state];
|
||||
return (<div key="todayWind" className={classes['todayState-div']}>
|
||||
|
||||
{windChill !== null && windChill !== undefined ?
|
||||
(<div key="windChill" className={classes['todayState-windChill']}>
|
||||
<span className={classes['todayState-windChillTitle']}>{I18n.t('Windchill')}: </span>
|
||||
<span className={classes['todayState-windChillValue']}>{windChill}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{(windDir !== null && windDir !== undefined) || (windSpeed !== null && windSpeed !== undefined) ?
|
||||
(<div key="wind" className={classes['todayState-wind']}>
|
||||
{!windIcon ? (<span key="windTitle" className={classes['todayState-windTitle']}>{I18n.t('Wind')}:</span>) : null}
|
||||
{windIcon ? (<img className={classes['todayState-windIcon']} src={windIcon} alt="state"/>) : null}
|
||||
{windDir ? (<span className={classes['todayState-windDir']}>{windDir}</span>) : null}
|
||||
{windSpeed !== null && windSpeed !== undefined && !isNaN(windSpeed) ? (<span key="windSpeed" className={classes['todayState-windSpeed']}>{windSpeed}{this.windUnit}</span>) : null}
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{state ? (<div key="state" className={classes['todayState-state']}>{state}</div>) : null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getTodayTempDiv() {
|
||||
const classes = this.props.classes;
|
||||
let tempMin = this.ids.current.temperatureMin && this.state[this.ids.current.temperatureMin];
|
||||
let tempMax = this.ids.current.temperatureMax && this.state[this.ids.current.temperatureMax];
|
||||
let precipitation = this.ids.current.precipitation && this.state[this.ids.current.precipitation];
|
||||
|
||||
let temp;
|
||||
if (tempMin !== null && tempMin !== undefined &&
|
||||
tempMax !== null && tempMax !== undefined && tempMin !== tempMax) {
|
||||
temp = [
|
||||
(<span key="max" className={classes['todayTemp-temperatureMax']}>{tempMax}°</span>),
|
||||
(<span key="mid"> / </span>),
|
||||
(<span key="min" className={classes['todayTemp-temperatureMin']}>{tempMin}°</span>)
|
||||
];
|
||||
} else if (
|
||||
(tempMin !== null && tempMin !== undefined) ||
|
||||
(tempMax !== null && tempMax !== undefined)) {
|
||||
if (tempMin === null || tempMin === undefined) {
|
||||
tempMin = tempMax;
|
||||
}
|
||||
temp = (<span key="max" className={classes['todayTemp-temperatureMax']}>{tempMin}°</span>);
|
||||
}
|
||||
|
||||
if (!temp && !precipitation && precipitation !== 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (<div key="todayTemp" className={classes['todayTemp-div']}>
|
||||
{temp !== null && temp !== undefined ?
|
||||
(<div key="temp" className={classes['todayTemp-temperature']}>
|
||||
<span className={classes['todayTemp-temperatureValue']}>{temp}</span>
|
||||
</div>)
|
||||
: null}
|
||||
|
||||
{precipitation !== null && precipitation !== undefined ?
|
||||
(<div key="precipitation" className={classes['todayTemp-precipitation']}>
|
||||
<span key="windTitle" className={classes['todayTemp-precipitationTitle']}>{I18n.t('Precip.')}:</span>
|
||||
<span className={classes['todayTemp-precipitationValue']}>{precipitation}%</span>
|
||||
</div>)
|
||||
: null}
|
||||
</div>);
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent([
|
||||
this.getCurrentIconDiv(),
|
||||
this.getCurrentDateLocationDiv(),
|
||||
this.getTodayWindDiv(),
|
||||
this.getTodayTempDiv(),
|
||||
this.state.showDialog ?
|
||||
<Dialog dialogKey={this.key + 'dialog'}
|
||||
key={this.key + 'dialog'}
|
||||
name={this.state.settings.name}
|
||||
enumNames={this.props.enumNames}
|
||||
settings={this.state.settings}
|
||||
objects={this.props.objects}
|
||||
windUnit={this.windUnit}
|
||||
pressureUnit={this.pressureUnit}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
ids={this.ids}
|
||||
windowWidth={this.props.windowWidth}
|
||||
onClose={this.onDialogClose.bind(this)}
|
||||
/> : null
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(SmartWeatherForecast);
|
188
src/src/States/SmartWindowTilt.js
Normal file
@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartGeneric from './SmartGeneric';
|
||||
import IconWindowOpened from '../icons/WindowOpened';
|
||||
import IconWindowClosed from '../icons/WindowClosed';
|
||||
import IconWindowTilted from '../icons/WindowTilted';
|
||||
import Theme from '../theme';
|
||||
import I18n from '../i18n';
|
||||
|
||||
const VALUES = {
|
||||
closed: [/close/i],
|
||||
tilted: [/tilt/i],
|
||||
opened: [/open/i]
|
||||
};
|
||||
|
||||
class SmartWindowTilt extends SmartGeneric {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
if (this.channelInfo.states) {
|
||||
let state = this.channelInfo.states.find(state => state.id && state.name === 'ACTUAL');
|
||||
if (state) {
|
||||
this.id = state.id;
|
||||
} else {
|
||||
this.id = '';
|
||||
}
|
||||
}
|
||||
this.values = {
|
||||
closed: 0,
|
||||
tilted: 1,
|
||||
opened: 2
|
||||
};
|
||||
|
||||
if (this.id && this.props.objects[this.id] && this.props.objects[this.id].common && this.props.objects[this.id].common.states) {
|
||||
const states = this.props.objects[this.id].common.states;
|
||||
for (const val in states) {
|
||||
if (states.hasOwnProperty(val)) {
|
||||
for (const v in VALUES) {
|
||||
if (VALUES.hasOwnProperty(v) && VALUES[v].find(r => r.test(states[val])) !== undefined) {
|
||||
this.values[v] = parseInt(val, 10);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.props.tile.setState({
|
||||
isPointer: false
|
||||
});
|
||||
this.key = 'smart-window-' + this.id + '-';
|
||||
|
||||
//this.props.tile.registerHandler('onClick', this.onTileClick.bind(this));
|
||||
this.componentReady();
|
||||
}
|
||||
|
||||
updateState(id, state) {
|
||||
let val;
|
||||
if (typeof state.val !== 'number') {
|
||||
const i = parseInt(state.val, 10);
|
||||
if (i.toString() === i) {
|
||||
val = i;
|
||||
} else if (state.val !== null && state.val !== undefined) {
|
||||
val = state.val.toString();
|
||||
|
||||
for (const value in VALUES) {
|
||||
if (VALUES.hasOwnProperty(value)) {
|
||||
// eslint-disable-next-line no-loop-func
|
||||
if (VALUES[value].find(r => r.test(val))) {
|
||||
val = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
state.val = 0;
|
||||
}
|
||||
} else {
|
||||
val = state.val;
|
||||
}
|
||||
if (typeof val === 'number') {
|
||||
for (const value in this.values) {
|
||||
if (this.values.hasOwnProperty(value) && this.values[value] === val) {
|
||||
val = value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (typeof val === 'number') {
|
||||
val = 'closed';
|
||||
}
|
||||
|
||||
if (id === this.id) {
|
||||
const newState = {};
|
||||
newState[id] = val;
|
||||
this.setState(newState);
|
||||
|
||||
if ((!this.props.tile.state.state && val !== 'closed') || (this.props.tile.state.state && val === 'closed')) {
|
||||
this.props.tile.setState({
|
||||
state: val !== 'closed'
|
||||
});
|
||||
}
|
||||
} else {
|
||||
super.updateState(id, state);
|
||||
}
|
||||
if (this.hideOnFalse) {
|
||||
let someIndicator = false;
|
||||
if (this.indicators) {
|
||||
const ids = Object.keys(this.indicators).filter(_id => this.indicators[_id]);
|
||||
someIndicator = ids.find(_id => this.state[this.indicators[_id]]);
|
||||
}
|
||||
|
||||
this.props.tile.setState({
|
||||
visible: this.state[this.id] || someIndicator
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
getIcon() {
|
||||
let Icon;
|
||||
switch (this.state[this.id]) {
|
||||
case 'opened':
|
||||
Icon = IconWindowOpened;
|
||||
break;
|
||||
|
||||
case 'tilted':
|
||||
Icon = IconWindowTilted;
|
||||
break;
|
||||
|
||||
case 'closed':
|
||||
default:
|
||||
Icon = IconWindowClosed;
|
||||
break;
|
||||
}
|
||||
|
||||
const iconStyle = {
|
||||
width: 60,
|
||||
height: 60,
|
||||
top: '0.2rem',
|
||||
left: '0.2rem'
|
||||
};
|
||||
let customIcon;
|
||||
|
||||
if (this.state.settings.useDefaultIcon) {
|
||||
customIcon = (<img alt="icon" src={this.getDefaultIcon()} style={{width: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
if (this.state.settings.icon) {
|
||||
customIcon = (<img alt="icon" src={this.state.settings.icon} style={{height: '100%', zIndex: 1}}/>);
|
||||
} else {
|
||||
customIcon = (<Icon width={'100%'} style={{zIndex: 1}}/>);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div key={this.key + 'icon'} style={Object.assign({}, Theme.tile.tileIcon, iconStyle)} className="tile-icon">
|
||||
{customIcon}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
getStateText() {
|
||||
if (this.state[this.id]){
|
||||
return I18n.t(this.state[this.id]);
|
||||
} else {
|
||||
return I18n.t('unknown');
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.wrapContent(this.getStandardContent(this.actualId));
|
||||
}
|
||||
}
|
||||
|
||||
export default SmartWindowTilt;
|
||||
|
567
src/src/StatesList.js
Normal file
@ -0,0 +1,567 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 SmartTile from './SmartTile';
|
||||
import { withStyles } from '@material-ui/core/styles';
|
||||
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'
|
||||
import {FaArrowsAltV as IconVertical} from 'react-icons/fa'
|
||||
import {MdAdd as IconAdd} from 'react-icons/md'
|
||||
import {FaArrowsAltH as IconHorizontal} from 'react-icons/fa'
|
||||
import Button from '@material-ui/core/Button';
|
||||
|
||||
import Theme from './theme';
|
||||
import Utils from './Utils';
|
||||
import I18n from './i18n';
|
||||
import StatesSubList from './StatesSubList';
|
||||
|
||||
const styles = {
|
||||
'drag-item': {
|
||||
display: 'inline-block',
|
||||
width: '100%'
|
||||
},
|
||||
'drag-item-overlay': {
|
||||
backgroundColor: 'green',
|
||||
borderRadius: '1em'
|
||||
},
|
||||
'sub-list-disabled-overflow': {
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
position: 'absolute',
|
||||
right: 0,
|
||||
left: 0,
|
||||
zIndex: 2,
|
||||
backgroundColor: 'rgba(90,90,90,0.5)'
|
||||
},
|
||||
'drag-button': {
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
right: 30,
|
||||
zIndex: 4
|
||||
},
|
||||
'add-button': {
|
||||
position: 'fixed',
|
||||
top: 70,
|
||||
right: 100,
|
||||
zIndex: 4
|
||||
}
|
||||
};
|
||||
|
||||
class StatesList extends Component {
|
||||
|
||||
static propTypes = {
|
||||
enumID: PropTypes.string.isRequired,
|
||||
user: PropTypes.string.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
editMode: PropTypes.bool.isRequired,
|
||||
states: PropTypes.object.isRequired,
|
||||
connected: PropTypes.bool.isRequired,
|
||||
debug: PropTypes.bool,
|
||||
background: PropTypes.string.isRequired,
|
||||
backgroundId: PropTypes.number,
|
||||
backgroundColor: PropTypes.string,
|
||||
align: PropTypes.string,
|
||||
ignoreIndicators: PropTypes.array,
|
||||
windowWidth: PropTypes.number,
|
||||
windowHeight: PropTypes.number,
|
||||
newLine: PropTypes.bool
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.enumFunctions = [];
|
||||
|
||||
this.state = {
|
||||
visible: false,
|
||||
newLine: false,
|
||||
dragging: false,
|
||||
subDragging: false,
|
||||
enumID: this.props.enumID,
|
||||
align: this.props.align,
|
||||
order: Utils.getSettingsOrder(this.props.objects[this.props.enumID], null, {user: this.props.user}),
|
||||
customURLs: Utils.getSettingsCustomURLs(this.props.objects[this.props.enumID], null, {user: this.props.user}),
|
||||
background: this.props.background,
|
||||
backgroundId: this.props.backgroundId,
|
||||
visibleChildren: {}
|
||||
};
|
||||
if (this.state.order !== null && !(this.state.order instanceof Array)) {
|
||||
this.state.order = null;
|
||||
}
|
||||
this.keys = null;
|
||||
this.collectVisibility = null;
|
||||
this.collectVisibilityTimer = null;
|
||||
}
|
||||
|
||||
componentWillUpdate(nextProps, nextState) {
|
||||
if (!this.enumFunctions.length) {
|
||||
this.getEnumFunctions(nextProps.objects).forEach(e => this.enumFunctions.push(e));
|
||||
}
|
||||
const newState = {};
|
||||
let changed = false;
|
||||
|
||||
if (nextProps.newLine !== this.state.newLine) {
|
||||
newState.newLine = nextProps.newLine;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (nextProps.backgroundColor !== this.state.backgroundColor) {
|
||||
newState.backgroundColor = nextProps.backgroundColor;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.background !== this.state.background) {
|
||||
newState.background = nextProps.background;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.align !== this.state.align) {
|
||||
newState.align = nextProps.align;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.backgroundId !== this.state.backgroundId) {
|
||||
newState.backgroundId = nextProps.backgroundId;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.enumID !== this.state.enumID) {
|
||||
newState.enumID = nextProps.enumID;
|
||||
newState.order = Utils.getSettingsOrder(this.props.objects[newState.enumID], null, {user: this.props.user});
|
||||
if (newState.order !== null && !(newState.order instanceof Array)) {
|
||||
newState.order = null;
|
||||
}
|
||||
newState.customURLs = Utils.getSettingsCustomURLs(this.props.objects[newState.enumID], null, {user: this.props.user});
|
||||
|
||||
this.order = null;
|
||||
newState.visibleChildren = {};
|
||||
newState.visible = false;
|
||||
this.keys = null;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
this.setState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
onDragEnd(result) {
|
||||
const newState = {dragging: false};
|
||||
|
||||
if (result.destination && result.destination.index !== result.source.index) {
|
||||
this.order = Utils.reorder(this.order, result.source.index, result.destination.index);
|
||||
newState.order = this.order;
|
||||
const settings = Utils.getSettings(this.props.objects[this.props.enumID], {user: this.props.user});
|
||||
settings.order = settings.order || {};
|
||||
settings.order = this.order.filter(id => this.state.visibleChildren[id]);
|
||||
this.props.onSaveSettings && this.props.onSaveSettings(this.props.enumID, settings);
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
}
|
||||
|
||||
getElementsToShow() {
|
||||
if (this.props.enumID === Utils.INSTANCES) {
|
||||
return Object.keys(this.props.objects).filter(id => !this.props.objects[id].common.onlyWWW).sort((a, b) => {
|
||||
const objA = this.props.objects[a].common;
|
||||
const objB = this.props.objects[b].common;
|
||||
if (objA.onlyWWW && objB.onlyWWW) {
|
||||
if (objA.name > objB.name) return 1;
|
||||
if (objA.name < objB.name) return -1;
|
||||
return 0;
|
||||
} else if (objA.onlyWWW) {
|
||||
return 1;
|
||||
} else if (objB.onlyWWW) {
|
||||
return -1;
|
||||
} else {
|
||||
if (objA.name > objB.name) return 1;
|
||||
if (objA.name < objB.name) return -1;
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
let _enum = this.props.objects[this.state.enumID];
|
||||
|
||||
return _enum && _enum.common ? _enum.common.members || [] : [];
|
||||
}
|
||||
}
|
||||
|
||||
getEnums(objects, enums) {
|
||||
objects = objects || this.props.objects;
|
||||
let result = [];
|
||||
|
||||
for (let id in objects) {
|
||||
if (objects.hasOwnProperty(id) &&
|
||||
objects[id] &&
|
||||
objects[id].common &&
|
||||
objects[id].common.members &&
|
||||
objects[id].common.members.length &&
|
||||
id.startsWith(enums)
|
||||
) {
|
||||
result.push(id);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
onVisibilityTimer() {
|
||||
this.collectVisibilityTimer = null;
|
||||
let commonVisible = false;
|
||||
const combinedVisibility = Object.assign({}, this.state.visibleChildren, this.collectVisibility);
|
||||
for (const _id in combinedVisibility) {
|
||||
if (combinedVisibility.hasOwnProperty(_id) && combinedVisibility[_id] ) {
|
||||
commonVisible = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const newState = {visibleChildren: combinedVisibility};
|
||||
|
||||
if (this.state.visible !== commonVisible) {
|
||||
newState.visible = commonVisible;
|
||||
this.props.onVisibilityControl && this.props.onVisibilityControl(this.props.enumSubID, commonVisible);
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
this.collectVisibility = null;
|
||||
}
|
||||
|
||||
onVisibilityControl(id, visible) {
|
||||
const oldState = this.collectVisibility && this.collectVisibility[id] !== undefined ? this.collectVisibility[id] : this.state.visibleChildren[id];
|
||||
|
||||
if (oldState !== visible) {
|
||||
this.collectVisibility = this.collectVisibility || {};
|
||||
this.collectVisibility[id] = visible;
|
||||
if (this.collectVisibilityTimer) {
|
||||
clearTimeout(this.collectVisibilityTimer);
|
||||
}
|
||||
this.collectVisibilityTimer = setTimeout(() => this.onVisibilityTimer(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
onDelete(id) {
|
||||
if (id === this.props.enumID) {
|
||||
const customURLs = Utils.getSettingsCustomURLs(this.props.objects[this.props.enumID], null, {user: this.props.user});
|
||||
this.setState({customURLs});
|
||||
}
|
||||
}
|
||||
|
||||
getEnumFunctions() {
|
||||
return this.getEnums('enum.functions.');
|
||||
}
|
||||
|
||||
wrapItem(id, items, isUseBright, index) {
|
||||
if (!this.state.subDragging && this.props.editMode && id !== 'nothing' && id !== Utils.INSTANCES) {
|
||||
return (<Draggable
|
||||
key={this.state.enumID + '_' + id + '-list1'}
|
||||
draggableId={this.state.enumID + '_' + id + '-list'} index={index}>
|
||||
{(provided, snapshot) => (
|
||||
<div
|
||||
key={this.state.enumID + '_' + id + '-list2'}
|
||||
className={this.props.classes['drag-item'] + (snapshot.isDragging ? ' ' + this.props.classes['drag-item-overlay'] : '')}
|
||||
style={{display: 'inline-block'}}
|
||||
ref={provided.innerRef}
|
||||
{...provided.draggableProps}
|
||||
// {...provided.dragHandleProps}
|
||||
><StatesSubList
|
||||
key={this.state.enumID + '_' + id + '-list'}
|
||||
objects={this.props.objects}
|
||||
user={this.props.user}
|
||||
states={this.props.states}
|
||||
newLine={this.props.newLine}
|
||||
items={items}
|
||||
isUseBright={isUseBright}
|
||||
ignoreIndicators={this.props.ignoreIndicators}
|
||||
onVisibilityControl={this.onVisibilityControl.bind(this)}
|
||||
onDelete={this.onDelete.bind(this)}
|
||||
debug={this.props.debug}
|
||||
align={this.state.align}
|
||||
editMode={this.props.editMode}
|
||||
windowWidth={this.props.windowWidth}
|
||||
enumFunctions={this.enumFunctions}
|
||||
enumID={id === Utils.INSTANCES ? Utils.INSTANCES : this.state.enumID}
|
||||
enumSubID={id === Utils.INSTANCES ? '' : id}
|
||||
keys={this.keys}
|
||||
onSaveSettings={this.props.onSaveSettings}
|
||||
onControl={this.props.onControl}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
dragHandleProps={provided.dragHandleProps}
|
||||
subDragging={false}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</Draggable>);
|
||||
} else {
|
||||
const control = (<StatesSubList
|
||||
key={this.state.enumID + '_' + id + '-list'}
|
||||
objects={this.props.objects}
|
||||
user={this.props.user}
|
||||
states={this.props.states}
|
||||
newLine={this.props.newLine}
|
||||
items={items}
|
||||
isUseBright={isUseBright}
|
||||
ignoreIndicators={this.props.ignoreIndicators}
|
||||
onVisibilityControl={this.onVisibilityControl.bind(this)}
|
||||
onDelete={this.onDelete.bind(this)}
|
||||
debug={this.props.debug}
|
||||
align={this.state.align}
|
||||
editMode={this.props.editMode}
|
||||
windowWidth={this.props.windowWidth}
|
||||
enumFunctions={this.enumFunctions}
|
||||
enumID={id === Utils.INSTANCES ? Utils.INSTANCES : this.state.enumID}
|
||||
enumSubID={id === Utils.INSTANCES ? '' : id}
|
||||
keys={this.keys}
|
||||
onSaveSettings={this.props.onSaveSettings}
|
||||
onControl={this.props.onControl}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
subDragging={true}
|
||||
/>);
|
||||
if (this.props.editMode) {
|
||||
return (<div
|
||||
key={this.state.enumID + '_' + id + '-list2'}
|
||||
className={this.props.classes['drag-item']}
|
||||
style={{display: 'inline-block'}}
|
||||
>{control}</div>);
|
||||
} else {
|
||||
return control;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
wrapAllItems(columns, provided, snapshot, style) {
|
||||
style = Object.assign({marginLeft: this.props.marginLeft, width: 'calc(100% - ' + this.props.marginLeft + 'px)'}, style);
|
||||
|
||||
return (
|
||||
<div style={style} ref={provided.innerRef} {...provided.droppableProps}>
|
||||
{columns}
|
||||
{provided.placeholder}
|
||||
{this.getToggleDragButton()}
|
||||
{this.getAddButton()}
|
||||
</div>);
|
||||
}
|
||||
|
||||
getToggleDragButton() {
|
||||
if (this.props.editMode && this.props.enumID !== Utils.INSTANCES) {
|
||||
return (<Button key={this.props.dialogKey + '-drag-button'}
|
||||
variant="fab"
|
||||
title={I18n.t('Drag direction')}
|
||||
style={{fontSize: 24}}
|
||||
onClick={() => this.setState({subDragging: !this.state.subDragging})}
|
||||
className={this.props.classes['drag-button']}>
|
||||
{this.state.subDragging ? <IconHorizontal/> : <IconVertical/>}
|
||||
</Button>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
onAddCustomURL () {
|
||||
const newState = {customURLs: JSON.parse(JSON.stringify(this.state.customURLs || []))};
|
||||
|
||||
newState.customURLs.push({
|
||||
type: 'url',
|
||||
title: I18n.t('Custom URL'),
|
||||
id: '_custom_' + Date.now(),
|
||||
settingsId: this.state.enumID,
|
||||
enabled: true,
|
||||
fullWidth: true,
|
||||
doubleSize: true
|
||||
});
|
||||
|
||||
this.order = null;
|
||||
|
||||
const settings = Utils.getSettings(this.props.objects[this.props.enumID], {user: this.props.user});
|
||||
settings.URLs = newState.customURLs;
|
||||
this.props.onSaveSettings && this.props.onSaveSettings(this.props.enumID, settings, () => {
|
||||
this.setState(newState);
|
||||
});
|
||||
}
|
||||
|
||||
getAddButton() {
|
||||
if (this.props.editMode && this.props.enumID !== Utils.INSTANCES) {
|
||||
return (<Button key={this.props.dialogKey + '-add-button'}
|
||||
variant="fab"
|
||||
title={I18n.t('Add custom URL')}
|
||||
style={{fontSize: 24}}
|
||||
onClick={() => this.onAddCustomURL()}
|
||||
className={this.props.classes['add-button']}>
|
||||
<IconAdd/>
|
||||
</Button>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
wrapContent(columns, isNothing) {
|
||||
let style;
|
||||
if (this.state.background) {
|
||||
if (this.state.background.match(/\.jpg$|\.gif$|\.png$|\.jpeg$/)) {
|
||||
style = Object.assign({}, Theme.mainPanel, {
|
||||
backgroundSize: this.props.windowWidth > this.props.windowHeight ? '100% auto' : 'auto 100%',
|
||||
backgroundImage: 'url(' + this.state.background + (this.state.backgroundId ? '?ts=' + Date.now() : '') + ')'});
|
||||
} else {
|
||||
style = Object.assign({}, Theme.mainPanel, {background: this.state.background, backgroundImage: 'none'});
|
||||
}
|
||||
} else if (this.state.backgroundColor) {
|
||||
style = Object.assign({}, Theme.mainPanel, {background: this.state.backgroundColor, backgroundImage: 'none'});
|
||||
} else {
|
||||
style = Object.assign({}, Theme.mainPanel, {backgroundSize: this.props.windowWidth > this.props.windowHeight ? '100% auto' : 'auto 100%'});
|
||||
}
|
||||
|
||||
if (this.state.align && !this.state.dragging) {
|
||||
style.textAlign = this.state.align;
|
||||
}
|
||||
|
||||
if (!this.state.subDragging && this.props.editMode && this.props.enumID !== Utils.INSTANCES && !isNothing) {
|
||||
return (
|
||||
<DragDropContext onDragEnd={result => this.onDragEnd(result)} onDragStart={() => this.setState({dragging: true})}>
|
||||
<Droppable droppableId="mainList" direction="vertical">
|
||||
{(provided, snapshot) => this.wrapAllItems(columns, provided, snapshot, style)}
|
||||
</Droppable>
|
||||
</DragDropContext>
|
||||
);
|
||||
} else {
|
||||
return (<div style={Object.assign({marginLeft: this.props.marginLeft}, style)}>
|
||||
{columns}
|
||||
{this.getToggleDragButton()}
|
||||
{this.getAddButton()}
|
||||
</div>);
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
let items = this.getElementsToShow();
|
||||
if (items.length > 300) {
|
||||
return null; // something is wrong
|
||||
}
|
||||
|
||||
let columns = [];
|
||||
|
||||
if (!this.keys || !this.keys.length) {
|
||||
this.keys = Object.keys(this.props.objects);
|
||||
this.keys.sort();
|
||||
}
|
||||
if (!this.enumFunctions.length) {
|
||||
this.getEnumFunctions(this.props.objects).forEach(e => this.enumFunctions.push(e));
|
||||
}
|
||||
|
||||
|
||||
if (this.props.enumID === Utils.INSTANCES) {
|
||||
columns.push({items, id: Utils.INSTANCES});
|
||||
} else
|
||||
if (items && items.length) {
|
||||
let orderEnums;
|
||||
if (this.state.enumID && this.state.enumID.startsWith('enum.rooms.')) {
|
||||
orderEnums = 'enum.functions.';
|
||||
} else
|
||||
if (this.state.enumID && this.state.enumID.startsWith('enum.functions.')) {
|
||||
orderEnums = 'enum.rooms.';
|
||||
} else {
|
||||
orderEnums = 'enum.functions.';
|
||||
}
|
||||
|
||||
let enums = this.getEnums(this.props.objects, orderEnums);
|
||||
let used = [];
|
||||
enums.forEach(id => {
|
||||
const obj = this.props.objects[id];
|
||||
let column = [];
|
||||
if (obj && obj.common && obj.common.members && obj.common.members.length) {
|
||||
column = obj.common.members.filter(item => {
|
||||
return used.indexOf(item) === -1 && items.indexOf(item) !== -1;
|
||||
});
|
||||
}
|
||||
|
||||
if (column.length) {
|
||||
this.props.debug && console.log('Add to ' + this.state.enumID + '_' + id + ': ' + column.join(', '));
|
||||
columns.push({id, items: column});
|
||||
column.forEach(id => used.push(id));
|
||||
}
|
||||
});
|
||||
|
||||
// collect others
|
||||
let column = [];
|
||||
items.forEach(item => {
|
||||
if (used.indexOf(item) === -1) {
|
||||
column.push(item);
|
||||
}
|
||||
});
|
||||
|
||||
if (column.length || (this.state.customURLs && this.state.customURLs.length)) {
|
||||
this.props.debug && console.log('Add to others: ' + column.join(', '));
|
||||
|
||||
if (this.state.customURLs && this.state.customURLs.length) {
|
||||
this.state.customURLs.forEach(e => {
|
||||
column.push({id: e.id, settingsId: this.state.enumID, name: 'URL'});
|
||||
});
|
||||
}
|
||||
|
||||
if (column.length) {
|
||||
columns.push({id: 'others', items: column});
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.state.visible) {
|
||||
columns.push({id: 'nothing'});
|
||||
}
|
||||
} else {
|
||||
columns.push({id: 'nothing'});
|
||||
}
|
||||
|
||||
if (!this.order) {
|
||||
this.order = this.state.order;
|
||||
if (!this.order) {
|
||||
this.order = columns.map(c => c.id);
|
||||
} else {
|
||||
// add missing IDs
|
||||
columns.forEach(c => this.order.indexOf(c.id) === -1 && this.order.push(c.id));
|
||||
|
||||
// remove deleted IDs
|
||||
for (let i = this.order.length - 1; i >= 0; i--) {
|
||||
// if ID does not exist any more
|
||||
if (!columns.find(c => this.order[i] === c.id)) {
|
||||
this.order.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let pos = this.order.indexOf('nothing');
|
||||
if (pos !== -1 && pos !== this.order.length - 1) {
|
||||
this.order.splice(pos, 1);
|
||||
this.order.push('nothing');
|
||||
}
|
||||
const background = this.props.backgroundColor;
|
||||
const isUseBright = !background || Utils.isUseBright(background);
|
||||
|
||||
const orderedColumns = this.order.map(function (id, i) {
|
||||
const elem = columns.find(c => c.id === id);
|
||||
if (elem) {
|
||||
if (elem.id === 'nothing') {
|
||||
return (<SmartTile
|
||||
key="nothing"
|
||||
editMode={this.props.editMode}
|
||||
user={this.props.user}
|
||||
states={this.props.states}
|
||||
objects={this.props.objects}
|
||||
id=""/>);
|
||||
} else {
|
||||
return this.wrapItem(elem.id, elem.items, isUseBright, i);
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}.bind(this)).filter(e => e);
|
||||
|
||||
return this.wrapContent(orderedColumns);
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(StatesList);
|
508
src/src/StatesSubList.js
Normal file
@ -0,0 +1,508 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 { withStyles } from '@material-ui/core/styles';
|
||||
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd'
|
||||
import ButtonBase from '@material-ui/core/ButtonBase';
|
||||
|
||||
import {MdPermScanWifi as IconUnreach} from 'react-icons/md';
|
||||
import {MdDragHandle as IconGrip} from 'react-icons/md';
|
||||
import {TiLightbulb as IconLight} from 'react-icons/ti';
|
||||
|
||||
import Utils from './Utils';
|
||||
import Theme from './theme';
|
||||
import I18n from './i18n';
|
||||
import SmartTile from './SmartTile';
|
||||
import SmartDetector from './States/SmartDetector';
|
||||
import Types from './States/SmartTypes';
|
||||
import VisibilityButton from './basic-controls/react-visibility-button/VisibilityButton';
|
||||
|
||||
const styles = {
|
||||
'drag-item': {
|
||||
display: 'inline-block'
|
||||
},
|
||||
'drag-item-overlay': {
|
||||
backgroundColor: 'green',
|
||||
borderRadius: '1em'
|
||||
},
|
||||
'sub-list-disabled-overflow': {
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
position: 'absolute',
|
||||
right: 0,
|
||||
left: 0,
|
||||
zIndex: 2,
|
||||
backgroundColor: 'rgba(90,90,90,0.5)'
|
||||
}
|
||||
};
|
||||
|
||||
class StatesSubList extends Component {
|
||||
|
||||
static propTypes = {
|
||||
enumID: PropTypes.string.isRequired,
|
||||
enumSubID: PropTypes.string.isRequired,
|
||||
user: PropTypes.string.isRequired,
|
||||
objects: PropTypes.object.isRequired,
|
||||
editMode: PropTypes.bool.isRequired,
|
||||
debug: PropTypes.bool,
|
||||
ignoreIndicators: PropTypes.array,
|
||||
onSaveSettings: PropTypes.func,
|
||||
onDelete: PropTypes.func,
|
||||
windowWidth: PropTypes.number,
|
||||
align: PropTypes.string,
|
||||
newLine: PropTypes.bool,
|
||||
subDragging: PropTypes.bool,
|
||||
dragHandleProps: PropTypes.object,
|
||||
isUseBright: PropTypes.bool,
|
||||
states: PropTypes.object.isRequired,
|
||||
keys: PropTypes.array.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.detector = new SmartDetector();
|
||||
const settings = Utils.getSettings(this.props.objects[this.props.enumSubID], {user: this.props.user});
|
||||
|
||||
this.state = {
|
||||
visible: false,
|
||||
newLine: false,
|
||||
align: this.props.align,
|
||||
enumID: this.props.enumID,
|
||||
subDragging: this.props.subDragging,
|
||||
enumSubID: this.props.enumSubID,
|
||||
enabled: settings && settings.subEnabled ? (settings.subEnabled[this.props.enumID] === undefined ? true : settings.subEnabled[this.props.enumID]) : true,
|
||||
order: Utils.getSettingsOrder(this.props.objects[this.props.enumSubID], this.props.enumID, {user: this.props.user}),
|
||||
dragging: false,
|
||||
visibleChildren: {}
|
||||
};
|
||||
if (this.state.enumID === Utils.INSTANCES) {
|
||||
this.name = I18n.t('All instances');
|
||||
} else {
|
||||
this.name = this.state.enumSubID && this.state.enumSubID !== 'others' ? Utils.getObjectName(this.props.objects, this.state.enumSubID, false, {language: I18n.getLanguage()}) : I18n.t('Others');
|
||||
}
|
||||
this.widgetTypes = {};
|
||||
this.collectVisibility = null;
|
||||
this.collectVisibilityTimer = null;
|
||||
}
|
||||
|
||||
componentWillUpdate(nextProps, nextState) {
|
||||
const newState = {};
|
||||
let changed = false;
|
||||
|
||||
if (nextProps.newLine !== this.state.newLine) {
|
||||
newState.newLine = nextProps.newLine;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (nextProps.align !== this.state.align) {
|
||||
newState.align = nextProps.align;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (nextProps.subDragging !== this.state.subDragging) {
|
||||
newState.subDragging = nextProps.subDragging;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (nextProps.editMode !== this.state.editMode) {
|
||||
this.order = null;
|
||||
}
|
||||
|
||||
if (nextProps.enumID !== this.state.enumID) {
|
||||
newState.enumID = nextProps.enumID;
|
||||
newState.visibleChildren = {};
|
||||
newState.visible = false;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.enumSubID !== this.state.enumSubID) {
|
||||
this.name = nextProps.enumSubID ? Utils.getObjectName(this.props.objects, nextProps.enumSubID, false, {language: I18n.getLanguage()}) : I18n.t('Others');
|
||||
newState.enumSubID = nextProps.enumSubID;
|
||||
newState.visibleChildren = {};
|
||||
newState.visible = false;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
this.setState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
onDragStart() {
|
||||
this.setState({dragging: true});
|
||||
}
|
||||
|
||||
onDragEnd(result) {
|
||||
const newState = {dragging: false};
|
||||
|
||||
if (result.destination && result.destination.index !== result.source.index) {
|
||||
this.order = Utils.reorder(this.order, result.source.index, result.destination.index);
|
||||
newState.order = this.order;
|
||||
const settings = Utils.getSettings(this.props.objects[this.props.enumSubID], {user: this.props.user});
|
||||
settings.subOrder = settings.subOrder || {};
|
||||
settings.subOrder[this.props.enumID] = this.order.filter(id => this.state.visibleChildren[id]);
|
||||
this.props.onSaveSettings && this.props.onSaveSettings(this.props.enumSubID, settings);
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
}
|
||||
|
||||
onToggleSubEnabled() {
|
||||
const settings = Utils.getSettings(this.props.objects[this.props.enumSubID], {user: this.props.user});
|
||||
settings.subEnabled = settings.subEnabled || {};
|
||||
let enabled = settings.subEnabled[this.props.enumID] === undefined ? true : settings.subEnabled[this.props.enumID];
|
||||
enabled = !enabled;
|
||||
settings.subEnabled[this.props.enumID] = enabled;
|
||||
this.props.onSaveSettings && this.props.onSaveSettings(this.props.enumSubID, settings, () => {
|
||||
this.setState({enabled});
|
||||
});
|
||||
}
|
||||
|
||||
onVisibilityTimer() {
|
||||
this.collectVisibilityTimer = null;
|
||||
let commonVisible = false;
|
||||
const newState = {visibleChildren: commonVisible};
|
||||
if (this.props.editMode || this.state.enabled) {
|
||||
const combinedVisibility = Object.assign({}, this.state.visibleChildren, this.collectVisibility);
|
||||
for (const _id in combinedVisibility) {
|
||||
if (combinedVisibility.hasOwnProperty(_id) && combinedVisibility[_id]) {
|
||||
commonVisible = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
newState.visibleChildren = combinedVisibility;
|
||||
}
|
||||
|
||||
if (this.state.visible !== commonVisible) {
|
||||
newState.visible = commonVisible;
|
||||
this.props.onVisibilityControl && this.props.onVisibilityControl(this.state.enumSubID, commonVisible);
|
||||
}
|
||||
|
||||
this.setState(newState);
|
||||
this.collectVisibility = null;
|
||||
}
|
||||
|
||||
|
||||
onVisibilityControl(id, visible, isDelete) {
|
||||
const oldState = this.collectVisibility && this.collectVisibility[id] !== undefined ? this.collectVisibility[id] : this.state.visibleChildren[id];
|
||||
|
||||
if (oldState !== visible) {
|
||||
this.collectVisibility = this.collectVisibility || {};
|
||||
this.collectVisibility[id] = visible;
|
||||
if (this.collectVisibilityTimer) {
|
||||
clearTimeout(this.collectVisibilityTimer);
|
||||
}
|
||||
this.collectVisibilityTimer = setTimeout(() => this.onVisibilityTimer(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
createControl(control, channelId, channelInfo, i) {
|
||||
if (!channelInfo) {
|
||||
debugger
|
||||
}
|
||||
|
||||
let state = channelInfo.states.find(state => state.id);
|
||||
|
||||
let Component = control; // This will be used by rendering
|
||||
// ↓
|
||||
return (<Component
|
||||
key={state.id + '-sublist-' + Component.name + '-' + i}
|
||||
id={channelId}
|
||||
enumNames={[this.name, Utils.getObjectName(this.props.objects, this.state.enumID, null, {language: I18n.getLanguage()})]}
|
||||
enumFunctions={this.props.enumFunctions}
|
||||
editMode={this.props.editMode}
|
||||
channelInfo={channelInfo}
|
||||
ignoreIndicators={this.props.ignoreIndicators}
|
||||
windowWidth={this.props.windowWidth}
|
||||
states={this.props.states}
|
||||
objects={this.props.objects}
|
||||
user={this.props.user}
|
||||
onVisibilityControl={this.onVisibilityControl.bind(this)}
|
||||
onDelete={this.props.onDelete}
|
||||
onSaveSettings={this.props.onSaveSettings}
|
||||
onCollectIds={this.props.onCollectIds}
|
||||
onControl={this.props.onControl}
|
||||
/>);
|
||||
}
|
||||
|
||||
getListItems(items) {
|
||||
const usedIds = [];
|
||||
|
||||
if (this.props.enumID === Utils.INSTANCES) {
|
||||
return items.map(function (id, i) {
|
||||
return {
|
||||
control: this.createControl(SmartTile, id, {
|
||||
states: [
|
||||
{id: id + '.alive', name: 'ALIVE'},
|
||||
{id: id + '.connected', name: 'UNREACH', type: 'boolean', indicator: true, icon: IconUnreach, color: Theme.tile.tileIndicatorsIcons.unreach}
|
||||
],
|
||||
type: Types.instance
|
||||
}, i),
|
||||
visible: true
|
||||
};
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
const controls = items.map(function (id) {
|
||||
if (this.state[id] === undefined) {
|
||||
//debugger;
|
||||
}
|
||||
|
||||
if (id && typeof id === 'object') {
|
||||
id = JSON.parse(JSON.stringify(id));
|
||||
id.name = 'URL';
|
||||
if (!id.id) {
|
||||
id.id = '_custom' + Math.random();
|
||||
}
|
||||
|
||||
// custom URL
|
||||
return {
|
||||
control: {
|
||||
type: Types.url,
|
||||
states: [id]
|
||||
},
|
||||
id: id.id
|
||||
};
|
||||
} else {
|
||||
const options = {
|
||||
objects: this.props.objects,
|
||||
id,
|
||||
_keysOptional: this.props.keys,
|
||||
_usedIdsOptional: usedIds,
|
||||
ignoreIndicators: this.props.ignoreIndicators
|
||||
};
|
||||
let controls = this.detector.detect(options);
|
||||
if (controls) {
|
||||
controls = controls.map(function (control) {
|
||||
const id = control.states.find(state => state.id).id;
|
||||
if (id) {
|
||||
this.widgetTypes[id] = {
|
||||
type: control.type,
|
||||
SET: control.states.find(state => state.name === 'SET'),
|
||||
ON_SET: control.states.find(state => state.name === 'ON_SET'),
|
||||
STOP: control.states.find(state => state.name === 'STOP'),
|
||||
};
|
||||
for (let a in this.widgetTypes[id]) {
|
||||
if (this.widgetTypes[id].hasOwnProperty(a) && a !== 'type' && this.widgetTypes[id][a]) {
|
||||
this.widgetTypes[id][a] = this.widgetTypes[id][a].id;
|
||||
}
|
||||
}
|
||||
|
||||
return {control, id};
|
||||
}
|
||||
}.bind(this));
|
||||
} else {
|
||||
this.props.debug && console.log('Nothing found for ' + id);
|
||||
}
|
||||
if (!controls || !controls.length) {
|
||||
return null;
|
||||
} else if (controls.length === 1) {
|
||||
return controls[0];
|
||||
} else {
|
||||
return controls;
|
||||
}
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
// join all arrays in one
|
||||
let result = [];
|
||||
controls.forEach(c => {
|
||||
if (c instanceof Array) {
|
||||
result = result.concat(c);
|
||||
} else if (c) {
|
||||
result.push(c);
|
||||
}
|
||||
});
|
||||
|
||||
// place visible first
|
||||
result.sort(function (a, b) {
|
||||
const av = this.state.visibleChildren[a.id];
|
||||
const bv = this.state.visibleChildren[b.id];
|
||||
if (av < bv) return 1;
|
||||
if (av > bv) return -1;
|
||||
return 0;
|
||||
}.bind(this));
|
||||
|
||||
if (!this.order) {
|
||||
this.order = this.state.order;
|
||||
if (!this.order) {
|
||||
this.order = result.map(c => c.id);
|
||||
} else {
|
||||
// add missing IDs
|
||||
result.forEach(c => this.order.indexOf(c.id) === -1 && this.order.push(c.id));
|
||||
|
||||
// remove deleted IDs
|
||||
for (let i = this.order.length - 1; i >= 0; i--) {
|
||||
// if ID does not exist any more
|
||||
if (!result.find(c => this.order[i] === c.id)) {
|
||||
this.order.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this.order.map(function (id, i) {
|
||||
const c = result.find(c => c.id === id);
|
||||
return {control: this.createControl(SmartTile, c.id, c.control, i), id: c.id};
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
wrapItem(item, index) {
|
||||
if (this.state.visibleChildren[item.id]) {
|
||||
const key = 'item-' + this.state.enumID + '-' + this.state.enumSubID + '-' + item.id;
|
||||
return (<Draggable key={key} draggableId={key} index={index}>
|
||||
{(provided, snapshot) => (
|
||||
<div
|
||||
className={this.props.classes['drag-item'] + (snapshot.isDragging ? ' ' + this.props.classes['drag-item-overlay'] : '')}
|
||||
style={{display: 'inline-block'}}
|
||||
ref={provided.innerRef}
|
||||
{...provided.draggableProps}
|
||||
{...provided.dragHandleProps}
|
||||
>
|
||||
{item.control}
|
||||
</div>
|
||||
)}
|
||||
</Draggable>);
|
||||
} else {
|
||||
return (<div key={'item-' + item.id}>{item.control}</div>);
|
||||
}
|
||||
}
|
||||
|
||||
wrapAllItems(items, provided, snapshot) {
|
||||
const style = {display: 'flex'};
|
||||
if (this.state.dragging) {
|
||||
style.background = 'rgba(2,173,2,0.26)';
|
||||
style.borderRadius = '1em';
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{width: '100%', overflow: 'auto'}}>
|
||||
<div style={style} ref={provided.innerRef} {...provided.droppableProps}>
|
||||
{items.map((item, index) => this.wrapItem(item, index))}
|
||||
{provided.placeholder}
|
||||
</div>
|
||||
</div>);
|
||||
}
|
||||
|
||||
wrapContent(items) {
|
||||
if (this.state.subDragging && this.props.editMode && this.props.enumID !== Utils.INSTANCES && this.state.enabled) {
|
||||
return(
|
||||
<DragDropContext
|
||||
onDragEnd={result => this.onDragEnd(result)}
|
||||
onDragStart={() => this.onDragStart()}>
|
||||
<Droppable droppableId={(this.state.enumID + '-' + this.state.enumSubID).replace(/[^\w\d]/g, '_') + '-droppable'} direction="horizontal">
|
||||
{(provided, snapshot) => this.wrapAllItems(items, provided, snapshot)}
|
||||
</Droppable>
|
||||
</DragDropContext>
|
||||
);
|
||||
} else if (this.props.editMode || (!this.state.subDragging || !this.state.enabled)) {
|
||||
return (
|
||||
<div key={(this.state.enumID + '-' + this.state.enumSubID).replace(/[^\w\d]/g, '_') + '-inset'} style={{width: '100%', overflow: 'auto', opacity: this.state.enabled ? 1 : 0.5}}>
|
||||
<div key="inline-div" style={{display: 'flex'}}>
|
||||
{items.map(e => (<div key={'inline-div-' + e.id}>{e.control}</div>))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return(<div key="inline-div">{items.map(e => e.control)}</div>);
|
||||
}
|
||||
}
|
||||
|
||||
controlAllLights(isOn) {
|
||||
for (let id in this.widgetTypes) {
|
||||
if (!this.widgetTypes.hasOwnProperty(id)) continue;
|
||||
if (this.widgetTypes[id].type === Types.dimmer) {
|
||||
if (this.widgetTypes[id].ON_SET) {
|
||||
this.props.onControl(this.widgetTypes[id].ON_SET, isOn);
|
||||
} else if (this.widgetTypes[id].SET) {
|
||||
this.props.onControl(this.widgetTypes[id].SET, isOn ? this.props.objects[this.widgetTypes[id].SET].common.max : this.props.objects[this.widgetTypes[id].SET].common.min);
|
||||
}
|
||||
} else if (this.widgetTypes[id].type === Types.light && this.widgetTypes[id].SET) {
|
||||
this.props.onControl(this.widgetTypes[id].SET, isOn);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getControlAll() {
|
||||
if (this.props.editMode) return null;
|
||||
|
||||
let countLights = 0;
|
||||
for (let id in this.widgetTypes) {
|
||||
if (this.widgetTypes.hasOwnProperty(id) &&
|
||||
(this.widgetTypes[id].type === Types.light || this.widgetTypes[id].type === Types.dimmer))
|
||||
{
|
||||
countLights++;
|
||||
}
|
||||
}
|
||||
if (countLights > 1) {
|
||||
return [
|
||||
(<ButtonBase key="light-off" variant="fab" mini="true" aria-label="Off" onClick={() => this.controlAllLights(false)} style={Object.assign({}, Theme.buttonAllLight, {color: 'black'})} title={I18n.t('All lights off')}><IconLight /></ButtonBase>),
|
||||
(<ButtonBase key="light-on" variant="fab" mini="true" aria-label="On" onClick={() => this.controlAllLights(true)} style={Object.assign({}, Theme.buttonAllLight, {color: Theme.palette.lampOn})} title={I18n.t('All lights on')}><IconLight /></ButtonBase>)
|
||||
];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.props.items && this.props.items.length) {
|
||||
let items = this.getListItems(this.props.items);
|
||||
items = items.filter(e => e);
|
||||
if (items.length) {
|
||||
const visible = this.state.visible || this.props.editMode;
|
||||
|
||||
const style = !visible ? {display: 'none'} : (this.state.newLine || this.props.editMode ? {display: 'block', border: 'none'} : {display: 'inline-block'});
|
||||
|
||||
if (this.state.align) {
|
||||
style.textAlign = this.state.align;
|
||||
}
|
||||
|
||||
const visibilityButton = this.props.editMode ? <VisibilityButton
|
||||
big={true}
|
||||
style={{display: 'inline-block', marginLeft: 15}}
|
||||
visible={this.state.enabled}
|
||||
useBright={this.props.isUseBright}
|
||||
onChange={() => this.onToggleSubEnabled()}/> : null;
|
||||
|
||||
//style={Object.assign({}, Theme.list.row, {display: display})}
|
||||
return (
|
||||
<div key={(this.state.enumID + '-' + this.state.enumSubID).replace(/[^\w\d]/g, '_') + '-title'}
|
||||
style={Object.assign({}, Theme.list.row, style)}>
|
||||
<h3 {...this.props.dragHandleProps} style={Object.assign({}, Theme.list.title, {color: this.props.isUseBright ? 'white' : 'black'})}>
|
||||
{this.props.editMode ? (<IconGrip style={{color: this.props.isUseBright ? 'white' : 'black', width: 24, height: 24, float: 'left', opacity: this.state.subDragging ? 0 : 1}}/>) : null}
|
||||
{this.name}
|
||||
{this.getControlAll()}
|
||||
{visibilityButton}
|
||||
</h3>
|
||||
{this.wrapContent(items)}
|
||||
</div>);
|
||||
} else {
|
||||
if (this.props.editMode) {
|
||||
return (<div {...this.props.dragHandleProps}/>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (this.props.editMode) {
|
||||
return (<div {...this.props.dragHandleProps}/>);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(StatesSubList);
|
450
src/src/Utils.js
Normal file
@ -0,0 +1,450 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 I18n from './i18n';
|
||||
|
||||
const NAMESPACE = 'material';
|
||||
const days = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
|
||||
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
||||
class Utils {
|
||||
static namespace = NAMESPACE;
|
||||
static INSTANCES = 'instances';
|
||||
static dateFormat = ['DD', 'MM'];
|
||||
|
||||
static CapitalWords(name) {
|
||||
return (name || '').split(/[\s_]/)
|
||||
.filter(item => item)
|
||||
.map(word => word ? word[0].toUpperCase() + word.substring(1).toLowerCase() : '')
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
static getObjectName(objects, id, settings, options, isDesc) {
|
||||
let item = objects[id];
|
||||
let text = id;
|
||||
const attr = isDesc ? 'desc' : 'name';
|
||||
|
||||
options = options || {};
|
||||
if (!options.language) {
|
||||
options.language = (objects['system.config'] && objects['system.config'].common && objects['system.config'].common.language) || window.sysLang || 'en';
|
||||
}
|
||||
if (settings && settings.name) {
|
||||
text = settings.name;
|
||||
if (typeof text === 'object') {
|
||||
text = text[options.language] || text.en;
|
||||
}
|
||||
} else
|
||||
if (item && item.common && item.common[attr]) {
|
||||
text = item.common[attr];
|
||||
if (attr !== 'desc' && !text && item.common.desc) {
|
||||
text = item.common.desc;
|
||||
}
|
||||
if (typeof text === 'object') {
|
||||
text = text[options.language] || text.en;
|
||||
}
|
||||
text = text.replace(/[_.]/g, ' ');
|
||||
|
||||
if (text === text.toUpperCase()) {
|
||||
text = text[0] + text.substring(1).toLowerCase();
|
||||
}
|
||||
} else {
|
||||
let pos = id.lastIndexOf('.');
|
||||
text = id.substring(pos + 1).replace(/[_.]/g, ' ');
|
||||
text = Utils.CapitalWords(text);
|
||||
}
|
||||
return text.trim();
|
||||
}
|
||||
|
||||
static getSettingsOrder(obj, forEnumId, options) {
|
||||
if (obj && obj.hasOwnProperty('common')) {
|
||||
obj = obj.common;
|
||||
}
|
||||
let settings;
|
||||
if (obj && obj.custom) {
|
||||
settings = (obj.custom || {})[NAMESPACE];
|
||||
const user = options.user || 'admin';
|
||||
if (settings && settings[user]) {
|
||||
if (forEnumId) {
|
||||
if (settings[user].subOrder && settings[user].subOrder[forEnumId]) {
|
||||
return JSON.parse(JSON.stringify(settings[user].subOrder[forEnumId]));
|
||||
}
|
||||
} else {
|
||||
if (settings[user].order) {
|
||||
return JSON.parse(JSON.stringify(settings[user].order));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static getSettingsCustomURLs(obj, forEnumId, options) {
|
||||
if (obj && obj.hasOwnProperty('common')) {
|
||||
obj = obj.common;
|
||||
}
|
||||
let settings;
|
||||
if (obj && obj.custom) {
|
||||
settings = (obj.custom || {})[NAMESPACE];
|
||||
const user = options.user || 'admin';
|
||||
if (settings && settings[user]) {
|
||||
if (forEnumId) {
|
||||
if (settings[user].subURLs && settings[user].subURLs[forEnumId]) {
|
||||
return JSON.parse(JSON.stringify(settings[user].subURLs[forEnumId]));
|
||||
}
|
||||
} else {
|
||||
if (settings[user].URLs) {
|
||||
return JSON.parse(JSON.stringify(settings[user].URLs));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static reorder(list, source, dest) {
|
||||
const result = Array.from(list);
|
||||
const [removed] = result.splice(source, 1);
|
||||
result.splice(dest, 0, removed);
|
||||
return result;
|
||||
};
|
||||
|
||||
static getSettings(obj, options, defaultEnabling) {
|
||||
let settings;
|
||||
const id = (obj && obj._id) || (options && options.id);
|
||||
if (obj && obj.hasOwnProperty('common')) {
|
||||
obj = obj.common;
|
||||
}
|
||||
if (obj && obj.custom) {
|
||||
settings = obj.custom || {};
|
||||
settings = settings[NAMESPACE] && settings[NAMESPACE][options.user || 'admin'] ? JSON.parse(JSON.stringify(settings[NAMESPACE][options.user || 'admin'])) : {enabled: true};
|
||||
} else {
|
||||
settings = {enabled: defaultEnabling === undefined ? true : defaultEnabling, useCustom: false};
|
||||
}
|
||||
|
||||
if (!settings.hasOwnProperty('enabled')) {
|
||||
settings.enabled = defaultEnabling === undefined ? true : defaultEnabling;
|
||||
}
|
||||
|
||||
if (false && settings.useCommon) {
|
||||
if (obj.color) settings.color = obj.color;
|
||||
if (obj.icon) settings.icon = obj.icon;
|
||||
if (obj.name) settings.name = obj.name;
|
||||
} else {
|
||||
if (options) {
|
||||
if (!settings.name && options.name) settings.name = options.name;
|
||||
if (!settings.icon && options.icon) settings.icon = options.icon;
|
||||
if (!settings.color && options.color) settings.color = options.color;
|
||||
}
|
||||
|
||||
if (obj) {
|
||||
if (!settings.color && obj.color) settings.color = obj.color;
|
||||
if (!settings.icon && obj.icon) settings.icon = obj.icon;
|
||||
if (!settings.name && obj.name) settings.name = obj.name;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof settings.name === 'object') {
|
||||
settings.name = settings.name[options.language] || settings.name.en;
|
||||
|
||||
settings.name = (settings.name || '').replace(/_/g, ' ');
|
||||
|
||||
if (settings.name === settings.name.toUpperCase()) {
|
||||
settings.name = settings.name[0] + settings.name.substring(1).toLowerCase();
|
||||
}
|
||||
}
|
||||
if (!settings.name && id) {
|
||||
let pos = id.lastIndexOf('.');
|
||||
settings.name = id.substring(pos + 1).replace(/[_.]/g, ' ');
|
||||
settings.name = (settings.name || '').replace(/_/g, ' ');
|
||||
settings.name = Utils.CapitalWords(settings.name);
|
||||
}
|
||||
|
||||
return settings;
|
||||
}
|
||||
|
||||
static setSettings(obj, settings, options) {
|
||||
if (obj) {
|
||||
obj.common = obj.common || {};
|
||||
obj.common.custom = obj.common.custom || {};
|
||||
obj.common.custom[NAMESPACE] = obj.common.custom[NAMESPACE] || {};
|
||||
obj.common.custom[NAMESPACE][options.user || 'admin'] = settings;
|
||||
const s = obj.common.custom[NAMESPACE][options.user || 'admin'];
|
||||
if (s.useCommon) {
|
||||
if (s.color !== undefined) {
|
||||
obj.common.color = s.color;
|
||||
delete s.color;
|
||||
}
|
||||
if (s.icon !== undefined) {
|
||||
obj.common.icon = s.icon;
|
||||
delete s.icon;
|
||||
}
|
||||
if (s.name !== undefined) {
|
||||
if (typeof obj.common.name !== 'object') {
|
||||
obj.common.name = {};
|
||||
obj.common.name[options.language] = s.name;
|
||||
} else{
|
||||
obj.common.name[options.language] = s.name;
|
||||
}
|
||||
delete s.name;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static getIcon(settings, style) {
|
||||
if (settings && settings.icon) {
|
||||
if (settings.icon.startsWith('data:image')) {
|
||||
return (<img alt={settings.name} src={settings.icon} style={style || {}}/>);
|
||||
} else { // may be later some changes for second type
|
||||
return (<img alt={settings.name} src={settings.icon} style={style || {}}/>);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static getObjectIcon(id, obj) {
|
||||
if (obj && obj.common && obj.common.icon) {
|
||||
let icon = obj.common.icon;
|
||||
if (icon.startsWith('data:image')) {
|
||||
return icon;
|
||||
} else {
|
||||
const parts = id.split('.');
|
||||
if (parts[0] === 'system') {
|
||||
icon = 'adapter/' + parts[2] + icon;
|
||||
} else {
|
||||
icon = 'adapter/' + parts[0] + icon;
|
||||
}
|
||||
|
||||
if (window.location.pathname.match(/material\/[.\d]+/)) {
|
||||
icon = '../../' + icon;
|
||||
} else
|
||||
if (window.location.pathname.match(/material\//)) {
|
||||
icon = '../' + icon;
|
||||
}
|
||||
return icon;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static splitCamelCase(text) {
|
||||
if (false && text !== text.toUpperCase()) {
|
||||
const words = text.split(/\s+/);
|
||||
for (let i = 0; i < words.length; i++) {
|
||||
let word = words[i];
|
||||
if (word.toLowerCase() !== word && word.toUpperCase() !== word) {
|
||||
let z = 0;
|
||||
const ww = [];
|
||||
let start = 0;
|
||||
while (z < word.length) {
|
||||
if (word[z].match(/[A-ZÜÄÖА-Я]/)) {
|
||||
ww.push(word.substring(start, z));
|
||||
start = z;
|
||||
}
|
||||
z++;
|
||||
}
|
||||
if (start !== z) {
|
||||
ww.push(word.substring(start, z));
|
||||
}
|
||||
for (let k = 0; k < ww.length; k++) {
|
||||
words.splice(i + k, 0, ww[k]);
|
||||
}
|
||||
i += ww.length;
|
||||
}
|
||||
}
|
||||
|
||||
return words.map(w => {
|
||||
w = w.trim();
|
||||
if (w) {
|
||||
return w[0].toUpperCase() + w.substring(1).toLowerCase();
|
||||
}
|
||||
return '';
|
||||
}).join(' ');
|
||||
} else {
|
||||
return Utils.CapitalWords(text);
|
||||
}
|
||||
}
|
||||
|
||||
// https://stackoverflow.com/questions/35969656/how-can-i-generate-the-opposite-color-according-to-current-color
|
||||
static isUseBright(color, defaultValue) {
|
||||
if (color === null || color === undefined || color === '') {
|
||||
return defaultValue === undefined ? true : defaultValue;
|
||||
}
|
||||
color = color.toString();
|
||||
if (color.indexOf('#') === 0) {
|
||||
color = color.slice(1);
|
||||
}
|
||||
let r;
|
||||
let g;
|
||||
let b;
|
||||
|
||||
const rgb = color.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
|
||||
if (rgb && rgb.length === 4) {
|
||||
r = parseInt(rgb[1], 10);
|
||||
g = parseInt(rgb[2], 10);
|
||||
b = parseInt(rgb[3], 10);
|
||||
} else {
|
||||
// convert 3-digit hex to 6-digits.
|
||||
if (color.length === 3) {
|
||||
color = color[0] + color[0] + color[1] + color[1] + color[2] + color[2];
|
||||
}
|
||||
if (color.length !== 6) {
|
||||
return false;
|
||||
}
|
||||
|
||||
r = parseInt(color.slice(0, 2), 16);
|
||||
g = parseInt(color.slice(2, 4), 16);
|
||||
b = parseInt(color.slice(4, 6), 16);
|
||||
}
|
||||
|
||||
|
||||
// http://stackoverflow.com/a/3943023/112731
|
||||
return (r * 0.299 + g * 0.587 + b * 0.114) <= 186;
|
||||
};
|
||||
|
||||
static getTimeString(seconds) {
|
||||
seconds = parseFloat(seconds);
|
||||
if (isNaN(seconds)) {
|
||||
return '--:--';
|
||||
}
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
let minutes = Math.floor((seconds % 3600) / 60);
|
||||
let secs = seconds % 60;
|
||||
if (hours) {
|
||||
if (minutes < 10) minutes = '0' + minutes;
|
||||
if (secs < 10) secs = '0' + secs;
|
||||
return hours + ':' + minutes + ':' + secs;
|
||||
} else {
|
||||
if (secs < 10) secs = '0' + secs;
|
||||
return minutes + ':' + secs;
|
||||
}
|
||||
}
|
||||
|
||||
static getWindDirection(angle) {
|
||||
if (angle >= 0 && angle < 11.25) {
|
||||
return 'N'
|
||||
} else if (angle >= 11.25 && angle < 33.75) {
|
||||
return 'NNE'
|
||||
} else if (angle >= 33.75 && angle < 56.25) {
|
||||
return 'NE'
|
||||
} else if (angle >= 56.25 && angle < 78.75) {
|
||||
return 'ENE'
|
||||
} else if (angle >= 78.75 && angle < 101.25) {
|
||||
return 'E'
|
||||
} else if (angle >= 101.25 && angle < 123.75) {
|
||||
return 'ESE'
|
||||
} else if (angle >= 123.75 && angle < 146.25) {
|
||||
return 'SE'
|
||||
} else if (angle >= 146.25 && angle < 168.75) {
|
||||
return 'SSE'
|
||||
} else if (angle >= 168.75 && angle < 191.25) {
|
||||
return 'S'
|
||||
} else if (angle >= 191.25 && angle < 213.75) {
|
||||
return 'SSW'
|
||||
} else if (angle >= 213.75 && angle < 236.25) {
|
||||
return 'SW'
|
||||
} else if (angle >= 236.25 && angle < 258.75) {
|
||||
return 'WSW'
|
||||
} else if (angle >= 258.75 && angle < 281.25) {
|
||||
return 'W'
|
||||
} else if (angle >= 281.25 && angle < 303.75) {
|
||||
return 'WNW'
|
||||
} else if (angle >= 303.75 && angle < 326.25) {
|
||||
return 'NW'
|
||||
} else if (angle >= 326.25 && angle < 348.75) {
|
||||
return 'NNW'
|
||||
} else if (angle >= 348.75) {
|
||||
return 'N'
|
||||
}
|
||||
}
|
||||
|
||||
static padding(num) {
|
||||
if (typeof num === 'string') {
|
||||
if (num.length < 2) {
|
||||
return '0' + num;
|
||||
} else {
|
||||
return num;
|
||||
}
|
||||
} else if (num < 10) {
|
||||
return '0' + num;
|
||||
} else {
|
||||
return num;
|
||||
}
|
||||
}
|
||||
|
||||
static setDataFormat(format) {
|
||||
if (format) {
|
||||
Utils.dateFormat = format.toUpperCase().split(/[.-/]/);
|
||||
Utils.dateFormat.splice(Utils.dateFormat.indexOf('YYYY'), 1);
|
||||
}
|
||||
}
|
||||
|
||||
static date2string(now) {
|
||||
if (typeof now === 'string') {
|
||||
now = now.trim();
|
||||
if (!now) return '';
|
||||
// only letters
|
||||
if (now.match(/^[\w\s]+$/)) {
|
||||
// Day of week
|
||||
return now;
|
||||
}
|
||||
let m = now.match(/(\d{1,4})[-./](\d{1,2})[-./](\d{1,4})/);
|
||||
if (m) {
|
||||
let a = [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)];
|
||||
let year = a.find(y => y > 31);
|
||||
a.splice(a.indexOf(year), 1);
|
||||
let day = a.find(m => m > 12);
|
||||
if (day) {
|
||||
a.splice(a.indexOf(day), 1);
|
||||
now = new Date(year, a[0] - 1, day);
|
||||
} else {
|
||||
// MM DD
|
||||
if (Utils.dateFormat[0][0] === 'M' && Utils.dateFormat[1][0] === 'D') {
|
||||
now = new Date(year, a[0] - 1, a[1]);
|
||||
if (Math.abs(now.getTime - Date.now()) > 3600000 * 24 * 10) {
|
||||
now = new Date(year, a[1] - 1, a[0]);
|
||||
}
|
||||
} else
|
||||
// DD MM
|
||||
if (Utils.dateFormat[0][0] === 'D' && Utils.dateFormat[1][0] === 'M') {
|
||||
now = new Date(year, a[1] - 1, a[0]);
|
||||
if (Math.abs(now.getTime - Date.now()) > 3600000 * 24 * 10) {
|
||||
now = new Date(year, a[0] - 1, a[1]);
|
||||
}
|
||||
} else {
|
||||
now = new Date(now);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
now = new Date(now);
|
||||
}
|
||||
} else {
|
||||
now = new Date(now);
|
||||
}
|
||||
|
||||
let date = I18n.t('dow_' + days[now.getDay()]).replace('dow_', '');
|
||||
date += '. ' + now.getDate() + ' ' + I18n.t('month_' + months[now.getMonth()]).replace('month_', '');
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
export default Utils;
|
191
src/src/UtilsColors.js
Normal file
@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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.
|
||||
**/
|
||||
|
||||
class UtilsColors {
|
||||
static hue2rgb(p, q, t) {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1/6) return p + (q - p) * 6 * t;
|
||||
if (t < 1/2) return q;
|
||||
if (t < 2/3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an HSL color value to RGB. Conversion formula
|
||||
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
|
||||
* Assumes h, s, and l are contained in the set [0, 1] and
|
||||
* returns r, g, and b in the set [0, 255].
|
||||
*
|
||||
* Taken from here: https://gist.github.com/mjackson/5311256
|
||||
*
|
||||
* @param {number} h The hue
|
||||
* @param {number} s The saturation
|
||||
* @param {number} l The lightness
|
||||
* @return {Array} The RGB representation
|
||||
*/
|
||||
static hslToRgb(h, s, l) {
|
||||
let r, g, b;
|
||||
|
||||
if (!s) {
|
||||
r = g = b = l; // achromatic
|
||||
} else {
|
||||
|
||||
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
|
||||
const p = 2 * l - q;
|
||||
|
||||
r = UtilsColors.hue2rgb(p, q, h + 1/3);
|
||||
g = UtilsColors.hue2rgb(p, q, h);
|
||||
b = UtilsColors.hue2rgb(p, q, h - 1/3);
|
||||
}
|
||||
|
||||
return [r * 255, g * 255, b * 255];
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an RGB color value to HSL. Conversion formula
|
||||
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
|
||||
* Assumes r, g, and b are contained in the set [0, 255] and
|
||||
* returns h, s, and l in the set [0, 1].
|
||||
*
|
||||
* Taken from here: https://gist.github.com/mjackson/5311256
|
||||
*
|
||||
* @param {number} r The red color value
|
||||
* @param {number} g The green color value
|
||||
* @param {number} b The blue color value
|
||||
* @return {Array} The HSL representation
|
||||
*/
|
||||
static rgbToHsl(r, g, b) {
|
||||
r /= 255;
|
||||
g /= 255;
|
||||
b /= 255;
|
||||
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
let h, s, l = (max + min) / 2;
|
||||
|
||||
if (max === min) {
|
||||
h = s = 0; // achromatic
|
||||
} else {
|
||||
let d = max - min;
|
||||
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||||
|
||||
switch (max) {
|
||||
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
|
||||
case g: h = (b - r) / d + 2; break;
|
||||
case b: h = (r - g) / d + 4; break;
|
||||
default: break;
|
||||
}
|
||||
|
||||
h /= 6;
|
||||
}
|
||||
|
||||
return [ h, s, l ];
|
||||
}
|
||||
|
||||
static limit(x) {
|
||||
if (x < 0) {
|
||||
return 0;
|
||||
} else
|
||||
if (x > 255) {
|
||||
return 255;
|
||||
} else {
|
||||
return Math.round(x);
|
||||
}
|
||||
}
|
||||
|
||||
// taken from here https://gist.github.com/paulkaplan/5184275
|
||||
static temperatureToRGB(kelvin) {
|
||||
let temp = kelvin / 100;
|
||||
let red;
|
||||
let green;
|
||||
let blue;
|
||||
|
||||
if (temp <= 66) {
|
||||
red = 255;
|
||||
green = temp;
|
||||
green = 99.4708025861 * Math.log(green) - 161.1195681661;
|
||||
|
||||
if (temp <= 19) {
|
||||
blue = 0;
|
||||
} else {
|
||||
blue = temp - 10;
|
||||
blue = 138.5177312231 * Math.log(blue) - 305.0447927307;
|
||||
}
|
||||
} else {
|
||||
red = temp - 60;
|
||||
red = 329.698727446 * Math.pow(red, -0.1332047592);
|
||||
|
||||
green = temp - 60;
|
||||
green = 288.1221695283 * Math.pow(green, -0.0755148492);
|
||||
blue = 255;
|
||||
}
|
||||
|
||||
return [
|
||||
UtilsColors.limit(red, 0, 255),
|
||||
UtilsColors.limit(green, 0, 255),
|
||||
UtilsColors.limit(blue, 0, 255)
|
||||
]
|
||||
}
|
||||
|
||||
static rgb2temperature(r, g, b) {
|
||||
let temperature;
|
||||
let testRGB;
|
||||
let epsilon = 0.4;
|
||||
let minTemperature = 2200;
|
||||
let maxTemperature = 6500;
|
||||
while (maxTemperature - minTemperature > epsilon) {
|
||||
temperature = (maxTemperature + minTemperature) / 2;
|
||||
testRGB = UtilsColors.temperatureToRGB(temperature);
|
||||
if ((testRGB.blue / testRGB.red) >= (b / r)) {
|
||||
maxTemperature = temperature;
|
||||
} else {
|
||||
minTemperature = temperature;
|
||||
}
|
||||
}
|
||||
return Math.round(temperature);
|
||||
}
|
||||
|
||||
static rgb2string(rgbArray) {
|
||||
let r = UtilsColors.limit(rgbArray[0]).toString(16);
|
||||
let g = UtilsColors.limit(rgbArray[1]).toString(16);
|
||||
let b = UtilsColors.limit(rgbArray[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;
|
||||
}
|
||||
|
||||
static hex2array(hex) {
|
||||
let r = parseInt(hex.substring(1, 3), 16);
|
||||
let g = parseInt(hex.substring(3, 5), 16);
|
||||
let b = parseInt(hex.substring(5, 7), 16);
|
||||
return [r, g, b];
|
||||
}
|
||||
|
||||
static hexToRgbA(hex, a) {
|
||||
let r = parseInt(hex.substring(1, 3), 16);
|
||||
let g = parseInt(hex.substring(3, 5), 16);
|
||||
let b = parseInt(hex.substring(5, 7), 16);
|
||||
if (a !== undefined) {
|
||||
return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
|
||||
} else {
|
||||
return 'rgb(' + r + ',' + g + ',' + b + ')';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default UtilsColors;
|
BIN
src/src/assets/apartment.jpg
Normal file
After Width: | Height: | Size: 376 KiB |
BIN
src/src/assets/colors.png
Normal file
After Width: | Height: | Size: 28 KiB |
BIN
src/src/assets/rgb.png
Normal file
After Width: | Height: | Size: 383 KiB |
BIN
src/src/assets/tempColor.png
Normal file
After Width: | Height: | Size: 45 KiB |
114
src/src/basic-controls/react-color-picker/ColorPicker.js
vendored
Normal file
@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 {ChromePicker} from 'react-color'
|
||||
import TextField from '@material-ui/core/TextField';
|
||||
import IconButton from '@material-ui/core/IconButton';
|
||||
import {MdDelete as IconDelete} from 'react-icons/md';
|
||||
|
||||
const styles = {
|
||||
color: {
|
||||
width: '36px',
|
||||
height: '14px',
|
||||
borderRadius: '2px',
|
||||
},
|
||||
delButton: {
|
||||
width: 32,
|
||||
height: 32
|
||||
},
|
||||
swatch: {
|
||||
padding: '5px',
|
||||
background: '#fff',
|
||||
borderRadius: '1px',
|
||||
boxShadow: '0 0 0 1px rgba(0,0,0,.1)',
|
||||
display: 'inline-block',
|
||||
cursor: 'pointer',
|
||||
verticalAlign: 'middle'
|
||||
},
|
||||
popover: {
|
||||
position: 'absolute',
|
||||
zIndex: '2',
|
||||
},
|
||||
cover: {
|
||||
position: 'fixed',
|
||||
top: '0px',
|
||||
right: '0px',
|
||||
bottom: '0px',
|
||||
left: '0px',
|
||||
}
|
||||
};
|
||||
|
||||
class ColorPicker extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
displayColorPicker: false,
|
||||
color: this.props.color,
|
||||
};
|
||||
}
|
||||
|
||||
handleClick = () => {
|
||||
this.setState({displayColorPicker: !this.state.displayColorPicker});
|
||||
};
|
||||
|
||||
handleClose = () => {
|
||||
this.setState({displayColorPicker: false});
|
||||
};
|
||||
|
||||
static getColor(color) {
|
||||
if (color && typeof color === 'object') {
|
||||
if (color.rgb) {
|
||||
return 'rgba(' + color.rgb.r + ',' + color.rgb.g + ',' + color.rgb.b + ',' + color.rgb.a + ')';
|
||||
} else {
|
||||
return 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')';
|
||||
}
|
||||
} else {
|
||||
return color || '';
|
||||
}
|
||||
}
|
||||
|
||||
handleChange = (color) => {
|
||||
this.setState({color});
|
||||
this.props.onChange && this.props.onChange(ColorPicker.getColor(color));
|
||||
};
|
||||
|
||||
render() {
|
||||
const color = ColorPicker.getColor(this.state.color);
|
||||
return (
|
||||
<div style={this.props.style}>
|
||||
<TextField
|
||||
id="name"
|
||||
style={{width: 'calc(100% - 80px)'}}
|
||||
label={this.props.name || 'color'}
|
||||
value={color}
|
||||
onChange={e => this.handleChange(e.target.value)}
|
||||
margin="normal"
|
||||
/>
|
||||
<IconButton onClick={() => this.handleChange('')} style={Object.assign({}, styles.delButton, color ? {} : {opacity: 0, cursor: 'default'})}><IconDelete/></IconButton>
|
||||
<div style={styles.swatch} onClick={() => this.handleClick()}>
|
||||
<div style={Object.assign({}, styles.color, {background: color})} />
|
||||
</div>
|
||||
{ this.state.displayColorPicker ? <div style={styles.popover}>
|
||||
<div style={styles.cover} onClick={() => this.handleClose()}/>
|
||||
<ChromePicker color={ this.state.color } onChangeComplete={color => this.handleChange(color)} />
|
||||
</div> : null }
|
||||
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default ColorPicker
|
106
src/src/basic-controls/react-color-saturation/ColorSaturation.js
vendored
Normal file
@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 {withStyles} from '@material-ui/core/styles';
|
||||
|
||||
import Slider from './Slider';
|
||||
|
||||
import UtilsColor from '../../UtilsColors';
|
||||
|
||||
const styles = {
|
||||
track: {
|
||||
background: 'rgba(0,0,0,0) !important',
|
||||
},
|
||||
trackBefore: {
|
||||
background: 'rgba(0,0,0,0) !important',
|
||||
},
|
||||
trackAfter: {
|
||||
background: 'rgba(0,0,0,0) !important',
|
||||
},
|
||||
thumb: {
|
||||
background: 'rgba(255,255,255,0.8)',
|
||||
borderRadius: 10,
|
||||
height: 20
|
||||
},
|
||||
div: {
|
||||
borderRadius: 15,
|
||||
paddingLeft: 5,
|
||||
paddingRight: 5,
|
||||
width: '100%',
|
||||
height: 30,
|
||||
paddingTop: 0.1,
|
||||
// boxShadow: 'rgba(255, 255, 255, 0.1) 0px 0.2em 0.1em 0.05em inset, rgba(0, 0, 0, 0.5) 0px -0.2em 0.1em 0.05em inset, rgba(0, 0, 0, 0.3) 0px 0.5em 0.65em 0px'
|
||||
}
|
||||
};
|
||||
|
||||
class ColorSaturation extends React.Component {
|
||||
static propTypes = {
|
||||
hue: PropTypes.number,
|
||||
saturation: PropTypes.number,
|
||||
onChange: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
hue: this.props.hue || 0, // 0 - 360
|
||||
saturation: this.props.saturation
|
||||
};
|
||||
}
|
||||
|
||||
componentWillReceiveProps(nextProps) {
|
||||
const newState = {};
|
||||
let changed = false;
|
||||
if (nextProps.hue !== this.state.hue) {
|
||||
newState.hue = nextProps.hue;
|
||||
changed = true;
|
||||
}
|
||||
if (nextProps.saturation !== this.state.saturation) {
|
||||
newState.saturation = nextProps.saturation;
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
this.setState(newState);
|
||||
}
|
||||
}
|
||||
|
||||
handleChange(event, value) {
|
||||
if (event) event.stopPropagation();
|
||||
this.props.onChange && this.props.onChange(value);
|
||||
this.setState({saturation: value});
|
||||
};
|
||||
|
||||
render() {
|
||||
const rgb = this.state.hue === '#FFFFFF' ? '#FFFFFF' : UtilsColor.rgb2string(UtilsColor.hslToRgb(this.state.hue / 360, 1, 0.5));
|
||||
const rgba = UtilsColor.hexToRgbA(rgb, 1);
|
||||
const color = 'linear-gradient(to right, rgba(0,0,0,1) 0%,' + rgba + ' 100%)';
|
||||
return (
|
||||
<div className={this.props.classes.div} style={{background: color}}>
|
||||
<Slider value={this.state.saturation} aria-labelledby="label" min={0} max={100}
|
||||
classes={{
|
||||
track: this.props.classes.track,
|
||||
trackBefore: this.props.classes.trackBefore,
|
||||
trackAfter: this.props.classes.trackAfter,
|
||||
thumb: this.props.classes.thumb
|
||||
}}
|
||||
onChange={this.handleChange.bind(this)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(ColorSaturation);
|
545
src/src/basic-controls/react-color-saturation/Slider.js
vendored
Normal file
@ -0,0 +1,545 @@
|
||||
import React from 'react';
|
||||
import { findDOMNode } from 'react-dom';
|
||||
import PropTypes from 'prop-types';
|
||||
import keycode from 'keycode';
|
||||
import classNames from 'classnames';
|
||||
import withStyles from '@material-ui/core/styles/withStyles';
|
||||
import ButtonBase from '@material-ui/core/ButtonBase';
|
||||
import { fade } from '@material-ui/core/styles/colorManipulator';
|
||||
import clamp from '@material-ui/lab/utils/clamp';
|
||||
|
||||
export const styles = theme => {
|
||||
const commonTransitionsOptions = {
|
||||
duration: theme.transitions.duration.short,
|
||||
easing: theme.transitions.easing.easeOut,
|
||||
};
|
||||
|
||||
const commonTransitions = theme.transitions.create(
|
||||
['width', 'height', 'left', 'top', 'box-shadow'],
|
||||
commonTransitionsOptions,
|
||||
);
|
||||
// no transition on the position
|
||||
const thumbActivatedTransitions = theme.transitions.create(
|
||||
['width', 'height', 'box-shadow'],
|
||||
commonTransitionsOptions,
|
||||
);
|
||||
|
||||
const colors = {
|
||||
primary: theme.palette.primary.main,
|
||||
disabled: theme.palette.grey[400],
|
||||
};
|
||||
|
||||
return {
|
||||
/* Styles applied to the root element. */
|
||||
root: {
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
padding: '16px 8px',
|
||||
cursor: 'pointer',
|
||||
WebkitTapHighlightColor: 'transparent',
|
||||
'&$disabled': {
|
||||
cursor: 'no-drop',
|
||||
},
|
||||
'&$vertical': {
|
||||
height: '100%',
|
||||
padding: '8px 16px',
|
||||
},
|
||||
'&$reverse': {
|
||||
transform: 'scaleX(-1)',
|
||||
},
|
||||
'&$vertical$reverse': {
|
||||
transform: 'scaleY(-1)',
|
||||
},
|
||||
},
|
||||
/* Styles applied to the container element. */
|
||||
container: {
|
||||
position: 'relative',
|
||||
'&$vertical': {
|
||||
height: '100%',
|
||||
},
|
||||
},
|
||||
/* Styles applied to the track elements. */
|
||||
track: {
|
||||
position: 'absolute',
|
||||
transform: 'translate(0, -50%)',
|
||||
top: '50%',
|
||||
height: 2,
|
||||
backgroundColor: colors.primary,
|
||||
'&$activated': {
|
||||
transition: 'none',
|
||||
},
|
||||
'&$disabled': {
|
||||
backgroundColor: colors.disabled,
|
||||
},
|
||||
'&$vertical': {
|
||||
transform: 'translate(-50%, 0)',
|
||||
left: '50%',
|
||||
top: 'initial',
|
||||
width: 2,
|
||||
},
|
||||
},
|
||||
/* Styles applied to the track element before the thumb. */
|
||||
trackBefore: {
|
||||
zIndex: 1,
|
||||
left: 0,
|
||||
transition: commonTransitions,
|
||||
},
|
||||
/* Styles applied to the track element after the thumb. */
|
||||
trackAfter: {
|
||||
right: 0,
|
||||
opacity: 0.24,
|
||||
transition: commonTransitions,
|
||||
'&$vertical': {
|
||||
bottom: 0,
|
||||
},
|
||||
},
|
||||
/* Styles applied to the thumb element. */
|
||||
thumb: {
|
||||
position: 'absolute',
|
||||
zIndex: 2,
|
||||
transform: 'translate(-50%, -50%)',
|
||||
width: 12,
|
||||
height: 12,
|
||||
borderRadius: '50%',
|
||||
transition: commonTransitions,
|
||||
backgroundColor: colors.primary,
|
||||
'&$focused': {
|
||||
boxShadow: `0px 0px 0px 9px ${fade(colors.primary, 0.16)}`,
|
||||
},
|
||||
'&$activated': {
|
||||
width: 17,
|
||||
height: 17,
|
||||
transition: thumbActivatedTransitions,
|
||||
},
|
||||
'&$disabled': {
|
||||
cursor: 'no-drop',
|
||||
width: 9,
|
||||
height: 9,
|
||||
backgroundColor: colors.disabled,
|
||||
},
|
||||
'&$jumped': {
|
||||
width: 17,
|
||||
height: 17,
|
||||
},
|
||||
},
|
||||
/* Class applied to the root element to trigger JSS nested styles if `reverse={true}` . */
|
||||
reverse: {},
|
||||
/* Class applied to the track and thumb elements to trigger JSS nested styles if `disabled`. */
|
||||
disabled: {},
|
||||
/* Class applied to the track and thumb elements to trigger JSS nested styles if `jumped`. */
|
||||
jumped: {},
|
||||
/* Class applied to the track and thumb elements to trigger JSS nested styles if `focused`. */
|
||||
focused: {},
|
||||
/* Class applied to the track and thumb elements to trigger JSS nested styles if `activated`. */
|
||||
activated: {},
|
||||
/* Class applied to the root, track and container to trigger JSS nested styles if `vertical`. */
|
||||
vertical: {},
|
||||
};
|
||||
};
|
||||
|
||||
function percentToValue(percent, min, max) {
|
||||
return ((max - min) * percent) / 100 + min;
|
||||
}
|
||||
|
||||
function roundToStep(number, step) {
|
||||
return Math.round(number / step) * step;
|
||||
}
|
||||
|
||||
function getOffset(node) {
|
||||
const { pageYOffset, pageXOffset } = global;
|
||||
const { left, top } = node.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
top: top + pageYOffset,
|
||||
left: left + pageXOffset,
|
||||
};
|
||||
}
|
||||
|
||||
function getMousePosition(event) {
|
||||
if (event.changedTouches && event.changedTouches[0]) {
|
||||
return {
|
||||
x: event.changedTouches[0].pageX,
|
||||
y: event.changedTouches[0].pageY,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
x: event.pageX,
|
||||
y: event.pageY,
|
||||
};
|
||||
}
|
||||
|
||||
function calculatePercent(node, event, isVertical, isReverted) {
|
||||
const { width, height } = node.getBoundingClientRect();
|
||||
const { top, left } = getOffset(node);
|
||||
const { x, y } = getMousePosition(event);
|
||||
|
||||
const value = isVertical ? y - top : x - left;
|
||||
const onePercent = (isVertical ? height : width) / 100;
|
||||
|
||||
return isReverted ? 100 - clamp(value / onePercent) : clamp(value / onePercent);
|
||||
}
|
||||
|
||||
function preventPageScrolling(event) {
|
||||
event.preventDefault();
|
||||
}
|
||||
|
||||
/* istanbul ignore if */
|
||||
if (process.env.NODE_ENV !== 'production' && !React.createContext) {
|
||||
throw new Error('Material-UI: react@16.3.0 or greater is required.');
|
||||
}
|
||||
|
||||
class Slider extends React.Component {
|
||||
state = { currentState: 'initial' };
|
||||
|
||||
jumpAnimationTimeoutId = -1;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.handleMouseMoveBind = this.handleMouseMove.bind(this);
|
||||
this.handleMouseUpBind = this.handleMouseUp.bind(this);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
if (this.containerRef) {
|
||||
this.containerRef.addEventListener('touchstart', preventPageScrolling, { passive: false });
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.containerRef.removeEventListener('touchstart', preventPageScrolling, { passive: false });
|
||||
document.body.removeEventListener('mousemove', this.handleMouseMoveBind);
|
||||
document.body.removeEventListener('mouseup', this.handleMouseUpBind);
|
||||
document.body.removeEventListener('touchmove', this.handleMouseMoveBind);
|
||||
document.body.removeEventListener('touchend', this.handleMouseUpBind);
|
||||
clearTimeout(this.jumpAnimationTimeoutId);
|
||||
}
|
||||
|
||||
static getDerivedStateFromProps(nextProps, prevState) {
|
||||
if (nextProps.disabled) {
|
||||
return { currentState: 'disabled' };
|
||||
}
|
||||
|
||||
if (!nextProps.disabled && prevState.currentState === 'disabled') {
|
||||
return { currentState: 'normal' };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
handleKeyDown = event => {
|
||||
const { min, max, value: currentValue } = this.props;
|
||||
|
||||
const onePercent = Math.abs((max - min) / 100);
|
||||
const step = this.props.step || onePercent;
|
||||
let value;
|
||||
|
||||
switch (keycode(event)) {
|
||||
case 'home':
|
||||
value = min;
|
||||
break;
|
||||
case 'end':
|
||||
value = max;
|
||||
break;
|
||||
case 'page up':
|
||||
value = currentValue + onePercent * 10;
|
||||
break;
|
||||
case 'page down':
|
||||
value = currentValue - onePercent * 10;
|
||||
break;
|
||||
case 'right':
|
||||
case 'up':
|
||||
value = currentValue + step;
|
||||
break;
|
||||
case 'left':
|
||||
case 'down':
|
||||
value = currentValue - step;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
value = clamp(value, min, max);
|
||||
|
||||
this.emitChange(event, value);
|
||||
};
|
||||
|
||||
handleFocus = () => {
|
||||
this.setState({ currentState: 'focused' });
|
||||
};
|
||||
|
||||
handleBlur = () => {
|
||||
this.setState({ currentState: 'normal' });
|
||||
};
|
||||
|
||||
handleClick = event => {
|
||||
const { min, max, vertical, reverse } = this.props;
|
||||
const percent = calculatePercent(this.containerRef, event, vertical, reverse);
|
||||
const value = percentToValue(percent, min, max);
|
||||
|
||||
this.emitChange(event, value, () => {
|
||||
this.playJumpAnimation();
|
||||
});
|
||||
};
|
||||
|
||||
handleTouchStart = event => {
|
||||
return this.handleMouseDown(event, true);
|
||||
};
|
||||
|
||||
handleMouseDown = (event, isTouch) => {
|
||||
event.preventDefault();
|
||||
this.setState({ currentState: 'activated' });
|
||||
this.touch = isTouch;
|
||||
this.moved = false;
|
||||
|
||||
document.body.addEventListener('mousemove', this.handleMouseMoveBind);
|
||||
document.body.addEventListener('mouseup', this.handleMouseUpBind);
|
||||
document.body.addEventListener('touchmove', this.handleMouseMoveBind);
|
||||
document.body.addEventListener('touchend', this.handleMouseUpBind);
|
||||
|
||||
if (typeof this.props.onDragStart === 'function') {
|
||||
this.props.onDragStart(event);
|
||||
}
|
||||
};
|
||||
|
||||
handleMouseUp = event => {
|
||||
this.setState({ currentState: 'normal' });
|
||||
|
||||
document.body.removeEventListener('mousemove', this.handleMouseMoveBind);
|
||||
document.body.removeEventListener('mouseup', this.handleMouseUpBind);
|
||||
document.body.removeEventListener('touchmove', this.handleMouseMoveBind);
|
||||
document.body.removeEventListener('touchend', this.handleMouseUpBind);
|
||||
|
||||
if (typeof this.props.onDragEnd === 'function') {
|
||||
this.props.onDragEnd(event);
|
||||
}
|
||||
if (this.touch && !this.moved) {
|
||||
this.handleClick(event);
|
||||
}
|
||||
};
|
||||
|
||||
handleMouseMove = event => {
|
||||
const { min, max, vertical, reverse } = this.props;
|
||||
const percent = calculatePercent(this.containerRef, event, vertical, reverse);
|
||||
const value = percentToValue(percent, min, max);
|
||||
this.moved = true;
|
||||
|
||||
this.emitChange(event, value);
|
||||
};
|
||||
|
||||
emitChange(event, rawValue, callback) {
|
||||
const { step, value: previousValue, onChange, disabled } = this.props;
|
||||
let value = rawValue;
|
||||
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (step) {
|
||||
value = roundToStep(rawValue, step);
|
||||
} else {
|
||||
value = Number(rawValue.toFixed(3));
|
||||
}
|
||||
|
||||
if (typeof onChange === 'function' && value !== previousValue) {
|
||||
onChange(event, value);
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
calculateTrackAfterStyles(percent) {
|
||||
const { currentState } = this.state;
|
||||
|
||||
switch (currentState) {
|
||||
case 'activated':
|
||||
return `calc(100% - ${percent === 0 ? 7 : 5}px)`;
|
||||
case 'disabled':
|
||||
return `calc(${100 - percent}% - 6px)`;
|
||||
default:
|
||||
return 'calc(100% - 5px)';
|
||||
}
|
||||
}
|
||||
|
||||
calculateTrackBeforeStyles(percent) {
|
||||
const { currentState } = this.state;
|
||||
|
||||
switch (currentState) {
|
||||
case 'disabled':
|
||||
return `calc(${percent}% - 6px)`;
|
||||
default:
|
||||
return `${percent}%`;
|
||||
}
|
||||
}
|
||||
|
||||
playJumpAnimation() {
|
||||
this.setState({ currentState: 'jumped' }, () => {
|
||||
clearTimeout(this.jumpAnimationTimeoutId);
|
||||
this.jumpAnimationTimeoutId = setTimeout(() => {
|
||||
this.setState({ currentState: 'normal' });
|
||||
}, this.props.theme.transitions.duration.complex);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
const { currentState } = this.state;
|
||||
const {
|
||||
component: Component,
|
||||
classes,
|
||||
className: classNameProp,
|
||||
disabled,
|
||||
max,
|
||||
min,
|
||||
reverse,
|
||||
theme,
|
||||
value,
|
||||
vertical,
|
||||
...other
|
||||
} = this.props;
|
||||
|
||||
const percent = clamp(((value - min) * 100) / (max - min));
|
||||
|
||||
const commonClasses = {
|
||||
[classes.disabled]: disabled,
|
||||
[classes.jumped]: !disabled && currentState === 'jumped',
|
||||
[classes.focused]: !disabled && currentState === 'focused',
|
||||
[classes.activated]: !disabled && currentState === 'activated',
|
||||
};
|
||||
|
||||
const className = classNames(
|
||||
classes.root,
|
||||
{
|
||||
[classes.vertical]: vertical,
|
||||
[classes.reverse]: reverse,
|
||||
[classes.disabled]: disabled,
|
||||
},
|
||||
classNameProp,
|
||||
);
|
||||
|
||||
const containerClasses = classNames(classes.container, {
|
||||
[classes.vertical]: vertical,
|
||||
});
|
||||
|
||||
const trackBeforeClasses = classNames(classes.track, classes.trackBefore, commonClasses, {
|
||||
[classes.vertical]: vertical,
|
||||
});
|
||||
|
||||
const trackAfterClasses = classNames(classes.track, classes.trackAfter, commonClasses, {
|
||||
[classes.vertical]: vertical,
|
||||
});
|
||||
|
||||
const thumbClasses = classNames(classes.thumb, commonClasses);
|
||||
|
||||
const trackProperty = vertical ? 'height' : 'width';
|
||||
const thumbProperty = vertical ? 'top' : 'left';
|
||||
const inlineTrackBeforeStyles = { [trackProperty]: this.calculateTrackBeforeStyles(percent) };
|
||||
const inlineTrackAfterStyles = { [trackProperty]: this.calculateTrackAfterStyles(percent) };
|
||||
const inlineThumbStyles = { [thumbProperty]: `${percent}%` };
|
||||
|
||||
return (
|
||||
<Component
|
||||
role="slider"
|
||||
className={className}
|
||||
aria-valuenow={value}
|
||||
aria-valuemin={min}
|
||||
aria-valuemax={max}
|
||||
aria-orientation={vertical ? 'vertical' : 'horizontal'}
|
||||
onClick={this.handleClick}
|
||||
onMouseDown={this.handleMouseDown.bind(this)}
|
||||
onTouchStart={this.handleTouchStart.bind(this)}
|
||||
ref={ref => {
|
||||
this.containerRef = findDOMNode(ref);
|
||||
}}
|
||||
{...other}
|
||||
>
|
||||
<div className={containerClasses}>
|
||||
<div className={trackBeforeClasses} style={inlineTrackBeforeStyles} />
|
||||
<ButtonBase
|
||||
className={thumbClasses}
|
||||
disableRipple
|
||||
style={inlineThumbStyles}
|
||||
onBlur={this.handleBlur}
|
||||
onKeyDown={this.handleKeyDown}
|
||||
onFocusVisible={this.handleFocus}
|
||||
/>
|
||||
<div className={trackAfterClasses} style={inlineTrackAfterStyles} />
|
||||
</div>
|
||||
</Component>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Slider.propTypes = {
|
||||
/**
|
||||
* Override or extend the styles applied to the component.
|
||||
* See [CSS API](#css-api) below for more details.
|
||||
*/
|
||||
classes: PropTypes.object.isRequired,
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
className: PropTypes.string,
|
||||
/**
|
||||
* The component used for the root node.
|
||||
* Either a string to use a DOM element or a component.
|
||||
*/
|
||||
component: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object]),
|
||||
/**
|
||||
* If `true`, the slider will be disabled.
|
||||
*/
|
||||
disabled: PropTypes.bool,
|
||||
/**
|
||||
* The maximum allowed value of the slider.
|
||||
* Should not be equal to min.
|
||||
*/
|
||||
max: PropTypes.number,
|
||||
/**
|
||||
* The minimum allowed value of the slider.
|
||||
* Should not be equal to max.
|
||||
*/
|
||||
min: PropTypes.number,
|
||||
/**
|
||||
* Callback function that is fired when the slider's value changed.
|
||||
*/
|
||||
onChange: PropTypes.func,
|
||||
/**
|
||||
* Callback function that is fired when the slide has stopped moving.
|
||||
*/
|
||||
onDragEnd: PropTypes.func,
|
||||
/**
|
||||
* Callback function that is fired when the slider has begun to move.
|
||||
*/
|
||||
onDragStart: PropTypes.func,
|
||||
/**
|
||||
* If `true`, the slider will be reversed.
|
||||
*/
|
||||
reverse: PropTypes.bool,
|
||||
/**
|
||||
* The granularity the slider can step through values.
|
||||
*/
|
||||
step: PropTypes.number,
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
theme: PropTypes.object.isRequired,
|
||||
/**
|
||||
* The value of the slider.
|
||||
*/
|
||||
value: PropTypes.number.isRequired,
|
||||
/**
|
||||
* If `true`, the slider will be vertical.
|
||||
*/
|
||||
vertical: PropTypes.bool,
|
||||
};
|
||||
|
||||
Slider.defaultProps = {
|
||||
min: 0,
|
||||
max: 100,
|
||||
component: 'div',
|
||||
};
|
||||
|
||||
export default withStyles(styles, { name: 'MuiSlider', withTheme: true })(Slider);
|
147
src/src/basic-controls/react-image-selector/ImageList.js
vendored
Normal file
@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Copyright 2018 bluefox <dogafox@gmail.com>
|
||||
*
|
||||
* 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 { withStyles } from '@material-ui/core/styles';
|
||||
import ButtonBase from '@material-ui/core/ButtonBase';
|
||||
|
||||
const styles = theme => ({
|
||||
root: {
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
minWidth: 300,
|
||||
width: '100%',
|
||||
overflowX: 'hidden',
|
||||
overflowY: 'auto',
|
||||
marginLeft: 22
|
||||
},
|
||||
image: {
|
||||
position: 'relative',
|
||||
height: 200,
|
||||
/*[theme.breakpoints.down('xs')]: {
|
||||
width: '100% !important', // Overrides inline-style
|
||||
height: 100,
|
||||
},*/
|
||||
'&:hover, &$focusVisible': {
|
||||
zIndex: 1,
|
||||
'& $imageBackdrop': {
|
||||
opacity: 0.15,
|
||||
},
|
||||
'& $imageMarked': {
|
||||
opacity: 0,
|
||||
},
|
||||
'& $imageTitle': {
|
||||
border: '4px solid currentColor',
|
||||
},
|
||||
},
|
||||
},
|
||||
focusVisible: {},
|
||||
imageButton: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: theme.palette.common.white,
|
||||
},
|
||||
imageSrc: {
|
||||
position: 'absolute',
|
||||
left: 5,
|
||||
right: 5,
|
||||
top: 5,
|
||||
bottom: 5,
|
||||
backgroundSize: 'cover',
|
||||
backgroundPosition: 'center 40%',
|
||||
color: 'white'
|
||||
},
|
||||
imageBackdrop: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: theme.palette.common.black,
|
||||
opacity: 0.4,
|
||||
transition: theme.transitions.create('opacity'),
|
||||
},
|
||||
imageTitle: {
|
||||
position: 'relative',
|
||||
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 4}px ${theme.spacing.unit + 6}px`,
|
||||
},
|
||||
imageMarked: {
|
||||
height: 3,
|
||||
width: 18,
|
||||
backgroundColor: theme.palette.common.white,
|
||||
position: 'absolute',
|
||||
bottom: -2,
|
||||
left: 'calc(50% - 9px)',
|
||||
transition: theme.transitions.create('opacity'),
|
||||
},
|
||||
});
|
||||
|
||||
class ImageList extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.classes = props.classes;
|
||||
}
|
||||
onSelect(image, i) {
|
||||
this.props.onSelect && this.props.onSelect(image);
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<div className={this.classes.root} style={this.props.maxHeight ? {maxHeight: this.props.maxHeight} : {}}>
|
||||
{this.props.images.map(function(image, i) {
|
||||
let Image;
|
||||
|
||||
if (typeof image === 'object') {
|
||||
Image = image.icon;
|
||||
}
|
||||
return (
|
||||
<ButtonBase
|
||||
tabIndex={i}
|
||||
onClick={() => this.onSelect(image, i)}
|
||||
focusRipple
|
||||
key={'images-' + i}
|
||||
className={this.classes.image}
|
||||
focusVisibleClassName={this.classes.focusVisible}
|
||||
style={{width: 64, height: 64, background: 'grey', marginRight: 2, marginBottom: 2}}
|
||||
>
|
||||
{Image ?
|
||||
(<Image className={this.classes.imageSrc} width={'calc(100% - 10px)'} height={'calc(100% - 10px)'}/>) :
|
||||
(<span className={this.classes.imageSrc} style={{backgroundImage: `url(${image})`,}}/>)
|
||||
}
|
||||
<span className={this.classes.imageBackdrop} />
|
||||
<span className={this.classes.imageButton}/>
|
||||
</ButtonBase>
|
||||
);
|
||||
}.bind(this))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
ImageList.propTypes = {
|
||||
classes: PropTypes.object.isRequired,
|
||||
images: PropTypes.array.isRequired,
|
||||
onSelect: PropTypes.func.isRequired
|
||||
};
|
||||
|
||||
export default withStyles(styles)(ImageList);
|