Compare commits

..
Author SHA1 Message Date
thomasnordquist 8edf5ad7c2 Apply automatic changes 2024-05-15 06:25:08 +00:00
thomasnordquist 51a1f5eef2 Apply automatic changes 2024-05-11 19:58:24 +00:00
Thomas Nordquist 952cb8d946 chore: update readme template 2024-05-11 21:57:26 +02:00
Thomas Nordquist c70bf7f0a2 update readme 2024-05-11 13:10:01 +02:00
Thomas Nordquist d74b4bd8ad chore: update readme 2024-05-11 13:05:53 +02:00
Thomas Nordquist dbeb3a7a18 add new version 2024-05-11 12:56:01 +02:00
Thomas Nordquist 6c6e4df164 Update links to build artifacts 2020-04-27 21:00:43 +02:00
Thomas Nordquist c23f6e2a1a Update changelog 2020-04-27 20:54:45 +02:00
Thomas Nordquist ae9724408d Update release 2020-04-27 20:51:20 +02:00
Thomas Nordquist b36d26ebc6 Merge remote-tracking branch 'origin/gh-pages' into gh-pages 2020-04-27 20:45:52 +02:00
Thomas Nordquist 6e5068207b Update dependecies 2020-01-17 12:46:17 +01:00
Thomas Nordquist aac7bf3696 Document telemetry details in issue #52 2019-07-22 16:13:56 +02:00
Thomas Nordquist a53670d368 Update Readme 2019-07-22 16:09:49 +02:00
Thomas Nordquist 737207297a Update changelog 2019-07-18 12:15:13 +02:00
Thomas Nordquist 318e604169 Update Readme 2019-07-18 01:19:48 +02:00
Thomas Nordquist 024cd2925b Update video 2019-07-17 20:32:44 +02:00
Thomas Nordquist 77c8986920 Update Readme 2019-07-17 20:31:05 +02:00
Thomas Nordquist 31a9e3f6e3 Combat form bots 2019-07-17 16:15:53 +02:00
Thomas Nordquist 5212a8330e Update readme 2019-07-17 16:15:39 +02:00
Thomas Nordquist d0a9b17b68 Add paypal.me link 2019-07-13 20:23:57 +02:00
Thomas Nordquist 4334bd9326 Add ubuntu tweer 2019-07-03 13:04:48 +02:00
Thomas Nordquist a43dc11d98 Add survey 2019-07-02 23:51:45 +02:00
Thomas Nordquist 1200b40f1b Update Readme 2019-06-21 02:10:10 +02:00
Thomas Nordquist fcda705083 Update links 2019-06-19 08:48:49 +02:00
Thomas Nordquist deea820107 Update links 2019-06-19 00:11:28 +02:00
Thomas Nordquist 427abf5647 Update screenshot 2019-06-19 00:09:54 +02:00
Thomas Nordquist 9fe9b08c55 Add version number 2019-06-18 23:53:01 +02:00
Thomas Nordquist a2c77b5d2f Update screenshot 2019-06-18 23:51:32 +02:00
Thomas Nordquist 202a04eea3 Update release 2019-06-18 23:36:49 +02:00
Thomas Nordquist d2b42293c2 Update changelog 2019-06-18 15:03:10 +02:00
Thomas Nordquist 223d4b55aa Update links 2019-05-13 12:50:52 +02:00
Thomas Nordquist b452fac4a5 Fix spacing 2019-05-07 19:34:00 +02:00
Thomas Nordquist c8a20d9d8d Update version 2019-05-07 19:31:09 +02:00
Thomas Nordquist 2126f9a00c Fix github button 2019-05-02 16:26:53 +02:00
Thomas Nordquist 9d2a2271cd Update page 2019-05-02 12:59:37 +02:00
Thomas Nordquist 4add67ec5a Update changelog 2019-04-25 00:30:25 +02:00
Thomas Nordquist 84709b29a1 Update template 2019-04-09 13:20:46 +02:00
Thomas Nordquist 1a4af8dbe5 Add OSX like frame 2019-04-09 13:17:48 +02:00
Thomas Nordquist 14fce24458 Use mp4 instaed of a gif 2019-04-09 12:33:27 +02:00
Thomas Nordquist 50d86478a0 Add jekyll local support 2019-04-09 12:33:04 +02:00
Thomas Nordquist 4ad4472dee Add mp4 video instead of gif 2019-04-09 12:18:25 +02:00
Thomas Nordquist 7687b32b44 Remove duplicate MQTT Explorer titlte 2019-04-09 12:11:55 +02:00
Thomas Nordquist 88ab41875a Update pages 2019-04-09 03:58:51 +02:00
Thomas Nordquist 48ee4dee29 Update page 2019-04-08 14:57:29 +02:00
Thomas Nordquist 3e5130b9d8 Update changelog 2019-04-08 14:42:57 +02:00
Thomas Nordquist 26ac4e0c27 Add changelog 2019-04-08 14:24:58 +02:00
Thomas Nordquist 03b304163d Fix image location 2019-04-08 14:23:42 +02:00
Thomas Nordquist 16ed84193a Initial commit 2019-04-04 20:36:35 +02:00
242 changed files with 1405 additions and 23613 deletions
-8
View File
@@ -1,8 +0,0 @@
{
"language": "en",
"words": [
"subheader",
"basepath",
"webdriverio"
]
}
-17
View File
@@ -1,17 +0,0 @@
{
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
}
}
+2 -7
View File
@@ -1,9 +1,4 @@
node_modules
backend/coverage
backend/.nyc_output
build
/dist
.DS_Store
test.dot
test.png
.awcache
.bundle
_site
-2
View File
@@ -1,2 +0,0 @@
node_modules
build
-38
View File
@@ -1,38 +0,0 @@
language: node_js
services:
- xvfb
cache:
directories:
- node_modules
- $HOME/.cache/electron
- $HOME/.cache/electron-builder
- $HOME/.npm/_prebuilds
node_js:
- "10"
os:
- linux
- osx
dist: xenial
services:
- docker
install:
- yarn install
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get update && sudo apt-get -y install snap squashfs-tools && sudo snap install snapcraft --classic; fi;
script:
- yarn run build
- yarn lint
- yarn test
- export TRAVIS_BUILD_NUMBER="" # Override travis build number since it is uses for tagging the binary version https://github.com/electron-userland/electron-builder/issues/3730
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then docker run -e GH_TOKEN=$GH_TOKEN -e GIT_TAG=$TRAVIS_TAG --rm -v `pwd`:/app thomasnordquist/ui-test-recording-env sh -c "cd app && docker/testMounted.sh"; fi
- if [[ "$TRAVIS_TAG" != "" ]]; then yarn run prepare-release; fi
- if [[ "$TRAVIS_OS_NAME" == "linux" ]] && [[ "$TRAVIS_TAG" != "" ]]; then yarn run package linux; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then yarn run package -- mac; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]] && [[ "$TRAVIS_TAG" != "" ]]; then yarn run package -- win; fi
-7
View File
@@ -1,7 +0,0 @@
{
"editor.formatOnSave": true,
"files.exclude": {
"**/node_modules": true,
"build/": true
}
}
+1
View File
@@ -0,0 +1 @@
mqtt-explorer.com
+138
View File
@@ -1,3 +1,73 @@
[back](./)
# 0.4.0-beta1
- Fix Copy & Paste
- Allow setting QoS for subscriptions
- Show Meassge ID (for QoS > 0)
- Improve JSON editor
- Allow multiple connections to the same broker from MQTT Explorer (random client ids)
- Remove recursive topic removal limit
- Retain focus on publish input fields when publishing
- Fix editor layout issue
- Fix password input
- Fix charts where json properties contain periods
- Fix publish sidebar width
- Fix plot range selection
- Update Electron
A downgrade to a version prior to 0.4.0 is due to a new configuration format not possible.
# 0.3.5
- Add keyboard support
- Navigate with arrow keys and tab return and escape
- Delete topic topics with the delete key
- Add time range options to chart panel
- Add "Clear Data" option to charts
- Add support for client certificates
- Add support for SNI (encryption-related)
- Make connection profile list scrollable
- Improve the browsability of previous messages
- various small fixes
# 0.3.2
- Ubuntu performance fix
# 0.3.1
- Ubuntu bugfix release
- Add wayland support (for snap builds)
# 0.3.0
- Add functionality to plot JSON data
- Add chart panel, containing multiple plots (bottom panel)
- Chart panel and settings will be restored on restart
- Charts can be paused
- Panels can be hidden/overlap others completely
- Plot range can be customized
- Plot interpolation can be customized
- Migrated public broker from iot.eclipse.org to mqtt.eclipse.org
- Fix unrounded time intervals in the message history
- Fix weird plot curve interpolations
# 0.2.6
- Add a pause function
- Add light / dark themes
- Add localized date formatting
- Allow pinning self-signed-certificates
- Allow copying values from the message history
- Buffer changes while in pause mode
- Improve layout
- Improve numeric plot layout and smooth curves
- Improve scroll behavior message history
- Improve performance and memory footprint by ~30%
- Improve text selection behavior (Ctrl+A) for value preview and history
- Immediately apply changed settings
- Fix memory leak on search and disconnect- Deactivate auto-update for Windows portable releases.
- Fix OSX code-signing and auto-update
# 0.2.3
- Highlight differences in the last received message with a "diff" view
@@ -9,4 +79,72 @@
- Fix bug where mqtt explorer resets the tree after a reconnect
- Fix MQTT-Client id
# 0.2.1, 0.2.2
- Release for Mac App Store
- Release for Microsoft Store
# 0.2.0
- Support multiple connection profiles
- Support custom subscriptions
- Delete Topics recursively
- Add option to disable activity indicator
- Add connection health indicator
- Remember settings after exiting the app
- Fixed ws:// connections
- Fixed exception after failed connection
- Rework topic selection indicator
- Fix scrollbar (draggable scroll handle)
- Improve look & feel
- Reduce binary size by ~60%
# 0.1.3
- Add search function
- Fix a crash on windows
- Greatly increase performance
- Show broker statistics (Settings sidebar)
- Show more content in topic preview
- Make right sidebar resizable
- Fixed minor visual imperfections.
# 0.1.0
- Improved error handling


- Fix plot
# 0.0.9
- Plot topics in a graph
- Delete retained topics with click
- Show message retention and QoS
- Set message retain and QoS
- Subscribed to broker statistics: $SYS topic
- Improved error handling


- Fixed Copy&Paste
- Crash on launch
# 0.0.7
- Fix auto-updater fallback
- Add debugging capability
- Show receive date next to message value
- Fix certificate validation switch
# 0.0.6
- Fix issue with mqtt authentication
# 0.0.5
- Fix performance bottleneck
- Fix missing icons
# 0.0.3
- Add splash screen
# 0.0.2
- Fixed bugs
- Added bugs
# 0.0.1
- Initial Release
+2
View File
@@ -0,0 +1,2 @@
source 'https://rubygems.org'
gem 'github-pages', group: :jekyll_plugins
+248
View File
@@ -0,0 +1,248 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (4.2.10)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
addressable (2.5.2)
public_suffix (>= 2.0.2, < 4.0)
coffee-script (2.4.1)
coffee-script-source
execjs
coffee-script-source (1.11.1)
colorator (1.1.0)
commonmarker (0.17.13)
ruby-enum (~> 0.5)
concurrent-ruby (1.1.5)
dnsruby (1.61.2)
addressable (~> 2.5)
em-websocket (0.5.1)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0.6.0)
ethon (0.12.0)
ffi (>= 1.3.0)
eventmachine (1.2.7)
execjs (2.7.0)
faraday (0.15.4)
multipart-post (>= 1.2, < 3)
ffi (1.10.0)
forwardable-extended (2.6.0)
gemoji (3.0.0)
github-pages (197)
activesupport (= 4.2.10)
github-pages-health-check (= 1.16.1)
jekyll (= 3.7.4)
jekyll-avatar (= 0.6.0)
jekyll-coffeescript (= 1.1.1)
jekyll-commonmark-ghpages (= 0.1.5)
jekyll-default-layout (= 0.1.4)
jekyll-feed (= 0.11.0)
jekyll-gist (= 1.5.0)
jekyll-github-metadata (= 2.12.1)
jekyll-mentions (= 1.4.1)
jekyll-optional-front-matter (= 0.3.0)
jekyll-paginate (= 1.1.0)
jekyll-readme-index (= 0.2.0)
jekyll-redirect-from (= 0.14.0)
jekyll-relative-links (= 0.6.0)
jekyll-remote-theme (= 0.3.1)
jekyll-sass-converter (= 1.5.2)
jekyll-seo-tag (= 2.5.0)
jekyll-sitemap (= 1.2.0)
jekyll-swiss (= 0.4.0)
jekyll-theme-architect (= 0.1.1)
jekyll-theme-cayman (= 0.1.1)
jekyll-theme-dinky (= 0.1.1)
jekyll-theme-hacker (= 0.1.1)
jekyll-theme-leap-day (= 0.1.1)
jekyll-theme-merlot (= 0.1.1)
jekyll-theme-midnight (= 0.1.1)
jekyll-theme-minimal (= 0.1.1)
jekyll-theme-modernist (= 0.1.1)
jekyll-theme-primer (= 0.5.3)
jekyll-theme-slate (= 0.1.1)
jekyll-theme-tactile (= 0.1.1)
jekyll-theme-time-machine (= 0.1.1)
jekyll-titles-from-headings (= 0.5.1)
jemoji (= 0.10.2)
kramdown (= 1.17.0)
liquid (= 4.0.0)
listen (= 3.1.5)
mercenary (~> 0.3)
minima (= 2.5.0)
nokogiri (>= 1.8.5, < 2.0)
rouge (= 2.2.1)
terminal-table (~> 1.4)
github-pages-health-check (1.16.1)
addressable (~> 2.3)
dnsruby (~> 1.60)
octokit (~> 4.0)
public_suffix (~> 3.0)
typhoeus (~> 1.3)
html-pipeline (2.11.0)
activesupport (>= 2)
nokogiri (>= 1.4)
http_parser.rb (0.6.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
jekyll (3.7.4)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 0.7)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
kramdown (~> 1.14)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
jekyll-avatar (0.6.0)
jekyll (~> 3.0)
jekyll-coffeescript (1.1.1)
coffee-script (~> 2.2)
coffee-script-source (~> 1.11.1)
jekyll-commonmark (1.3.1)
commonmarker (~> 0.14)
jekyll (>= 3.7, < 5.0)
jekyll-commonmark-ghpages (0.1.5)
commonmarker (~> 0.17.6)
jekyll-commonmark (~> 1)
rouge (~> 2)
jekyll-default-layout (0.1.4)
jekyll (~> 3.0)
jekyll-feed (0.11.0)
jekyll (~> 3.3)
jekyll-gist (1.5.0)
octokit (~> 4.2)
jekyll-github-metadata (2.12.1)
jekyll (~> 3.4)
octokit (~> 4.0, != 4.4.0)
jekyll-mentions (1.4.1)
html-pipeline (~> 2.3)
jekyll (~> 3.0)
jekyll-optional-front-matter (0.3.0)
jekyll (~> 3.0)
jekyll-paginate (1.1.0)
jekyll-readme-index (0.2.0)
jekyll (~> 3.0)
jekyll-redirect-from (0.14.0)
jekyll (~> 3.3)
jekyll-relative-links (0.6.0)
jekyll (~> 3.3)
jekyll-remote-theme (0.3.1)
jekyll (~> 3.5)
rubyzip (>= 1.2.1, < 3.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
jekyll-seo-tag (2.5.0)
jekyll (~> 3.3)
jekyll-sitemap (1.2.0)
jekyll (~> 3.3)
jekyll-swiss (0.4.0)
jekyll-theme-architect (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-cayman (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-dinky (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-hacker (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-leap-day (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-merlot (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-midnight (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-minimal (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-modernist (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-primer (0.5.3)
jekyll (~> 3.5)
jekyll-github-metadata (~> 2.9)
jekyll-seo-tag (~> 2.0)
jekyll-theme-slate (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-tactile (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-time-machine (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-titles-from-headings (0.5.1)
jekyll (~> 3.3)
jekyll-watch (2.2.1)
listen (~> 3.0)
jemoji (0.10.2)
gemoji (~> 3.0)
html-pipeline (~> 2.2)
jekyll (~> 3.0)
kramdown (1.17.0)
liquid (4.0.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
mercenary (0.3.6)
mini_portile2 (2.4.0)
minima (2.5.0)
jekyll (~> 3.5)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.11.3)
multipart-post (2.0.0)
nokogiri (1.10.2)
mini_portile2 (~> 2.4.0)
octokit (4.14.0)
sawyer (~> 0.8.0, >= 0.5.3)
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (3.0.3)
rb-fsevent (0.10.3)
rb-inotify (0.10.0)
ffi (~> 1.0)
rouge (2.2.1)
ruby-enum (0.7.2)
i18n
ruby_dep (1.5.0)
rubyzip (1.2.2)
safe_yaml (1.0.5)
sass (3.7.4)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sawyer (0.8.1)
addressable (>= 2.3.5, < 2.6)
faraday (~> 0.8, < 1.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thread_safe (0.3.6)
typhoeus (1.3.1)
ethon (>= 0.9.0)
tzinfo (1.2.5)
thread_safe (~> 0.1)
unicode-display_width (1.5.0)
PLATFORMS
ruby
DEPENDENCIES
github-pages
BUNDLED WITH
2.0.1
-158
View File
@@ -1,158 +0,0 @@
## creative commons
# Attribution-NoDerivatives 4.0 International
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
### Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensors permission is not necessary for any reasonfor example, because of any applicable exception or limitation to copyrightthen that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
## Creative Commons Attribution-NoDerivatives 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-NoDerivatives 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.
a. __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.
b. __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.
c. __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.
d. __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.
e. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
f. __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.
g. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
h. __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.
i. __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.
j. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
### Section 2 Scope.
a. ___License grant.___
1. 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:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce and reproduce, but not Share, Adapted Material.
2. __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.
3. __Term.__ The term of this Public License is specified in Section 6(a).
4. __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.
5. __Downstream recipients.__
A. __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.
B. __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.
6. __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).
b. ___Other rights.___
1. 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.
2. Patent and trademark rights are not licensed under this Public License.
3. 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.
### Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. ___Attribution.___
1. If You Share the Licensed Material, You must:
A. retain the following if it is supplied by the Licensor with the Licensed Material:
i. 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);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under this Public License to Share Adapted Material.
2. 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.
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
### Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
a. 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, provided You do not Share Adapted Material;
b. 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
c. 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.
a. __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.__
b. __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.__
c. 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.
a. 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.
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
2. 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.
c. 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.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
### Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
b. 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.
a. 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.
b. 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.
c. 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.
d. 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.” 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](http://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
+115 -46
View File
@@ -1,66 +1,135 @@
# [MQTT Explorer](https://mqtt-explorer.com)
[![Downloads](https://img.shields.io/github/release/thomasnordquist/mqtt-explorer.svg)](https://travis-ci.org/thomasnordquist/MQTT-Explorer/releases)
[![Downloads](https://img.shields.io/github/downloads/thomasnordquist/mqtt-explorer/total.svg)](https://travis-ci.org/thomasnordquist/MQTT-Explorer/releases)
[![Downloads](https://img.shields.io/github/release/thomasnordquist/mqtt-explorer.svg)](https://github.com/thomasnordquist/MQTT-Explorer/releases)
[![Downloads](https://img.shields.io/github/downloads/thomasnordquist/mqtt-explorer/total.svg)](https://github.com/thomasnordquist/MQTT-Explorer/releases)
[![Build_Status](https://travis-ci.org/thomasnordquist/MQTT-Explorer.svg?branch=master)](https://travis-ci.org/thomasnordquist/MQTT-Explorer)
[![Build status](https://ci.appveyor.com/api/projects/status/c35tkm29rm4m5364/branch/master?svg=true)](https://ci.appveyor.com/project/thomasnordquist/mqtt-explorer/branch/master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/47b26e03fce543ceac7914214482334a)](https://app.codacy.com/app/thomasnordquist/MQTT-Explorer?utm_source=github.com&utm_medium=referral&utm_content=thomasnordquist/MQTT-Explorer&utm_campaign=Badge_Grade_Dashboard)
<a href="#" onClick="a=window;a.location='ht'+'tps:'+'/'+'/pay'+'pal.me/'+'ThomasNordquist'"><img src="https://img.shields.io/badge/Sponsor-PayPal-Flat.svg?color=0070ba&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgICB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIKICAgIHZlcnNpb249IjEuMSIgYmFzZVByb2ZpbGU9ImZ1bGwiIHZpZXdCb3g9IjAgMCAyNCAzMiIgd2lkdGg9IjI0IiBoZWlnaHQ9IjMyIiA+CiAgICA8cGF0aCB0cmFuc2Zvcm09InNjYWxlKDIpIiBmaWxsPSIjZWE0YWFhIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik05IDJjLS45NyAwLTEuNjkuNDItMi4yIDEtLjUxLjU4LS43OC45Mi0uOCAxLS4wMi0uMDgtLjI4LS40Mi0uOC0xLS41Mi0uNTgtMS4xNy0xLTIuMi0xLTEuNjMyLjA4Ni0yLjk1NCAxLjMzMy0zIDMgMCAuNTIuMDkgMS41Mi42NyAyLjY3QzEuMjUgOC44MiAzLjAxIDEwLjYxIDYgMTNjMi45OC0yLjM5IDQuNzctNC4xNyA1LjM0LTUuMzNDMTEuOTEgNi41MSAxMiA1LjUgMTIgNWMtLjA0Ny0xLjY5LTEuMzQyLTIuOTEzLTMtM3oiPjwvcGF0aD4KPC9zdmc+Cgo=" /></a>
| | | |
|:---:|:---:|:---:|
|[![screen_composite](https://mqtt-explorer.com/img/screen-composite_small.png)](https://mqtt-explorer.com/img/screen-composite.png)|[![screen2_small](https://mqtt-explorer.com/img/screen2_small.png)](https://mqtt-explorer.com/img/screen2.png)|[![screen3_small](https://mqtt-explorer.com/img/screen3_small.png)](https://mqtt-explorer.com/img/screen3.png)|
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="2500">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<a href="./img/screen2.png"><img src="./img/screen2_small.png" /></a>
</div>
<div class="carousel-item">
<a href="./img/screen3.png"><img src="./img/screen3_small.png" /></a>
</div>
<div class="carousel-item">
<a href="./img/screen-composite.png"><img src="./img/screen-composite_small.png" /></a>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
# The App has moved to [mqtt-explorer.com](https://mqtt-explorer.com)
MQTT Explorer is a comprehensive and easy-to-use MQTT Client.
Downloads can be found at the link above.
<span class="slider">
<a href="./img/screen2.png"><img src="./img/screen2_small.png" /></a>
<a href="./img/screen3.png"><img src="./img/screen3_small.png" /></a>
<a href="./img/screen-composite.png"><img src="./img/screen-composite_small.png" /></a>
</span>
This page is dedicated to its development.
Pull-Requests and error reports are welcome.
## Version 0.4.0-beta.6
## Run from sources
MQTT Explorer is a comprehensive MQTT client that provides a structured overview of your MQTT topics and makes working with devices/services on your broker dead-simple.
```bash
yarn
yarn build
yarn start
```
### Features
## Develop
- Visualize topics and topic activity
- Delete retained topics
- Search/filter topics
- Delete topics recursively
- Diff view of current and previous received messages
- Publish topics
- Plot numeric topics
- Retain a history of each topic
- Dark/Light Themes
- ... [See Changelog to see all features](./Changelog)
Launch Application
```bash
yarn
yarn dev
```
The hierarchical view makes this tool so easy to use and differentiates the **MQTT Explorer** from other great MQTT clients like [MQTTLens](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm), [MQTTBox](http://workswithweb.com/mqttbox.html) and [MQTT.fx](https://mqttfx.jensd.de/).
This MQTT Client strives to be a MQTT swiss-army-knife, the perfect tool to integrate new services and IoT devices on your network.
The `app` directory contains all the rendering logic, the `backend` directory currently contains the models, tests, connection management, `src` contains all the electron bindings. [mqttjs](https://github.com/mqttjs/MQTT.js) is used to facilitate communication to MQTT brokers.
## Download
## Automated Tests
Developing this tool takes a lot of effort, sweat and time, please consider rating the App on the Windows or Mac app store <img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" />.
If you feel like a feature is missing or you found a bug, please leave me a [comment / issue](https://github.com/thomasnordquist/MQTT-Explorer/issues) and I'll see what I can do.
To achieve a reliable product automated tests run regularly on travis.
| Platform | | Downloads |
|:----------:|:-------------:|:------:|
| ![windows](https://user-images.githubusercontent.com/7721625/51445407-b4172080-1d04-11e9-8c70-d8413d1d6d8b.png) | **Windows** | <a href="https://www.microsoft.com/store/apps/9PP8SFM082WD?ocid=badge"><img src="https://get.microsoft.com/images/en-us%20dark.svg" width="165" /></a><br />**[portable](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer-0.4.0-beta.6.exe), [installer](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer-Setup-0.4.0-beta.6.exe)** |
| ![mac](https://user-images.githubusercontent.com/7721625/51445390-921d9e00-1d04-11e9-8339-351469ef20ae.png) | **Mac** | <a href="https://itunes.apple.com/app/apple-store/id1455214828?pt=118225860&ct=mqtt-explorer.com&mt=8"><img src="https://developer.apple.com/app-store/marketing/guidelines/images/badge-download-on-the-mac-app-store.svg" height="40"/></a><br />**[Intel](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer-0.4.0-beta.6.dmg), [ARM](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer-0.4.0-beta.6-arm64.dmg)** <br /> *[How to start untrusted apps](https://support.apple.com/guide/mac-help/open-a-mac-app-from-an-unidentified-developer-mh40616/mac)*|
| ![ubuntu](https://user-images.githubusercontent.com/7721625/51445401-a5306e00-1d04-11e9-9b9b-20e196b82142.png) | **Ubuntu**<br />*debian, mint, neon, fedora, etc...* | <a href="https://snapcraft.io/mqtt-explorer" title="Get it from the Snap Store"><img src="https://snapcraft.io/static/images/badges/en/snap-store-black.svg" width="165" /></a><br />`snap install mqtt-explorer`<br />[Ubuntu Store](snap://mqtt-explorer) |
| ![linux](https://user-images.githubusercontent.com/7721625/51445392-947ff800-1d04-11e9-8c7f-a30efb755651.png) | **Linux**<br />*almost every linux* | **[AppImage](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer-0.4.0-beta.6.AppImage), [deb](https:&#x2F;&#x2F;github.com&#x2F;thomasnordquist&#x2F;MQTT-Explorer&#x2F;releases&#x2F;download&#x2F;v0.4.0-beta.6&#x2F;MQTT-Explorer_0.4.0-beta.6_amd64.deb)**<br />*Run AppImage:<br />Make it executable and double-click it.* |
- Data model
- MQTT integration
- UI-Tests (The demo is a recorded ui test)
[More Downloads](https://github.com/thomasnordquist/MQTT-Explorer/releases)
## Run UI-tests
A [mosquitto](https://mosquitto.org/) MQTT broker is required to run the ui-tests.
## Video
Run tests with
```bash
# Run chromedriver in a separate terminal session
./node_modules/.bin/chromedriver --url-base=wd/hub --port=9515 --verbose
```
<div class="osx-frame">
<div class="titlebar">
<div class="buttons">
<div class="close"></div>
<div class="minimize"></div>
<div class="zoom"></div>
</div>
MQTT Explorer
</div>
<div class="content">
<video style="width: 100%" autoplay muted loop>
<source type="video/mp4" src="./video.mp4">
![screencast](https://user-images.githubusercontent.com/7721625/53954172-b7f4db80-40d5-11e9-852c-f8d85e511a00.gif)
</video></div>
</div>
<br>
Compile and execute tests
```bash
npm run build
node dist/src/spec/webdriverio.js
```
## Performance
## License
This MQTT Client is optimized to handle thousands of topics and at hundreds of thousands messages per minute.
![CC-BY-ND 4.0](https://img.shields.io/badge/License-CC%20BY--ND%204.0-blue.svg)
[CC-BY-ND 4.0](https://creativecommons.org/licenses/by-nd/4.0/)
Custom subscriptions can limit the amount of messages **MQTT Explorer** needs to process, subscriptions can be managed in the advanced connection settings.
In very large productive environments brokers may handle an extreme load of topics, subscribing with a wildcard topic is in this scenario not advised.
The license is a little restrictive to distributing derived work, this may change in the future if the interest arises or more people work on this project.
## IoT Applications
List of useful IoT applications using MQTT to integrate devices / services
- [Home Assistant](https://www.home-assistant.io/) - Open source home automation gateway
- [OpenHAB](https://www.openhab.org/) - Smart Home Gateway
- [Node-RED](https://nodered.org/) - Flow-based programming for the Internet of Things
- [zigbee2mqtt](https://github.com/Koenkk/zigbee2mqtt) - A ZigBee to MQTT bridge
- [Tasmota](https://github.com/arendst/Sonoff-Tasmota) - ESP8266 firmware with MQTT support
## Feedback
<form onsubmit="if(!this.elements.noshow.value){ this.action='https://docs.google.com/forms/d/e/1FAIpQLSePeIHoZxpbB_-ku4H97go8JPhfdrlxNc-nHPGQuWB6g-U3HQ/formResponse?embedded=true' }">
### What do you like?
<textarea style="width: 100%; border-radius: 5px; box-shadow: 5px 5px;" name="entry.1944371594"></textarea>
### What can be improved?
<textarea style="width: 100%; border-radius: 5px; box-shadow: 5px 5px;" name="entry.22814098"></textarea>
### Email (optional)
<span style="display: flex"><input style="padding: 8px; flex: 2; border-radius: 5px; box-shadow: 5px 5px; border: 1px solid" type="email" name="entry.2055444782" /><button type="submit" style="padding: 8px; margin-left: 16px; border: 1px solid #2879d0; border-radius: 5px; background-color: #eee; box-shadow: 5px 5px #ccc; text-align: right; color: #2879d0;">Submit</button></span>
<input class="noshow" name="noshow" value="">
</form>
<div style="text-align: center; width: 100%">
Ideas and bugs can also be reported on [github](https://github.com/thomasnordquist/MQTT-Explorer/issues).
</div>
## Telemetry
App telemetry has been removed, we rely on your bug reports to [GitHub issues](https://github.com/thomasnordquist/MQTT-Explorer/issues)
+135
View File
@@ -0,0 +1,135 @@
[![Downloads](https://img.shields.io/github/release/thomasnordquist/mqtt-explorer.svg)](https://github.com/thomasnordquist/MQTT-Explorer/releases)
[![Downloads](https://img.shields.io/github/downloads/thomasnordquist/mqtt-explorer/total.svg)](https://github.com/thomasnordquist/MQTT-Explorer/releases)
[![Build_Status](https://travis-ci.org/thomasnordquist/MQTT-Explorer.svg?branch=master)](https://travis-ci.org/thomasnordquist/MQTT-Explorer)
[![Build status](https://ci.appveyor.com/api/projects/status/c35tkm29rm4m5364/branch/master?svg=true)](https://ci.appveyor.com/project/thomasnordquist/mqtt-explorer/branch/master)
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/47b26e03fce543ceac7914214482334a)](https://app.codacy.com/app/thomasnordquist/MQTT-Explorer?utm_source=github.com&utm_medium=referral&utm_content=thomasnordquist/MQTT-Explorer&utm_campaign=Badge_Grade_Dashboard)
<a href="#" onClick="a=window;a.location='ht'+'tps:'+'/'+'/pay'+'pal.me/'+'ThomasNordquist'"><img src="https://img.shields.io/badge/Sponsor-PayPal-Flat.svg?color=0070ba&logo=data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgICB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIKICAgIHZlcnNpb249IjEuMSIgYmFzZVByb2ZpbGU9ImZ1bGwiIHZpZXdCb3g9IjAgMCAyNCAzMiIgd2lkdGg9IjI0IiBoZWlnaHQ9IjMyIiA+CiAgICA8cGF0aCB0cmFuc2Zvcm09InNjYWxlKDIpIiBmaWxsPSIjZWE0YWFhIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik05IDJjLS45NyAwLTEuNjkuNDItMi4yIDEtLjUxLjU4LS43OC45Mi0uOCAxLS4wMi0uMDgtLjI4LS40Mi0uOC0xLS41Mi0uNTgtMS4xNy0xLTIuMi0xLTEuNjMyLjA4Ni0yLjk1NCAxLjMzMy0zIDMgMCAuNTIuMDkgMS41Mi42NyAyLjY3QzEuMjUgOC44MiAzLjAxIDEwLjYxIDYgMTNjMi45OC0yLjM5IDQuNzctNC4xNyA1LjM0LTUuMzNDMTEuOTEgNi41MSAxMiA1LjUgMTIgNWMtLjA0Ny0xLjY5LTEuMzQyLTIuOTEzLTMtM3oiPjwvcGF0aD4KPC9zdmc+Cgo=" /></a>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="2500">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<a href="./img/screen2.png"><img src="./img/screen2_small.png" /></a>
</div>
<div class="carousel-item">
<a href="./img/screen3.png"><img src="./img/screen3_small.png" /></a>
</div>
<div class="carousel-item">
<a href="./img/screen-composite.png"><img src="./img/screen-composite_small.png" /></a>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<span class="slider">
<a href="./img/screen2.png"><img src="./img/screen2_small.png" /></a>
<a href="./img/screen3.png"><img src="./img/screen3_small.png" /></a>
<a href="./img/screen-composite.png"><img src="./img/screen-composite_small.png" /></a>
</span>
## Version {{ version }}
MQTT Explorer is a comprehensive MQTT client that provides a structured overview of your MQTT topics and makes working with devices/services on your broker dead-simple.
### Features
- Visualize topics and topic activity
- Delete retained topics
- Search/filter topics
- Delete topics recursively
- Diff view of current and previous received messages
- Publish topics
- Plot numeric topics
- Retain a history of each topic
- Dark/Light Themes
- ... [See Changelog to see all features](./Changelog)
The hierarchical view makes this tool so easy to use and differentiates the **MQTT Explorer** from other great MQTT clients like [MQTTLens](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm), [MQTTBox](http://workswithweb.com/mqttbox.html) and [MQTT.fx](https://mqttfx.jensd.de/).
This MQTT Client strives to be a MQTT swiss-army-knife, the perfect tool to integrate new services and IoT devices on your network.
## Download
Developing this tool takes a lot of effort, sweat and time, please consider rating the App on the Windows or Mac app store <img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" /><img src="./res/star.svg" width="16" />.
If you feel like a feature is missing or you found a bug, please leave me a [comment / issue](https://github.com/thomasnordquist/MQTT-Explorer/issues) and I'll see what I can do.
| Platform | | Downloads |
|:----------:|:-------------:|:------:|
| ![windows](https://user-images.githubusercontent.com/7721625/51445407-b4172080-1d04-11e9-8c70-d8413d1d6d8b.png) | **Windows** | <a href="https://www.microsoft.com/store/apps/9PP8SFM082WD?ocid=badge"><img src="https://get.microsoft.com/images/en-us%20dark.svg" width="165" /></a><br />**{{windowsTargets}}** |
| ![mac](https://user-images.githubusercontent.com/7721625/51445390-921d9e00-1d04-11e9-8339-351469ef20ae.png) | **Mac** | <a href="https://itunes.apple.com/app/apple-store/id1455214828?pt=118225860&ct=mqtt-explorer.com&mt=8"><img src="https://developer.apple.com/app-store/marketing/guidelines/images/badge-download-on-the-mac-app-store.svg" height="40"/></a><br />**{{macTargets}}** <br /> *[How to start untrusted apps](https://support.apple.com/guide/mac-help/open-a-mac-app-from-an-unidentified-developer-mh40616/mac)*|
| ![ubuntu](https://user-images.githubusercontent.com/7721625/51445401-a5306e00-1d04-11e9-9b9b-20e196b82142.png) | **Ubuntu**<br />*debian, mint, neon, fedora, etc...* | <a href="https://snapcraft.io/mqtt-explorer" title="Get it from the Snap Store"><img src="https://snapcraft.io/static/images/badges/en/snap-store-black.svg" width="165" /></a><br />`snap install mqtt-explorer`<br />[Ubuntu Store](snap://mqtt-explorer) |
| ![linux](https://user-images.githubusercontent.com/7721625/51445392-947ff800-1d04-11e9-8c7f-a30efb755651.png) | **Linux**<br />*almost every linux* | **{{linuxTargets}}**<br />*Run AppImage:<br />Make it executable and double-click it.* |
[More Downloads](https://github.com/thomasnordquist/MQTT-Explorer/releases)
## Video
<div class="osx-frame">
<div class="titlebar">
<div class="buttons">
<div class="close"></div>
<div class="minimize"></div>
<div class="zoom"></div>
</div>
MQTT Explorer
</div>
<div class="content">
<video style="width: 100%" autoplay muted loop>
<source type="video/mp4" src="./video.mp4">
![screencast](https://user-images.githubusercontent.com/7721625/53954172-b7f4db80-40d5-11e9-852c-f8d85e511a00.gif)
</video></div>
</div>
<br>
## Performance
This MQTT Client is optimized to handle thousands of topics and at hundreds of thousands messages per minute.
Custom subscriptions can limit the amount of messages **MQTT Explorer** needs to process, subscriptions can be managed in the advanced connection settings.
In very large productive environments brokers may handle an extreme load of topics, subscribing with a wildcard topic is in this scenario not advised.
## IoT Applications
List of useful IoT applications using MQTT to integrate devices / services
- [Home Assistant](https://www.home-assistant.io/) - Open source home automation gateway
- [OpenHAB](https://www.openhab.org/) - Smart Home Gateway
- [Node-RED](https://nodered.org/) - Flow-based programming for the Internet of Things
- [zigbee2mqtt](https://github.com/Koenkk/zigbee2mqtt) - A ZigBee to MQTT bridge
- [Tasmota](https://github.com/arendst/Sonoff-Tasmota) - ESP8266 firmware with MQTT support
## Feedback
<form onsubmit="if(!this.elements.noshow.value){ this.action='https://docs.google.com/forms/d/e/1FAIpQLSePeIHoZxpbB_-ku4H97go8JPhfdrlxNc-nHPGQuWB6g-U3HQ/formResponse?embedded=true' }">
### What do you like?
<textarea style="width: 100%; border-radius: 5px; box-shadow: 5px 5px;" name="entry.1944371594"></textarea>
### What can be improved?
<textarea style="width: 100%; border-radius: 5px; box-shadow: 5px 5px;" name="entry.22814098"></textarea>
### Email (optional)
<span style="display: flex"><input style="padding: 8px; flex: 2; border-radius: 5px; box-shadow: 5px 5px; border: 1px solid" type="email" name="entry.2055444782" /><button type="submit" style="padding: 8px; margin-left: 16px; border: 1px solid #2879d0; border-radius: 5px; background-color: #eee; box-shadow: 5px 5px #ccc; text-align: right; color: #2879d0;">Submit</button></span>
<input class="noshow" name="noshow" value="">
</form>
<div style="text-align: center; width: 100%">
Ideas and bugs can also be reported on [github](https://github.com/thomasnordquist/MQTT-Explorer/issues).
</div>
## Telemetry
App telemetry has been removed, we rely on your bug reports to [GitHub issues](https://github.com/thomasnordquist/MQTT-Explorer/issues)
+15
View File
@@ -0,0 +1,15 @@
theme: jekyll-theme-architect
title: MQTT Explorer
description: An all-round MQTT client that provides a structured topic overview
author:
name: Thomas Nordquist
picture: https://avatars1.githubusercontent.com/u/7721625?s=460&v=4
github_username: thomasnordquist
logo: https://user-images.githubusercontent.com/7721625/52227945-5280b580-28b1-11e9-804c-75a842537393.png
plugins:
- jekyll-seo-tag
google_analytics: UA-133696837-1
markdown: kramdown
kramdown:
parse_block_html: true
+192
View File
@@ -0,0 +1,192 @@
<!DOCTYPE html>
<html lang="{{ site.lang | default: "en-US" }}">
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script
src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8="
crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}" media="screen" type="text/css">
<link rel="stylesheet" href="{{ '/assets/css/print.css' | relative_url }}" media="print" type="text/css">
<link rel="stylesheet" href="./osx-frame.css">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<![endif]-->
<style>
.noshow {display: none}
@media (min-width: 768px) {
.slider {
display: flex;
}
.carousel {
display: none;
}
}
@media (max-width: 768px) {
.slider {
display: none;
}
.carousel {
display: block;
}
}
form>h3::before {
content: '' !important;
margin-left: 0 !important;
}
.carousel-control-next-icon, .carousel-control-prev-icon {
display: inline-block;
width: 32px;
height: 32px;
background-size: 70%;
background-repeat: no-repeat;
background-color: grey;
border-radius: 5px;
}
.inner img {
border-radius: 8px;
}
.slider a {
padding: 4px;
}
.carousel-item, .slider img {
box-shadow: 0px 0px 5px #6b6b6b;
}
</style>
{% seo %}
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-TRN5K6H');</script>
<!-- End Google Tag Manager -->
<script>
function trackConversion(url) {
const conversions = {
'snap://mqtt-explorer': 'snap',
'https://snapcraft.io/mqtt-explorer': 'snap',
'https://geo.itunes.apple.com/us/app/mqtt-explorer/id1455214828?mt=12&app=apps': 'Mac App Store',
'https://www.microsoft.com/store/apps/9PP8SFM082WD?ocid=badge': 'Microsoft Store',
'https://github.com/thomasnordquist/MQTT-Explorer/releases/download/': 'binary download'
}
const conversion = Object.keys(conversions).find(function(conversionUrlPrefix) { return url.startsWith(conversionUrlPrefix) })
if (conversion) {
ga('send', 'event', 'outbound', 'download', conversions[conversion], {
'transport': 'beacon',
'hitCallback': function(){ document.location = url; }
});
} else {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){ document.location = url; }
});
}
}
function didLoad() {
if (!Array.prototype.filter || !Array.prototype.find || !String.prototype.startsWith) {
return
}
Object.values(document.getElementsByTagName('a'))
.filter(function(a) { return !a.href.startsWith(a.baseURI)})
.forEach(function(a) { a.onclick = function() { trackConversion(a.href) }})
}
</script>
</head>
<body onload="didLoad()">
<header>
<div class="inner">
<a href="{{ '/' | absolute_url }}">
<h1 style="display: inline">
<img src="./icon.png" style="
height: 1em;
display: inline;
vertical-align: top;
margin-top: -0.04em;
"></img>
{{ site.title | default: site.github.repository_name }}
</h1>
</a>
<h2>{{ site.description | default: site.github.project_tagline }}</h2>
{% if site.github.is_project_page %}
<a href="{{ site.github.repository_url }}" style="box-sizing: initial" class="button"><small>View project on</small> GitHub</a>
{% endif %}
{% if site.github.is_user_page %}
<a href="{{ site.github.owner_url }}" class="button"><small>Follow me on</small> GitHub</a>
{% endif %}
</div>
</header>
<div id="content-wrapper">
<div class="inner clearfix">
<section id="main-content">
{{ content }}
</section>
<aside id="sidebar">
{% if site.show_downloads %}
<a href="{{ site.github.zip_url }}" class="button">
<small>Download</small>
.zip file
</a>
<a href="{{ site.github.tar_url }}" class="button">
<small>Download</small>
.tar.gz file
</a>
{% endif %}
{% if site.github.is_project_page %}
<h2>Author</h2>
<img src="{{ site.author.picture }}" width="200" />
<h3>{{ site.author.name }}</h3>
<p class="repo-owner"><a href="{{ site.github.owner_url }}">{{ site.github.owner_name }}</a></p>
{% endif %}
<br />
<h3>In the media</h3>
<blockquote class="twitter-tweet" data-width="200">
<p lang="en" dir="ltr">If youre seeking a comprehensive and easy to use
<a href="https://twitter.com/hashtag/MQTT?src=hash&amp;ref_src=twsrc%5Etfw">#MQTT</a> client for
<a href="https://twitter.com/hashtag/Ubuntu?src=hash&amp;ref_src=twsrc%5Etfw">#Ubuntu</a> then look no further than MQTT Explorer.
<br>
<br>snap install mqtt-explorer
<a href="https://t.co/1nd0Z8VQeR">https://t.co/1nd0Z8VQeR</a>
<a href="https://t.co/8XKenpQu0p">pic.twitter.com/8XKenpQu0p</a>
</p>
&mdash; Ubuntu (@ubuntu)
<a href="https://twitter.com/ubuntu/status/1125747632910077953?ref_src=twsrc%5Etfw">May 7, 2019</a>
</blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</aside>
</div>
</div>
{% if site.google_analytics %}
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{{ site.google_analytics }}', 'auto');
ga('send', 'pageview');
</script>
{% endif %}
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
require 'webrick'
include WEBrick
WEBrick::HTTPUtils::DefaultMimeTypes.store 'mp4', 'video/mpeg'
-181
View File
@@ -1,181 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" />
<title>MQTT Explorer</title>
<script src="./bugtracking.bundle.js"></script>
<style>
body,
html {
margin: 0;
padding: 0;
}
[tabindex] {
outline: none;
}
@keyframes updateDark {
0% {
background-color: none;
}
25% {
background-color: #3f51b5;
}
50% {
background-color: #3f51b5;
}
100% {
background-color: none;
}
}
@keyframes updateLight {
0% {
background-color: none;
color: inherit;
}
25% {
background-color: #bfc9c8;
color: #000;
}
50% {
background-color: #bfc9c8;
color: #000;
}
100% {
background-color: none;
color: inherit;
}
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-corner {
background-color: rgba(0, 0, 0, 0);
}
::-webkit-scrollbar-track {
-webkit-box-shadow: inset 0 0 6px rgba(60, 60, 60, 0.5);
background-color: rgba(140, 140, 140, 0.1);
}
::-webkit-scrollbar-thumb {
background-color: rgba(140, 140, 140, 0.8);
}
</style>
<style>
.Resizer {
background: rgba(200, 200, 200, 0);
z-index: 10;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
-moz-background-clip: padding;
-webkit-background-clip: padding;
background-clip: padding-box;
}
.Resizer:hover {
-webkit-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
}
.Resizer.horizontal {
height: 10px;
margin: -10px 0 0 0;
border-top: 5px solid rgba(255, 255, 255, 0);
border-bottom: 5px solid rgba(255, 255, 255, 0);
cursor: row-resize;
width: 100%;
}
.Resizer.horizontal::before {
content: '•••';
display: inline-block;
vertical-align: middle;
text-align: center;
width: 100%;
margin-top: -22px;
color: #aaa;
opacity: 1;
}
.Resizer.horizontal:hover {
border-top: 5px solid rgba(120, 120, 120, 0.3);
border-bottom: 5px solid rgba(120, 120, 120, 0.3);
}
.Resizer.vertical {
width: 2px;
margin: 0px -8px 0px 0px;
border-left: 4px solid rgba(128, 128, 128, 0);
border-right: 4px solid rgba(128, 128, 128, 0);
cursor: col-resize;
}
.Resizer.vertical::before {
content: '•••';
margin-left: -6px;
height: 100%;
display: inline-block;
vertical-align: middle;
text-align: center;
color: #aaa;
opacity: 1;
writing-mode: vertical-lr;
text-orientation: sideways;
}
.Resizer.vertical:hover {
border-left: 4px solid rgba(130, 130, 130, 0.3);
border-right: 4px solid rgba(140, 140, 140, 0.3);
}
.Resizer.disabled {
cursor: not-allowed;
}
.Resizer.disabled:hover {
border-color: transparent;
}
.example-enter {
opacity: 0;
}
.example-enter-active {
opacity: 1;
transition: opacity 300ms ease-in;
}
.example-exit {
opacity: 1;
}
.example-exit-active {
opacity: 0;
transition: opacity 300ms ease-in;
}
</style>
</head>
<body>
<div id="app" style="font:-webkit-control"></div>
<script>
function loadScript(path) {
var script = document.createElement('script')
script.src = path
document.head.appendChild(script)
}
document.addEventListener('DOMContentLoaded', onLoad(), false)
function onLoad() {
// <% _.forEach(htmlWebpackPlugin.files.js, function(file) { %>loadScript("<%- file %>");<% }); %>
// loadScript("<%= JSON.stringify(htmlWebpackPlugin) %>")
}
</script>
<% _.forEach(htmlWebpackPlugin.files.js, function(file) { %><script src="<%- file %>"></script
><% }); %>
</body>
</html>
-85
View File
@@ -1,85 +0,0 @@
{
"name": "mqtt-explorer-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "yarn rebuild && webpack --mode production",
"dev": "node_modules/.bin/webpack-dev-server --mode development --progress",
"rebuild": "cd node_modules/heapdump && node-gyp rebuild --target=5.0.4 --arch=x64 --dist-url=https://atom.io/download/electron || echo Could not build heapdump; cd -"
},
"author": "",
"license": "CC-BY-ND-4.0",
"dependencies": {
"@material-ui/core": "^4",
"@material-ui/icons": "^4",
"@material-ui/lab": "^4.0.0-alpha",
"@material-ui/styles": "^4",
"@types/react-transition-group": "^2.9.2",
"axios": "^0.19.0",
"brace": "^0.11.1",
"compare-versions": "^3.4.0",
"copy-text-to-clipboard": "^2.1.0",
"d3": "^5.9.2",
"d3-shape": "^1.3.5",
"diff": "^4.0.1",
"dot-prop": "^5.0.0",
"electron-telemetry": "git+https://github.com/thomasnordquist/electron-telemetry.git#dist",
"file-loader": "^4.0.0",
"get-value": "^3.0.1",
"immutable": "^4.0.0-rc.12",
"js-base64": "^2.5.1",
"json-to-ast": "^2.1.0",
"lodash.debounce": "^4.0.8",
"lodash.throttle": "^4.1.1",
"moment": "^2.24.0",
"moving-average": "^1.0.0",
"number-abbreviate": "^2.0.0",
"prismjs": "^1.15.0",
"react": "16.8",
"react-ace": "^7.0.1",
"react-dom": "^16.7.0",
"react-redux": "^7.0.3",
"react-resize-detector": "^4.1.4",
"react-split-pane": "^0.1.85",
"react-transition-group": "^4.1.1",
"react-vis": "^1.11.6",
"redux": "^4.0.1",
"redux-batched-actions": "^0.4.1",
"redux-thunk": "^2.3.0",
"sha1": "^1.1.1",
"socket.io-client": "^2.2.0",
"uuid": "^3.3.2"
},
"devDependencies": {
"@types/d3": "^5.7.2",
"@types/diff": "^4.0.1",
"@types/get-value": "^3.0.1",
"@types/node": "^12.0.4",
"@types/prismjs": "^1.9.1",
"@types/react": "^16.7.18",
"@types/react-dom": "^16.0.11",
"@types/react-redux": "^7.0.9",
"@types/react-resize-detector": "^4.0.1",
"@types/sha1": "^1.1.1",
"@types/socket.io-client": "^1.4.32",
"@types/uuid": "^3.4.4",
"@types/vis": "^4.21.9",
"awesome-typescript-loader": "^5.2.1",
"css-loader": "^3.0.0",
"hard-source-webpack-plugin": "^0.13.1",
"heapdump": "^0.3.12",
"html-webpack-plugin": "^4.0.0-beta.5",
"node-loader": "^0.6.0",
"source-map-loader": "^0.2.4",
"style-loader": "^0.23.1",
"typescript": "^3.2.2",
"webpack": "^4.28.2",
"webpack-bundle-analyzer": "^3.0.3",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.14"
},
"peerDependencies": {
"electron": "^5.0.4"
}
}
-114
View File
@@ -1,114 +0,0 @@
import { Action, ActionTypes, ChartParameters } from '../reducers/Charts'
import { AppState } from '../reducers'
import { default as persistentStorage, StorageIdentifier } from '../utils/PersistentStorage'
import { Dispatch } from 'redux'
import { showError } from './Global'
interface ConnectionViewState {
charts: Array<ChartParameters>
}
interface ConnectionViewStateDictionary {
[s: string]: ConnectionViewState
}
const connectionViewStateIdentifier: StorageIdentifier<ConnectionViewStateDictionary> = {
id: 'connection_view_state',
}
export const loadCharts = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
const connectionId = getState().connection.connectionId
if (!connectionId) {
return
}
let viewStates: ConnectionViewStateDictionary | undefined
try {
viewStates = await persistentStorage.load(connectionViewStateIdentifier)
} catch (error) {
dispatch(showError(error))
}
if (!viewStates || !viewStates[connectionId]) {
dispatch(setCharts([]))
return
}
const viewState = viewStates[connectionId]
if (viewState) {
dispatch(setCharts(viewState.charts))
}
}
export const saveCharts = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
const connectionId = getState().connection.connectionId
if (!connectionId) {
return
}
const charts = getState()
.charts.get('charts')
.toArray()
let viewStates: ConnectionViewStateDictionary | undefined
try {
viewStates = (await persistentStorage.load(connectionViewStateIdentifier)) || {}
const state: ConnectionViewState = viewStates[connectionId] || { charts: [] }
state.charts = charts
viewStates[connectionId] = state
await persistentStorage.store(connectionViewStateIdentifier, viewStates)
} catch (error) {
dispatch(showError(error))
}
}
export const addChart = (chartParameters: ChartParameters) => async (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
const chartExists = Boolean(
getState()
.charts.get('charts')
.find(chart => chart.topic === chartParameters.topic && chart.dotPath === chartParameters.dotPath)
)
if (chartExists) {
return
}
dispatch({
type: ActionTypes.CHARTS_ADD,
chart: chartParameters,
})
dispatch(saveCharts())
}
export const updateChart = (chartParameters: ChartParameters) => async (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
dispatch({
type: ActionTypes.CHARTS_UPDATE,
topic: chartParameters.topic,
dotPath: chartParameters.dotPath,
parameters: chartParameters,
})
dispatch(saveCharts())
}
export const removeChart = (chartParameters: ChartParameters) => async (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
dispatch({
chart: chartParameters,
type: ActionTypes.CHARTS_REMOVE,
})
dispatch(saveCharts())
}
export const setCharts = (charts: Array<ChartParameters>): Action => {
return {
charts,
type: ActionTypes.CHARTS_SET,
}
}
-94
View File
@@ -1,94 +0,0 @@
import * as q from '../../../backend/src/Model'
import * as url from 'url'
import { Action, ActionTypes } from '../reducers/Connection'
import { ActionTypes as SettingsActionTypes } from '../reducers/Settings'
import { AppState } from '../reducers'
import { DataSourceState, MqttOptions } from '../../../backend/src/DataSource'
import { Dispatch } from 'redux'
import { globalActions } from '.'
import { resetStore as resetTreeStore, showTree } from './Tree'
import { showError } from './Global'
import { TopicViewModel } from '../model/TopicViewModel'
import { addMqttConnectionEvent, makeConnectionStateEvent, removeConnection, rendererEvents } from '../../../events'
export const connect = (options: MqttOptions, connectionId: string) => (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
dispatch(connecting(connectionId))
rendererEvents.emit(addMqttConnectionEvent, { options, id: connectionId })
const event = makeConnectionStateEvent(connectionId)
const host = url.parse(options.url).hostname
rendererEvents.subscribe(event, dataSourceState => {
if (dataSourceState.connected) {
const didReconnect = Boolean(getState().connection.tree)
if (!didReconnect) {
const tree = new q.Tree<TopicViewModel>()
tree.updateWithConnection(rendererEvents, connectionId)
dispatch(showTree(tree))
dispatch(connected(tree, host!))
}
} else if (dataSourceState.error) {
dispatch(showError(dataSourceState.error))
dispatch(disconnect())
}
dispatch(updateHealth(dataSourceState))
})
}
const updateHealth = (dataSourceState: DataSourceState) => (dispatch: Dispatch<any>, getState: () => AppState) => {
let state
if (dataSourceState.connecting) {
state = 'connecting'
} else if (!dataSourceState.connected) {
state = 'offline'
dispatch(globalActions.showError('Disconnected from server'))
} else if (dataSourceState.connected) {
state = 'online'
} else {
state = undefined
}
dispatch({
type: ActionTypes.CONNECTION_SET_HEALTH,
health: state,
})
}
export const connected: (tree: q.Tree<TopicViewModel>, host: string) => Action = (
tree: q.Tree<TopicViewModel>,
host: string
) => ({
tree,
host,
type: ActionTypes.CONNECTION_SET_CONNECTED,
})
export const connecting: (connectionId: string) => Action = (connectionId: string) => ({
connectionId,
type: ActionTypes.CONNECTION_SET_CONNECTING,
})
export const disconnect = () => (dispatch: Dispatch<any>, getState: () => AppState) => {
const { connectionId, tree } = getState().connection
if (connectionId) {
rendererEvents.emit(removeConnection, connectionId)
rendererEvents.unsubscribeAll(makeConnectionStateEvent(connectionId))
}
tree && tree.stopUpdating()
tree && tree.destroy()
// Clear topic filter
dispatch({
topicFilter: '',
type: SettingsActionTypes.SETTINGS_FILTER_TOPICS,
})
dispatch(resetTreeStore())
dispatch({
type: ActionTypes.CONNECTION_SET_DISCONNECTED,
})
dispatch(showTree(undefined))
}
-209
View File
@@ -1,209 +0,0 @@
import { AppState } from '../reducers'
import { clearLegacyConnectionOptions, loadLegacyConnectionOptions } from '../model/LegacyConnectionSettings'
import {
ConnectionOptions,
createEmptyConnection,
makeDefaultConnections,
CertificateParameters,
} from '../model/ConnectionOptions'
import { default as persistentStorage, StorageIdentifier } from '../utils/PersistentStorage'
import { Dispatch } from 'redux'
import { showError } from './Global'
import { remote } from 'electron'
import * as fs from 'fs'
import * as path from 'path'
import { ActionTypes, Action } from '../reducers/ConnectionManager'
interface ConnectionDictionary {
[s: string]: ConnectionOptions
}
const storedConnectionsIdentifier: StorageIdentifier<ConnectionDictionary> = {
id: 'ConnectionManager_connections',
}
export const loadConnectionSettings = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
let connections
try {
await ensureConnectionsHaveBeenInitialized()
connections = await persistentStorage.load(storedConnectionsIdentifier)
} catch (error) {
dispatch(showError(error))
}
if (!connections) {
return
}
dispatch(setConnections(connections))
const firstKey = Object.keys(connections)[0]
if (firstKey) {
dispatch(selectConnection(firstKey))
}
}
export const selectCertificate = (connectionId: string) => async (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
try {
const certificate = await openCertificate()
dispatch(
updateConnection(connectionId, {
selfSignedCertificate: certificate,
})
)
} catch (error) {
dispatch(showError(error))
}
}
async function openCertificate(): Promise<CertificateParameters> {
const rejectReasons = {
noCertificateSelected: 'No certificate selected',
certificateSizeDoesNotMatch: 'Certificate size larger/smaller then expected.',
}
return new Promise((resolve, reject) => {
remote.dialog.showOpenDialog(
{ properties: ['openFile'], securityScopedBookmarks: true },
(filePaths?: Array<string>) => {
const selectedFile = filePaths && filePaths[0]
if (!selectedFile) {
reject(rejectReasons.noCertificateSelected)
return
}
fs.readFile(selectedFile, (error, data) => {
if (error) {
reject(error)
return
}
if (data.length > 16_384 || data.length < 128) {
reject(rejectReasons.certificateSizeDoesNotMatch)
return
}
resolve({
data: data.toString('base64'),
name: path.basename(selectedFile),
})
})
}
)
})
}
export const saveConnectionSettings = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
try {
console.log('store settings')
await persistentStorage.store(storedConnectionsIdentifier, getState().connectionManager.connections)
} catch (error) {
dispatch(showError(error))
}
}
export const updateConnection = (connectionId: string, changeSet: Partial<ConnectionOptions>): Action => ({
connectionId,
changeSet,
type: ActionTypes.CONNECTION_MANAGER_UPDATE_CONNECTION,
})
export const addSubscription = (subscription: string, connectionId: string): Action => ({
connectionId,
subscription,
type: ActionTypes.CONNECTION_MANAGER_ADD_SUBSCRIPTION,
})
export const deleteSubscription = (subscription: string, connectionId: string): Action => ({
connectionId,
subscription,
type: ActionTypes.CONNECTION_MANAGER_DELETE_SUBSCRIPTION,
})
export const createConnection = () => (dispatch: Dispatch<any>) => {
const newConnection = createEmptyConnection()
dispatch(addConnection(newConnection))
dispatch(selectConnection(newConnection.id))
}
export const setConnections = (connections: { [s: string]: ConnectionOptions }): Action => ({
connections,
type: ActionTypes.CONNECTION_MANAGER_SET_CONNECTIONS,
})
export const selectConnection = (connectionId: string): Action => ({
selected: connectionId,
type: ActionTypes.CONNECTION_MANAGER_SELECT_CONNECTION,
})
export const addConnection = (connection: ConnectionOptions): Action => ({
connection,
type: ActionTypes.CONNECTION_MANAGER_ADD_CONNECTION,
})
export const toggleAdvancedSettings = (): Action => ({
type: ActionTypes.CONNECTION_MANAGER_TOGGLE_ADVANCED_SETTINGS,
})
export const deleteConnection = (connectionId: string) => (dispatch: Dispatch<any>, getState: () => AppState) => {
const connectionIds = Object.keys(getState().connectionManager.connections)
const connectionIdLocation = connectionIds.indexOf(connectionId)
const remainingIds = connectionIds.filter(id => id !== connectionId)
const nextSelectedConnectionIndex = Math.min(remainingIds.length - 1, connectionIdLocation)
const nextSelectedConnection = remainingIds[nextSelectedConnectionIndex]
dispatch({
connectionId,
type: ActionTypes.CONNECTION_MANAGER_DELETE_CONNECTION,
})
if (nextSelectedConnection) {
dispatch(selectConnection(nextSelectedConnection))
}
}
async function ensureConnectionsHaveBeenInitialized() {
let connections = await persistentStorage.load(storedConnectionsIdentifier)
const requiresInitialization = !connections
if (requiresInitialization) {
const migratedConnection = loadLegacyConnectionOptions()
const defaultConnections = makeDefaultConnections()
connections = {
...migratedConnection,
...defaultConnections,
}
await persistentStorage.store(storedConnectionsIdentifier, connections)
clearLegacyConnectionOptions()
}
// Migrate connections, rewrite dictionary to "keep" it "ordered" (dictionaries do not have a guaranteed order)
const mayNeedMigrations = connections && connections['iot.eclipse.org']
if (connections && mayNeedMigrations) {
let newConnections = {}
for (const connection of Object.values(connections)) {
addMigratedConnection(newConnections, connection)
}
await persistentStorage.store(storedConnectionsIdentifier, newConnections)
}
}
function addMigratedConnection(newConnections: { [key: string]: ConnectionOptions }, connection: ConnectionOptions) {
// The host has been renamed, only change the host if it has not been changed
// Also check for ssl since SSL is not yet working
if (
connection.id === 'iot.eclipse.org' &&
connection.host === 'iot.eclipse.org' &&
connection.port === 1883 &&
!connection.encryption
) {
connection.id = 'mqtt.eclipse.org'
connection.host = 'mqtt.eclipse.org'
connection.name = 'mqtt.eclipse.org'
}
newConnections[connection.id] = connection
}
-22
View File
@@ -1,22 +0,0 @@
import { ActionTypes } from '../reducers/Global'
import { Dispatch } from 'redux'
export const showError = (error?: string) => ({
error,
type: ActionTypes.showError,
})
export const showNotification = (notification?: string) => ({
notification,
type: ActionTypes.showNotification,
})
export const didLaunch = () => ({
type: ActionTypes.didLaunch,
})
export const toggleSettingsVisibility = () => (dispatch: Dispatch<any>) => {
dispatch({
type: ActionTypes.toggleSettingsVisibility,
})
}
-57
View File
@@ -1,57 +0,0 @@
import { Action, ActionTypes } from '../reducers/Publish'
import { AppState } from '../reducers'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { Dispatch } from 'redux'
import { makePublishEvent, rendererEvents } from '../../../events'
export const setTopic = (topic?: string): Action => {
return {
topic,
type: ActionTypes.PUBLISH_SET_TOPIC,
}
}
export const setPayload = (payload?: string): Action => {
return {
payload,
type: ActionTypes.PUBLISH_SET_PAYLOAD,
}
}
export const setQoS = (qos: 0 | 1 | 2): Action => {
return {
qos,
type: ActionTypes.PUBLISH_SET_QOS,
}
}
export const setEditorMode = (editorMode: string): Action => {
return {
editorMode,
type: ActionTypes.PUBLISH_SET_EDITOR_MODE,
}
}
export const publish = (connectionId: string) => (dispatch: Dispatch<Action>, getState: () => AppState) => {
const state = getState()
const topic = state.publish.topic
if (!topic) {
return
}
const publishEvent = makePublishEvent(connectionId)
const mqttMessage = {
topic,
payload: state.publish.payload ? Base64Message.fromString(state.publish.payload) : null,
retain: state.publish.retain,
qos: state.publish.qos,
}
rendererEvents.emit(publishEvent, mqttMessage)
}
export const toggleRetain = (): Action => {
return {
type: ActionTypes.PUBLISH_TOGGLE_RETAIN,
}
}
-171
View File
@@ -1,171 +0,0 @@
import * as q from '../../../backend/src/Model'
import { ActionTypes, SettingsState, TopicOrder } from '../reducers/Settings'
import { AppState } from '../reducers'
import { autoExpandLimitSet } from '../components/SettingsDrawer/Settings'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { batchActions } from 'redux-batched-actions'
import { default as persistentStorage, StorageIdentifier } from '../utils/PersistentStorage'
import { Dispatch } from 'redux'
import { globalActions } from './'
import { showError } from './Global'
import { showTree } from './Tree'
import { TopicViewModel } from '../model/TopicViewModel'
const settingsIdentifier: StorageIdentifier<Partial<SettingsState>> = {
id: 'Settings',
}
export const loadSettings = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
try {
const settings = (await persistentStorage.load(settingsIdentifier)) || {}
dispatch({
settings: getState().settings.merge(settings),
type: ActionTypes.SETTINGS_DID_LOAD_SETTINGS,
})
} catch (error) {
dispatch(showError(error))
}
dispatch(globalActions.didLaunch())
}
export const storeSettings = () => async (dispatch: Dispatch<any>, getState: () => AppState) => {
const settings = {
...getState().settings.toJS(),
autoExpandLimit: undefined,
topicFilter: undefined,
visible: undefined,
}
try {
await persistentStorage.store(settingsIdentifier, settings)
} catch (error) {
dispatch(showError(error))
}
}
export const setAutoExpandLimit = (autoExpandLimit: number = 0) => (dispatch: Dispatch<any>) => {
dispatch({
autoExpandLimit,
type: ActionTypes.SETTINGS_SET_AUTO_EXPAND_LIMIT,
})
}
export const setTimeLocale = (timeLocale: string) => (dispatch: Dispatch<any>) => {
dispatch({
timeLocale,
type: ActionTypes.SETTINGS_SET_TIME_LOCALE,
})
dispatch(storeSettings())
}
export const selectTopicWithMouseOver = (doSelect: boolean) => (dispatch: Dispatch<any>) => {
dispatch({
selectTopicWithMouseOver: doSelect,
type: ActionTypes.SETTINGS_SET_SELECT_TOPIC_WITH_MOUSE_OVER,
})
dispatch(storeSettings())
}
export const setValueDisplayMode = (valueRendererDisplayMode: 'diff' | 'raw') => (dispatch: Dispatch<any>) => {
dispatch({
valueRendererDisplayMode,
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE,
})
dispatch(storeSettings())
}
export const toggleHighlightTopicUpdates = () => (dispatch: Dispatch<any>) => {
dispatch({
type: ActionTypes.SETTINGS_TOGGLE_HIGHLIGHT_ACTIVITY,
})
dispatch(storeSettings())
}
export const setTopicOrder = (topicOrder: TopicOrder = TopicOrder.none) => (dispatch: Dispatch<any>) => {
dispatch({
topicOrder,
type: ActionTypes.SETTINGS_SET_TOPIC_ORDER,
})
dispatch(storeSettings())
}
export const filterTopics = (filterStr: string) => (dispatch: Dispatch<any>, getState: () => AppState) => {
const { tree } = getState().connection
dispatch({
topicFilter: filterStr,
type: ActionTypes.SETTINGS_FILTER_TOPICS,
})
if (!filterStr || !tree) {
dispatch(batchActions([setAutoExpandLimit(0), showTree(tree) as any]))
return
}
const topicFilter = filterStr.toLowerCase()
const nodeFilter = (node: q.TreeNode<TopicViewModel>): boolean => {
const topicMatches =
node
.path()
.toLowerCase()
.indexOf(topicFilter) !== -1
if (topicMatches) {
return true
}
const messageMatches =
node.message &&
node.message.value &&
Base64Message.toUnicodeString(node.message.value)
.toLowerCase()
.indexOf(filterStr) !== -1
return Boolean(messageMatches)
}
const resultTree = tree
.childTopics()
.filter(nodeFilter)
.map((node: q.TreeNode<TopicViewModel>) => {
const clone = node.unconnectedClone()
q.TreeNodeFactory.insertNodeAtPosition(node.path().split('/'), clone)
return clone.firstNode()
})
.reduce((a: q.TreeNode<TopicViewModel>, b: q.TreeNode<TopicViewModel>) => {
a.updateWithNode(b)
return a
}, new q.Tree<TopicViewModel>())
const nextTree: q.Tree<TopicViewModel> = resultTree as q.Tree<TopicViewModel>
if (tree.updateSource && tree.connectionId) {
nextTree.updateWithConnection(tree.updateSource, tree.connectionId, nodeFilter)
}
dispatch(batchActions([setAutoExpandLimit(autoExpandLimitForTree(nextTree)), showTree(nextTree) as any]))
}
function autoExpandLimitForTree(tree: q.Tree<TopicViewModel>) {
if (!tree) {
return 0
}
function closestExistingLimit(i: number): number {
const sorted = autoExpandLimitSet.sort((a, b) => Math.abs(a.limit - i) - Math.abs(b.limit - i))
return sorted[0]!.limit
}
const count = tree.childTopicCount()
const calculatedLimit = Math.max(7 - Math.log(count), 0) * 2
return closestExistingLimit(calculatedLimit)
}
export const toggleTheme = () => (dispatch: Dispatch<any>, getState: () => AppState) => {
dispatch({
type:
getState().settings.get('theme') === 'light'
? ActionTypes.SETTINGS_SET_THEME_DARK
: ActionTypes.SETTINGS_SET_THEME_LIGHT,
})
dispatch(storeSettings())
}
-56
View File
@@ -1,56 +0,0 @@
import * as q from '../../../backend/src/Model'
import { ActionTypes } from '../reducers/Sidebar'
import { AppState } from '../reducers'
import { Dispatch } from 'redux'
import { makePublishEvent, rendererEvents } from '../../../events'
export const clearRetainedTopic = () => (dispatch: Dispatch<any>, getState: () => AppState) => {
const selectedTopic = getState().tree.get('selectedTopic')
if (!selectedTopic) {
return
}
dispatch(clearTopic(selectedTopic, false))
}
export const setCompareMessage = (message?: q.Message) => (dispatch: Dispatch<any>) => {
dispatch({
message,
type: ActionTypes.SIDEBAR_SET_COMPARE_MESSAGE,
})
}
export const clearTopic = (topic: q.TreeNode<any>, recursive: boolean, subtopicClearLimit = 50) => (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
const { connectionId } = getState().connection
if (!connectionId) {
return
}
const publishEvent = makePublishEvent(connectionId)
const mqttMessage = {
topic: topic.path(),
payload: null,
retain: true,
qos: 0 as 0,
}
rendererEvents.emit(publishEvent, mqttMessage)
if (recursive) {
topic
.childTopics()
.filter(topic => Boolean(topic.message && topic.message.value))
.slice(0, subtopicClearLimit)
.forEach(topic => {
const mqttMessage = {
topic: topic.path(),
payload: null,
retain: true,
qos: 0 as 0,
}
rendererEvents.emit(publishEvent, mqttMessage)
})
}
}
-114
View File
@@ -1,114 +0,0 @@
import * as q from '../../../backend/src/Model'
import { ActionTypes } from '../reducers/Tree'
import { ActionTypes as SidebarActionTypes } from '../reducers/Sidebar'
import { AnyAction, Dispatch } from 'redux'
import { AppState } from '../reducers'
import { batchActions } from 'redux-batched-actions'
import { setTopic } from './Publish'
import { TopicViewModel } from '../model/TopicViewModel'
import { globalActions } from '.'
const debounce = require('lodash.debounce')
export const selectTopic = (topic: q.TreeNode<TopicViewModel>) => (
dispatch: Dispatch<any>,
getState: () => AppState
) => {
debouncedSelectTopic(topic, dispatch, getState)
}
const debouncedSelectTopic = debounce(
(topic: q.TreeNode<TopicViewModel>, dispatch: Dispatch<any>, getState: () => AppState) => {
const previouslySelectedTopic = getState().tree.get('selectedTopic')
if (previouslySelectedTopic === topic) {
return
}
// Update publish topic
let setTopicDispatch: any | undefined
if (!getState().publish.topic) {
setTopicDispatch = setTopic(topic.path())
} else if (previouslySelectedTopic && previouslySelectedTopic.path() === getState().publish.topic) {
setTopicDispatch = setTopic(topic.path())
}
if (previouslySelectedTopic && previouslySelectedTopic.viewModel) {
previouslySelectedTopic.viewModel.setSelected(false)
}
if (topic.viewModel) {
topic.viewModel.setSelected(true)
}
const selectTreeTopicDispatch = {
selectedTopic: topic,
type: ActionTypes.TREE_SELECT_TOPIC,
}
dispatch({
type: SidebarActionTypes.SIDEBAR_SET_COMPARE_MESSAGE,
message: undefined,
})
if (setTopicDispatch) {
dispatch(batchActions([selectTreeTopicDispatch, setTopicDispatch]))
} else {
dispatch(selectTreeTopicDispatch)
}
},
70
)
function destroyUnreferencedTree(state: AppState) {
const visibleTree = state.tree.get('tree')
const connectionTree = state.connection.tree
// Stop updates of old tree
if (visibleTree && visibleTree !== connectionTree) {
console.warn('destroy')
visibleTree.stopUpdating()
visibleTree.destroy()
}
}
export const resetStore = () => (dispatch: Dispatch<any>, getState: () => AppState): AnyAction => {
destroyUnreferencedTree(getState())
return dispatch({
type: ActionTypes.TREE_RESET_STORE,
})
}
export const showTree = (tree: q.Tree<TopicViewModel> | undefined) => (
dispatch: Dispatch<any>,
getState: () => AppState
): AnyAction => {
destroyUnreferencedTree(getState())
return dispatch({
tree,
type: ActionTypes.TREE_SHOW_TREE,
})
}
export const togglePause = (tree?: q.Tree<TopicViewModel>) => (dispatch: Dispatch<any>, getState: () => AppState) => {
const paused = getState().tree.get('paused')
const tree = getState().tree.get('tree')
const changes = tree ? tree.unmergedChanges().length : 0
if (paused && changes > 0) {
dispatch(globalActions.showNotification('Applying recorded changes.'))
}
// Allow for notification to be displayed
setTimeout(() => {
tree && tree.applyUnmergedChanges()
if (paused && changes > 0) {
dispatch(globalActions.showNotification(`Sucessfully applied ${changes} changes.`))
}
}, 50)
dispatch({
type: paused ? ActionTypes.TREE_RESUME_UPDATES : ActionTypes.TREE_PAUSE_UPDATES,
})
}
-15
View File
@@ -1,15 +0,0 @@
import { ActionTypes, GlobalAction } from '../reducers/Global'
export const showUpdateNotification = (show: boolean): GlobalAction => {
return {
type: ActionTypes.showUpdateNotification,
showUpdateNotification: show,
}
}
export const showUpdateDetails = (show: boolean): GlobalAction => {
return {
type: ActionTypes.showUpdateDetails,
showUpdateDetails: show,
}
}
-21
View File
@@ -1,21 +0,0 @@
import * as chartActions from './Charts'
import * as connectionActions from './Connection'
import * as connectionManagerActions from './ConnectionManager'
import * as globalActions from './Global'
import * as publishActions from './Publish'
import * as settingsActions from './Settings'
import * as sidebarActions from './Sidebar'
import * as treeActions from './Tree'
import * as updateNotifierActions from './UpdateNotifier'
export {
settingsActions,
treeActions,
chartActions,
publishActions,
updateNotifierActions,
connectionActions,
sidebarActions,
connectionManagerActions,
globalActions,
}
-160
View File
@@ -1,160 +0,0 @@
import * as React from 'react'
import ConnectionSetup from './ConnectionSetup/ConnectionSetup'
import CssBaseline from '@material-ui/core/CssBaseline'
import ErrorBoundary from './ErrorBoundary'
import Notification from './Layout/Notification'
import TitleBar from './Layout/TitleBar'
import UpdateNotifier from './UpdateNotifier'
import { AppState } from '../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { globalActions, settingsActions } from '../actions'
import { Theme, withStyles } from '@material-ui/core/styles'
const Settings = React.lazy(() => import('./SettingsDrawer/Settings'))
const ContentView = React.lazy(() => import('./Layout/ContentView'))
interface Props {
connectionId: string
classes: any
settingsVisible: boolean
error?: string
notification?: string
actions: typeof globalActions
settingsActions: typeof settingsActions
launching: boolean
}
class App extends React.PureComponent<Props, {}> {
constructor(props: any) {
super(props)
this.state = {}
}
private renderNotification() {
const message = this.props.error || this.props.notification
const isError = message === this.props.error
if (message) {
// Guard in case someone ever calls showError with an error instead of a string
const str = typeof message === 'string' ? message : JSON.stringify(message)
return (
<Notification
message={str}
type={isError ? 'error' : 'notification'}
onClose={() => {
isError ? this.props.actions.showError(undefined) : this.props.actions.showNotification(undefined)
}}
/>
)
}
return null
}
public componentDidMount() {
this.props.settingsActions.loadSettings()
}
public render() {
const { settingsVisible } = this.props
const { content, contentShift, centerContent, paneDefaults, heightProperty } = this.props.classes
if (this.props.launching) {
return null
}
return (
<div className={centerContent}>
<CssBaseline />
<ErrorBoundary>
{this.renderNotification()}
<React.Suspense fallback={<div></div>}>
<Settings />
</React.Suspense>
<div className={centerContent}>
<div className={`${settingsVisible ? contentShift : content}`}>
<TitleBar />
</div>
<div className={settingsVisible ? contentShift : content}>
<React.Suspense fallback={<div></div>}>
<ContentView
heightProperty={heightProperty}
connectionId={this.props.connectionId}
paneDefaults={paneDefaults}
/>
</React.Suspense>
</div>
</div>
<UpdateNotifier />
<ConnectionSetup />
</ErrorBoundary>
</div>
)
}
}
const styles = (theme: Theme) => {
const drawerWidth = 300
const contentBaseStyle = {
width: '100vw',
backgroundColor: theme.palette.background.default,
}
return {
heightProperty: {
height: '100%', // 'calc(100vh - 64px) !important',
},
paneDefaults: {
backgroundColor: theme.palette.background.default,
color: theme.palette.text.primary,
display: 'block' as 'block',
height: 'calc(100vh - 64px)',
},
centerContent: {
width: '100vw',
overflow: 'hidden' as 'hidden',
},
content: {
...contentBaseStyle,
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
transform: 'translateX(0px)',
},
contentShift: {
...contentBaseStyle,
backgroundColor: theme.palette.background.default,
transition: theme.transitions.create('transform', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
transform: `translateX(${drawerWidth}px)`,
},
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(globalActions, dispatch),
settingsActions: bindActionCreators(settingsActions, dispatch),
}
}
const mapStateToProps = (state: AppState) => {
return {
settingsVisible: state.globalState.get('settingsVisible'),
connectionId: state.connection.connectionId,
error: state.globalState.get('error'),
notification: state.globalState.get('notification'),
highlightTopicUpdates: state.settings.get('highlightTopicUpdates'),
launching: state.globalState.get('launching'),
}
}
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(App)
)
-128
View File
@@ -1,128 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import Clear from '@material-ui/icons/Clear'
import CustomIconButton from '../helper/CustomIconButton'
import TopicPlot from '../TopicPlot'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../actions'
import { ChartParameters } from '../../reducers/Charts'
import { connect } from 'react-redux'
import { Paper, Theme, Typography, withStyles } from '@material-ui/core'
import { SettingsButton } from './ChartSettings/SettingsButton'
const throttle = require('lodash.throttle')
interface Props {
parameters: ChartParameters
tree?: q.Tree<any>
classes: any
actions: {
chart: typeof chartActions
}
}
function Chart(props: Props) {
if (!props.tree) {
return null
}
const { tree, parameters } = props
const initialTreeNode = tree.findNode(parameters.topic)
const [treeNode, setTreeNode] = React.useState<q.TreeNode<any> | undefined>(initialTreeNode)
usePollingToFetchTreeNode(treeNode, tree, parameters, setTreeNode)
const onRemove = React.useCallback(() => {
props.actions.chart.removeChart(props.parameters)
}, [props.parameters])
return (
<Paper style={{ padding: '8px' }}>
<div style={{ float: 'right' }}>
<SettingsButton parameters={parameters} />
<CustomIconButton tooltip="Remove chart" onClick={onRemove}>
<Clear />
</CustomIconButton>
</div>
<Typography variant="caption" className={props.classes.topic}>
{parameters.dotPath ? parameters.dotPath : ''}
</Typography>
<br />
<Typography variant="caption" className={props.classes.topic}>
{parameters.topic}
</Typography>
<br />
{treeNode ? (
<TopicPlot
interpolation={props.parameters.interpolation}
range={props.parameters.range ? [props.parameters.range.from, props.parameters.range.to] : undefined}
history={treeNode.messageHistory}
dotPath={parameters.dotPath}
/>
) : (
<span>No data</span>
)}
</Paper>
)
}
const mapStateToProps = (state: AppState) => {
return {
tree: state.connection.tree,
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
chart: bindActionCreators(chartActions, dispatch),
},
}
}
const styles = (theme: Theme) => ({
topic: {
wordBreak: 'break-all' as 'break-all',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden' as 'hidden',
textOverflow: 'ellipsis' as 'ellipsis',
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(Chart))
/**
* If a node is not available when the plot is shown, keep polling until it has been created
*/
function usePollingToFetchTreeNode(
treeNode: q.TreeNode<any> | undefined,
tree: q.Tree<any>,
parameters: ChartParameters,
setTreeNode: React.Dispatch<React.SetStateAction<q.TreeNode<any> | undefined>>
) {
const [lastUpdate, setLastUpdate] = React.useState(0)
function pollForTreeNode() {
const onUpdateCallback = throttle(() => setLastUpdate(treeNode ? treeNode.lastUpdate : 0), 300)
let intervalTimer: any
if (!treeNode) {
intervalTimer = setInterval(() => {
const node = tree.findNode(parameters.topic)
if (node) {
setTreeNode(node)
node.onMessage.subscribe(onUpdateCallback)
clearInterval(intervalTimer)
}
}, 500)
} else {
treeNode.onMessage.subscribe(onUpdateCallback)
}
return function cleanup() {
treeNode && treeNode.onMessage.unsubscribe(onUpdateCallback)
intervalTimer && clearInterval(intervalTimer)
}
}
React.useEffect(pollForTreeNode)
}
@@ -1,66 +0,0 @@
import * as React from 'react'
import { AppState } from '../../../reducers'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../../actions'
import { ChartParameters, PlotCurveTypes } from '../../../reducers/Charts'
import { connect } from 'react-redux'
import { Menu, MenuItem } from '@material-ui/core'
function chartParametersForAction(chart: ChartParameters, action: string) {
return {
topic: chart.topic,
dotPath: chart.dotPath,
interpolation: action as any,
}
}
const curves: Array<PlotCurveTypes> = ['curve', 'linear', 'step_after', 'step_before', 'cubic_basis_spline']
function InterpolationSettings(props: {
chart: ChartParameters
actions: {
chart: typeof chartActions
}
anchorEl?: Element
open: boolean
onClose: () => void
}) {
const callbacks = React.useMemo(() => {
const createCurveCallback = (curve: PlotCurveTypes) => () => {
props.actions.chart.updateChart(chartParametersForAction(props.chart, curve))
}
const callbacks: { [key: string]: () => void } = {}
for (const curve of curves) {
callbacks[curve] = createCurveCallback(curve)
}
return callbacks
}, [curves])
const menuItems = React.useMemo(() => {
return curves.map(curve => (
<MenuItem key={curve} onClick={callbacks[curve]} selected={props.chart.interpolation === curve}>
{curve.replace(/_/g, ' ')}
</MenuItem>
))
}, [curves, props.chart])
return (
<Menu id="long-menu" anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>
{menuItems}
</Menu>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
chart: bindActionCreators(chartActions, dispatch),
},
}
}
export default connect(
undefined,
mapDispatchToProps
)(InterpolationSettings)
@@ -1,78 +0,0 @@
import * as React from 'react'
import { ChartParameters } from '../../../reducers/Charts'
import { Menu, MenuItem, TextField, Typography } from '@material-ui/core'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../../actions'
function RangeSettings(props: {
actions: { chart: typeof chartActions }
chart: ChartParameters
anchorEl?: Element
open: boolean
onClose: () => void
}) {
const dismissClick = React.useCallback((e: React.MouseEvent) => e.stopPropagation(), [])
const [rangeFrom, setRangeFrom] = React.useState<string | number | undefined>(
props.chart.range && props.chart.range.from
)
const [rangeTo, setRangeTo] = React.useState<string | number | undefined>(props.chart.range && props.chart.range.to)
React.useEffect(() => {
const from = parseFloat(rangeFrom as any)
const to = parseFloat(rangeTo as any)
props.actions.chart.updateChart({
topic: props.chart.topic,
dotPath: props.chart.dotPath,
range: {
from: isNaN(from) ? undefined : from,
to: isNaN(to) ? undefined : to,
},
})
}, [rangeFrom, rangeTo])
const setFromHandler = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => setRangeFrom(e.target.value), [])
const setToHandler = React.useCallback((e: React.ChangeEvent<HTMLInputElement>) => setRangeTo(e.target.value), [])
return (
<Menu
style={{ textAlign: 'center' }}
id="long-menu"
anchorEl={props.anchorEl}
open={props.open}
onClose={props.onClose}
>
<Typography>Define custom ranges for the Y-Axis</Typography>
<div style={{ padding: '0 16px' }}>
<TextField
style={{ marginTop: '0' }}
onClick={dismissClick}
label="from"
value={rangeFrom}
onChange={setFromHandler}
margin="normal"
/>
<TextField
style={{ marginLeft: '8px', marginTop: '0' }}
onClick={dismissClick}
label="to"
value={rangeTo}
onChange={setToHandler}
margin="normal"
/>
</div>
</Menu>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
chart: bindActionCreators(chartActions, dispatch),
},
}
}
export default connect(
undefined,
mapDispatchToProps
)(RangeSettings)
@@ -1,26 +0,0 @@
import * as React from 'react'
import ChartSettings from '.'
import CustomIconButton from '../../helper/CustomIconButton'
import MoreVertIcon from '@material-ui/icons/Settings'
import { ChartParameters } from '../../../reducers/Charts'
export function SettingsButton(props: { parameters: ChartParameters }) {
const [visible, setVisible] = React.useState(false)
const settingsRef = React.useRef()
const toggleSettings = React.useCallback(() => {
setVisible(!visible)
}, [visible])
const close = React.useCallback(() => {
setVisible(false)
}, [])
return (
<span>
<ChartSettings open={visible} close={close} anchorEl={settingsRef} chart={props.parameters} />
<CustomIconButton tooltip="Chart settings" onClick={toggleSettings}>
<MoreVertIcon ref={settingsRef as any} />
</CustomIconButton>
</span>
)
}
@@ -1,51 +0,0 @@
import * as React from 'react'
import InterpolationSettings from './InterpolationSettings'
import { ChartParameters } from '../../../reducers/Charts'
import { Menu, MenuItem } from '@material-ui/core'
import RangeSettings from './RangeSettings'
function ChartSettings(props: {
open: boolean
close: () => void
chart: ChartParameters
anchorEl: React.MutableRefObject<undefined>
}) {
const [rangeVisible, setRangeVisible] = React.useState(false)
const [interpolationVisible, setInterpolationVisible] = React.useState(false)
const toggleRange = React.useCallback(() => {
if (!rangeVisible && open) {
props.close()
}
setRangeVisible(!rangeVisible)
}, [rangeVisible, open])
const toggleInterpolation = React.useCallback(() => {
if (!interpolationVisible && open) {
props.close()
}
setInterpolationVisible(!interpolationVisible)
}, [interpolationVisible, open])
return (
<span>
<Menu id="long-menu" anchorEl={props.anchorEl.current} open={props.open} onClose={props.close}>
<MenuItem key="range" onClick={toggleRange}>
Set range
</MenuItem>
<MenuItem key="interpolation" onClick={toggleInterpolation}>
Curve interpolation
</MenuItem>
</Menu>
<RangeSettings chart={props.chart} anchorEl={props.anchorEl.current} open={rangeVisible} onClose={toggleRange} />
<InterpolationSettings
chart={props.chart}
anchorEl={props.anchorEl.current}
open={interpolationVisible}
onClose={toggleInterpolation}
/>
</span>
)
}
export default ChartSettings
-106
View File
@@ -1,106 +0,0 @@
import * as React from 'react'
import Chart from './Chart'
import ShowChart from '@material-ui/icons/ShowChart'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../actions'
import { ChartParameters } from '../../reducers/Charts'
import { connect } from 'react-redux'
import { Grid, Theme, Typography, withStyles } from '@material-ui/core'
import { List } from 'immutable'
const { TransitionGroup, CSSTransition } = require('react-transition-group/esm')
interface Props {
charts: List<ChartParameters>
connectionId?: string
actions: {
chart: typeof chartActions
}
}
function spacingForChartCount(count: number): 4 | 6 | 12 {
if (count >= 5) {
return 4
} else if (count >= 2) {
return 6
} else {
return 12
}
}
function ChartPanel(props: Props) {
const chartsInView = props.charts.count()
const [spacing, setSpacing] = React.useState(spacingForChartCount(chartsInView))
React.useEffect(() => {
props.actions.chart.loadCharts()
}, [props.connectionId])
// Update spacing after animations have completed
React.useEffect(() => {
const newSpacing = spacingForChartCount(chartsInView)
if (newSpacing > spacing) {
setTimeout(() => setSpacing(newSpacing), 500)
} else {
setSpacing(newSpacing)
}
}, [chartsInView])
const charts = props.charts.map(chartParameters => (
<CSSTransition
key={`${chartParameters.topic}-${chartParameters.dotPath || ''}`}
timeout={{ enter: 500, exit: 500 }}
classNames="example"
>
<Grid item xs={spacing}>
<Chart parameters={chartParameters} />
</Grid>
</CSSTransition>
))
return (
<div style={{ width: '100%', height: '100%', padding: '8px' }}>
<Grid container spacing={1}>
<TransitionGroup component={null} className="example">
{charts}
</TransitionGroup>
{chartsInView === 0 ? <NoCharts key="noCharts" /> : null}
</Grid>
</div>
)
}
function NoCharts() {
return (
<div style={{ width: '100%', textAlign: 'center' }}>
<Typography variant="h2">No charts selected</Typography>
<Typography>Select a numeric values from the value preview.</Typography>
<Typography>
Click on <ShowChart /> to add a topic / value to this panel.
</Typography>
</div>
)
}
const mapStateToProps = (state: AppState) => {
return {
charts: state.charts.get('charts'),
connectionId: state.connection.connectionId,
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
chart: bindActionCreators(chartActions, dispatch),
},
}
}
const styles = (theme: Theme) => ({})
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(ChartPanel))
@@ -1,23 +0,0 @@
import * as React from 'react'
import Add from '@material-ui/icons/Add'
import { Fab } from '@material-ui/core'
import { Theme, withStyles } from '@material-ui/core/styles'
const styles = (theme: Theme) => ({
addButton: {
height: theme.spacing(4),
width: theme.spacing(4),
minHeight: '0',
},
addIcon: {
height: theme.spacing(2),
},
})
export const AddButton = withStyles(styles)((props: { classes: any; action: any }) => {
return (
<Fab size="small" color="secondary" aria-label="Add" className={props.classes.addButton} onClick={props.action}>
<Add className={props.classes.addIcon} />
</Fab>
)
})
@@ -1,202 +0,0 @@
import * as React from 'react'
import Add from '@material-ui/icons/Add'
import ClearAdornment from '../helper/ClearAdornment'
import Delete from '@material-ui/icons/Delete'
import Lock from '@material-ui/icons/Lock'
import Undo from '@material-ui/icons/Undo'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectionManagerActions } from '../../actions'
import { ConnectionOptions } from '../../model/ConnectionOptions'
import { Theme, withStyles } from '@material-ui/core/styles'
import {
Button,
Grid,
IconButton,
TextField,
List,
ListItem,
ListItemText,
Tooltip,
Typography,
} from '@material-ui/core'
interface Props {
connection: ConnectionOptions
classes: any
managerActions: typeof connectionManagerActions
}
interface State {
subscription: string
}
class ConnectionSettings extends React.Component<Props, State> {
constructor(props: any) {
super(props)
this.state = { subscription: '' }
}
private handleChange = (name: string) => (event: any) => {
this.props.managerActions.updateConnection(this.props.connection.id, {
[name]: event.target.value,
})
}
private renderCertificateInfo() {
if (!this.props.connection.selfSignedCertificate) {
return null
}
return (
<span>
<Tooltip title={this.props.connection.selfSignedCertificate.name}>
<Typography className={this.props.classes.certificateName}>
<ClearAdornment action={this.clearCertificate} value={this.props.connection.selfSignedCertificate.name} />
{this.props.connection.selfSignedCertificate.name}
</Typography>
</Tooltip>
</span>
)
}
private clearCertificate = () => {
this.props.managerActions.updateConnection(this.props.connection.id, {
selfSignedCertificate: undefined,
})
}
private renderSubscriptions() {
const connection = this.props.connection
return connection.subscriptions.map(subscription => (
<Subscription
deleteAction={() => this.props.managerActions.deleteSubscription(subscription, connection.id)}
subscription={subscription}
key={subscription}
/>
))
}
public render() {
const { classes } = this.props
return (
<div>
<form className={classes.container} noValidate={true} autoComplete="off">
<Grid container={true} spacing={3}>
<Grid item={true} xs={10} className={classes.gridPadding}>
<TextField
className={classes.fullWidth}
label="Subscription"
margin="normal"
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
this.setState({ subscription: event.target.value })
}
/>
</Grid>
<Grid item={true} xs={2} className={classes.gridPadding}>
<Button
className={classes.button}
color="secondary"
onClick={() =>
this.props.managerActions.addSubscription(this.state.subscription, this.props.connection.id)
}
variant="contained"
>
<Add /> Add
</Button>
</Grid>
<Grid item={true} xs={12} style={{ padding: 0 }}>
<List className={`${classes.topicList} advanced-connection-settings-topic-list`} component="nav">
<div className={classes.list}>{this.renderSubscriptions()}</div>
</List>
</Grid>
<Grid item={true} xs={7} className={classes.gridPadding}>
<TextField
className={classes.fullWidth}
label="MQTT Client ID"
margin="normal"
value={this.props.connection.clientId}
onChange={this.handleChange('clientId')}
/>
</Grid>
<Grid item={true} xs={3} className={classes.gridPadding}>
<div>
<Tooltip title="Select certificate to verify authenticity of a self-signed certificate" placement="top">
<Button
variant="contained"
className={classes.button}
onClick={() => this.props.managerActions.selectCertificate(this.props.connection.id)}
>
<Lock /> Certificate
</Button>
</Tooltip>
{this.renderCertificateInfo()}
</div>
</Grid>
<Grid item={true} xs={2} className={classes.gridPadding}>
<Button
variant="contained"
className={classes.button}
onClick={this.props.managerActions.toggleAdvancedSettings}
>
<Undo /> Back
</Button>
</Grid>
</Grid>
</form>
</div>
)
}
}
const Subscription = (props: { subscription: string; deleteAction: any }) => {
return (
<ListItem style={{ padding: '0 0 0 8px' }}>
<ListItemText>
<IconButton onClick={props.deleteAction} style={{ padding: '6px' }}>
<Delete />
</IconButton>
{props.subscription}
</ListItemText>
</ListItem>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
managerActions: bindActionCreators(connectionManagerActions, dispatch),
}
}
const styles = (theme: Theme) => ({
fullWidth: {
width: '100%',
},
gridPadding: {
padding: '0 12px !important',
},
topicList: {
height: '180px',
overflowY: 'scroll' as 'scroll',
margin: '8px 16px',
backgroundColor: theme.palette.background.default,
},
button: {
marginTop: theme.spacing(3),
float: 'right' as 'right',
},
certificateName: {
width: '100%',
height: 'calc(1em + 4px)',
overflow: 'hidden' as 'hidden',
whiteSpace: 'nowrap' as 'nowrap',
textOverflow: 'ellipsis' as 'ellipsis',
color: theme.palette.text.hint,
},
})
export default connect(
undefined,
mapDispatchToProps
)(withStyles(styles)(ConnectionSettings))
@@ -1,332 +0,0 @@
import * as React from 'react'
import Delete from '@material-ui/icons/Delete'
import Settings from '@material-ui/icons/Settings'
import PowerSettingsNew from '@material-ui/icons/PowerSettingsNew'
import Save from '@material-ui/icons/Save'
import Visibility from '@material-ui/icons/Visibility'
import VisibilityOff from '@material-ui/icons/VisibilityOff'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectionActions, connectionManagerActions } from '../../actions'
import { ConnectionOptions, toMqttConnection } from '../../model/ConnectionOptions'
import { Theme, withStyles } from '@material-ui/core/styles'
import {
Button,
FormControl,
FormControlLabel,
Grid,
IconButton,
Input,
InputAdornment,
InputLabel,
MenuItem,
Switch,
TextField,
} from '@material-ui/core'
import ConnectionHealthIndicator from '../helper/ConnectionHealthIndicator'
interface Props {
connection: ConnectionOptions
classes: { [s: string]: string }
actions: typeof connectionActions
managerActions: typeof connectionManagerActions
connected: boolean
connecting: boolean
}
const protocols = ['mqtt', 'ws']
interface State {
showPassword: boolean
}
class ConnectionSettings extends React.Component<Props, State> {
constructor(props: any) {
super(props)
this.state = {
showPassword: false,
}
}
private handleClickShowPassword = () => {
this.setState({ showPassword: !this.state.showPassword })
}
private requiresBasePath() {
return this.props.connection.protocol !== 'mqtt'
}
private renderBasePathInput() {
return (
<Grid item={true} xs={4}>
<TextField
label="Basepath"
className={this.props.classes.textField}
value={this.props.connection.basePath}
onChange={this.handleChange('basePath')}
margin="normal"
/>
</Grid>
)
}
private handleChange = (name: string) => (event: any) => {
if (!this.props.connection) {
return
}
this.updateConnection(name, event.target.value)
}
private updateConnection(name: string, value: any) {
this.props.managerActions.updateConnection(this.props.connection.id, {
[name]: value,
})
}
private renderProtocols() {
const { classes, connection } = this.props
const protocolItems = protocols.map((value: string) => (
<MenuItem key={value} value={value}>
{value}://
</MenuItem>
))
return (
<TextField
select={true}
label="Protocol"
className={classes.textField}
value={connection.protocol}
onChange={this.updateProtocol}
margin="normal"
>
{protocolItems}
</TextField>
)
}
private updateProtocol = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value
this.updateConnection('protocol', value)
if (event.target.value === 'mqtt') {
this.updateConnection('basePath', undefined)
} else {
this.updateConnection('basePath', 'ws')
}
}
private renderCertValidationSwitch() {
const { classes, connection } = this.props
const certSwitch = (
<Switch checked={connection.certValidation} onChange={this.toggleCertValidation} color="primary" />
)
return (
<div className={classes.switch}>
<FormControlLabel control={certSwitch} label="Validate certificate" labelPlacement="bottom" />
</div>
)
}
private toggleCertValidation = () => {
this.props.managerActions.updateConnection(this.props.connection.id, {
certValidation: !this.props.connection.certValidation,
})
}
private renderTlsSwitch() {
const { classes, connection } = this.props
const tlsSwitch = <Switch checked={connection.encryption} onChange={this.toggleTls} color="primary" />
return (
<div className={classes.switch}>
<FormControlLabel control={tlsSwitch} label="Encryption (tls)" labelPlacement="bottom" />
</div>
)
}
private toggleTls = () => {
this.props.managerActions.updateConnection(this.props.connection.id, {
encryption: !this.props.connection.encryption,
})
}
private renderConnectButton() {
const { classes, actions } = this.props
if (this.props.connecting) {
return (
<Button variant="contained" color="primary" className={classes.button} onClick={actions.disconnect}>
<ConnectionHealthIndicator />
&nbsp;&nbsp;Abort
</Button>
)
}
return (
<Button variant="contained" color="primary" className={classes.button} onClick={this.onClickConnect}>
<PowerSettingsNew /> Connect
</Button>
)
}
private onClickConnect = () => {
if (!this.props.connection) {
return
}
const mqttOptions = toMqttConnection(this.props.connection)
if (mqttOptions) {
this.props.actions.connect(mqttOptions, this.props.connection.id)
}
}
public render() {
const { classes, connection } = this.props
const passwordVisibilityButton = (
<InputAdornment position="end">
<IconButton aria-label="Toggle password visibility" onClick={this.handleClickShowPassword}>
{this.state.showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
)
return (
<div>
<form className={classes.container} noValidate={true} autoComplete="off">
<Grid container={true} spacing={3}>
<Grid item={true} xs={5}>
<TextField
label="Name"
className={classes.textField}
value={connection.name}
onChange={this.handleChange('name')}
margin="normal"
/>
</Grid>
<Grid item={true} xs={4}>
{this.renderCertValidationSwitch()}
</Grid>
<Grid item={true} xs={3}>
{this.renderTlsSwitch()}
</Grid>
<Grid item={true} xs={2}>
{this.renderProtocols()}
</Grid>
<Grid item={true} xs={7}>
<TextField
label="Host"
className={classes.textField}
value={connection.host}
onChange={this.handleChange('host')}
margin="normal"
/>
</Grid>
<Grid item={true} xs={3}>
<TextField
label="Port"
className={classes.textField}
value={connection.port}
onChange={this.handleChange('port')}
margin="normal"
/>
</Grid>
{this.requiresBasePath() ? this.renderBasePathInput() : null}
<Grid item={true} xs={this.requiresBasePath() ? 4 : 6}>
<TextField
label="Username"
className={classes.textField}
value={connection.username}
onChange={this.handleChange('username')}
margin="normal"
/>
</Grid>
<Grid item={true} xs={this.requiresBasePath() ? 4 : 6}>
<FormControl className={`${classes.textField} ${classes.inputFormControl}`}>
<InputLabel htmlFor="adornment-password">Password</InputLabel>
<Input
id="adornment-password"
type={this.state.showPassword ? 'text' : 'password'}
value={connection.password}
onChange={this.handleChange('password')}
endAdornment={passwordVisibilityButton}
/>
</FormControl>
</Grid>
</Grid>
<br />
<div>
<div style={{ float: 'left' }}>
<Button
variant="contained"
className={classes.button}
onClick={() => this.props.managerActions.deleteConnection(this.props.connection.id)}
>
Delete <Delete />
</Button>
<Button
variant="contained"
className={classes.button}
onClick={this.props.managerActions.toggleAdvancedSettings}
>
<Settings /> Advanced
</Button>
</div>
<div style={{ float: 'right' }}>
<Button
variant="contained"
color="secondary"
className={classes.button}
onClick={this.props.managerActions.saveConnectionSettings}
>
<Save /> Save
</Button>
{this.renderConnectButton()}
</div>
</div>
</form>
</div>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
connected: state.connection.connected,
connecting: state.connection.connecting,
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(connectionActions, dispatch),
managerActions: bindActionCreators(connectionManagerActions, dispatch),
}
}
const styles = (theme: Theme) => ({
textField: {
width: '100%',
},
switch: {
marginTop: 0,
},
button: {
margin: theme.spacing(1),
},
inputFormControl: {
marginTop: '16px',
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(ConnectionSettings))
@@ -1,133 +0,0 @@
import * as React from 'react'
import ConnectionSettings from './ConnectionSettings'
import ProfileList from './ProfileList'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectionManagerActions } from '../../actions'
import { ConnectionOptions, toMqttConnection } from '../../model/ConnectionOptions'
import { Theme, withStyles } from '@material-ui/core/styles'
import { Modal, Paper, Toolbar, Typography, Collapse } from '@material-ui/core'
import AdvancedConnectionSettings from './AdvancedConnectionSettings'
interface Props {
actions: any
classes: any
connection?: ConnectionOptions
visible: boolean
showAdvancedSettings: boolean
}
class ConnectionSetup extends React.Component<Props, {}> {
constructor(props: Props) {
super(props)
}
private renderSettings() {
const { connection, showAdvancedSettings } = this.props
if (!connection) {
return null
}
return (
<div>
<Collapse in={!showAdvancedSettings}>
<ConnectionSettings connection={connection} />
</Collapse>
<Collapse in={showAdvancedSettings}>
<AdvancedConnectionSettings connection={connection} />
</Collapse>
</div>
)
}
public componentDidMount() {
this.props.actions.loadConnectionSettings()
}
public render() {
const { classes, visible, connection } = this.props
const mqttConnection = connection && toMqttConnection(connection)
return (
<div>
<Modal open={visible} disableAutoFocus={true}>
<Paper className={classes.root}>
<div className={classes.left}>
<ProfileList />
</div>
<div className={classes.right} key={connection && connection.id}>
<Toolbar>
<Typography className={classes.title} variant="h6" color="inherit">
MQTT Connection
</Typography>
<Typography className={classes.connectionUri}>{mqttConnection && mqttConnection.url}</Typography>
</Toolbar>
{this.renderSettings()}
</div>
</Paper>
</Modal>
</div>
)
}
}
const connectionHeight = '440px'
const styles = (theme: Theme) => ({
title: {
color: theme.palette.text.primary,
whiteSpace: 'nowrap' as 'nowrap',
},
root: {
margin: `calc((100vh - ${connectionHeight}) / 2) auto 0 auto`,
minWidth: '800px',
maxWidth: '850px',
height: connectionHeight,
outline: 'none' as 'none',
display: 'flex' as 'flex',
},
left: {
borderRightStyle: 'dotted' as 'dotted',
borderRadius: `${theme.shape.borderRadius}px 0 0 ${theme.shape.borderRadius}px`,
paddingTop: theme.spacing(2),
flex: 3,
overflow: 'hidden',
backgroundColor: theme.palette.background.default,
color: theme.palette.text.primary,
},
right: {
borderRadius: `0 ${theme.shape.borderRadius}px ${theme.shape.borderRadius}px 0`,
backgroundColor: theme.palette.background.paper,
padding: theme.spacing(2),
flex: 10,
},
connectionUri: {
width: '27em',
textOverflow: 'ellipsis' as 'ellipsis',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden' as 'hidden',
color: theme.palette.text.hint,
fontSize: '0.9em',
marginLeft: theme.spacing(4),
},
})
const mapStateToProps = (state: AppState) => {
return {
visible: !state.connection.connected,
showAdvancedSettings: state.connectionManager.showAdvancedSettings,
connection: state.connectionManager.selected
? state.connectionManager.connections[state.connectionManager.selected]
: undefined,
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(connectionManagerActions, dispatch),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(ConnectionSetup))
@@ -1,120 +0,0 @@
import * as React from 'react'
import { AddButton } from './AddButton'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectionManagerActions } from '../../actions'
import { ConnectionOptions, toMqttConnection } from '../../model/ConnectionOptions'
import { Theme, withStyles } from '@material-ui/core/styles'
import { List, ListItem, ListSubheader, Typography } from '@material-ui/core'
interface Props {
classes: any
selected?: string
connections: { [s: string]: ConnectionOptions }
actions: any
}
class ProfileList extends React.Component<Props, {}> {
constructor(props: Props) {
super(props)
}
private addConnectionButton() {
return (
<span id="addProfileButton" style={{ marginRight: '12px' }}>
<AddButton action={this.props.actions.createConnection} />
</span>
)
}
public render() {
return (
<List
style={{ height: '100%' }}
component="nav"
subheader={<ListSubheader component="div">{this.addConnectionButton()}Connections</ListSubheader>}
>
<div className={this.props.classes.list}>
{Object.values(this.props.connections).map(connection => (
<ConnectionItem
connection={connection}
key={connection.id}
selected={this.props.selected === connection.id}
/>
))}
</div>
</List>
)
}
}
const styles = (theme: Theme) => ({
list: {
marginTop: theme.spacing(1),
height: `calc(100% - ${theme.spacing(6)})`,
overflowY: 'auto' as 'auto',
},
})
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(connectionManagerActions, dispatch),
}
}
interface ConnectionItemProps {
connection: ConnectionOptions
actions: any
selected: boolean
classes: any
}
const connectionItemStyle = (theme: Theme) => ({
name: {
width: '100%',
textOverflow: 'ellipsis' as 'ellipsis',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden' as 'hidden',
},
details: {
width: '100%',
textOverflow: 'ellipsis' as 'ellipsis',
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden' as 'hidden',
color: theme.palette.text.hint,
fontSize: '0.7em',
},
})
const connectionItemRenderer = withStyles(connectionItemStyle)((props: ConnectionItemProps) => {
const connection = props.connection.host && toMqttConnection(props.connection)
return (
<ListItem
button={true}
selected={props.selected}
style={{ display: 'block' }}
onClick={() => props.actions.selectConnection(props.connection.id)}
>
<Typography className={props.classes.name}>{props.connection.name || 'mqtt broker'}</Typography>
<Typography className={props.classes.details}>{connection && connection.url}</Typography>
</ListItem>
)
})
const ConnectionItem = connect(
null,
mapDispatchToProps
)(connectionItemRenderer)
const mapStateToProps = (state: AppState) => {
return {
connections: state.connectionManager.connections,
selected: state.connectionManager.selected,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(ProfileList))
-43
View File
@@ -1,43 +0,0 @@
import * as React from 'react'
import { Theme, withStyles } from '@material-ui/core'
interface Props {
keyboardKey: string
classes: any
}
class Key extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
this.state = { location: 'bottom' }
}
public render() {
return (
<div className={this.props.classes.keyStyle}>
<div className={this.props.classes.keyTextStyle}>{this.props.keyboardKey}</div>
</div>
)
}
}
const style = (theme: Theme) => ({
keyStyle: {
display: 'inline-block' as 'inline-block',
width: '1em',
height: '1em',
backgroundColor: '#bbb',
borderRadius: '10%',
verticalAlign: 'middle' as 'middle',
textAlign: 'center' as 'center',
textShadow: '1px 1px rgba(255,255,255,0.45)',
boxShadow: '0.08em 0.15em 0.01em 0px rgba(100,100,100,0.75)',
},
keyTextStyle: {
marginTop: '0.65em',
fontSize: '0.4em',
fontWeight: 'bold' as 'bold',
},
})
export default withStyles(style)(Key)
-82
View File
@@ -1,82 +0,0 @@
import * as React from 'react'
import { Theme, withStyles } from '@material-ui/core'
const cursor = require('./cursor.png')
interface State {
enabled: boolean
target: { x: number; y: number }
position: { x: number; y: number }
stepSizeX: number
stepSizeY: number
}
class Demo extends React.Component<{ classes: any }, State> {
private timer: any
private frameInterval = 20
constructor(props: any) {
super(props)
this.state = { enabled: false, target: { x: 0, y: 0 }, position: { x: 0, y: 0 }, stepSizeX: 1, stepSizeY: 1 }
}
private moveCloser(steps: number = 0) {
const steSizeX = Math.min(this.state.stepSizeX, Math.abs(this.state.position.x - this.state.target.x))
const steSizeY = Math.min(this.state.stepSizeY, Math.abs(this.state.position.y - this.state.target.y))
const dirX = this.state.position.x > this.state.target.x ? -1 : 1
const dirY = this.state.position.y > this.state.target.y ? -1 : 1
if (steSizeX <= 0.1 && steSizeY <= 0.1) {
this.timer && clearTimeout(this.timer)
return
}
this.setState({
position: {
x: this.state.position.x + dirX * steSizeX,
y: this.state.position.y + dirY * steSizeY,
},
})
this.timer = setTimeout(() => {
this.moveCloser(steps + 1)
}, this.frameInterval)
}
public componentDidMount() {
;(window as any).demo.enableMouse = () => {
this.setState({ enabled: true })
}
;(window as any).demo.moveMouse = (x: number, y: number, animationTime: number) => {
const stepSizeX = Math.abs(this.state.position.x - x) / (animationTime / this.frameInterval)
const stepSizeY = Math.abs(this.state.position.y - y) / (animationTime / this.frameInterval)
this.setState({ stepSizeX, stepSizeY, enabled: true, target: { x, y } })
this.moveCloser()
}
}
public render() {
if (!this.state.enabled) {
return null
}
const cursorStyle = {
left: this.state.position.x + 2,
top: this.state.position.y + 2,
}
return <img src={cursor} style={cursorStyle} className={this.props.classes.cursor} />
}
}
const style = (theme: Theme) => ({
cursor: {
width: '32px',
height: '32px',
position: 'fixed' as 'fixed',
zIndex: 1000000,
filter: theme.palette.type === 'light' ? undefined : 'invert(100%)',
pointerEvents: 'none' as 'none',
},
})
export default withStyles(style)(Demo)
-93
View File
@@ -1,93 +0,0 @@
import * as React from 'react'
import { Theme, withStyles } from '@material-ui/core'
import Key from './Key'
interface State {
message?: string
keys: Array<string>
location: string
}
class Demo extends React.Component<{ classes: any }, State> {
private timer: any
constructor(props: any) {
super(props)
this.state = { location: 'bottom', keys: [] }
}
private clearTimer() {
this.timer && clearTimeout(this.timer)
}
public componentDidMount() {
;(window as any).demo.showMessage = (
message: string,
location: string,
duration: number,
keys: Array<string> = []
) => {
this.clearTimer()
this.setState({ message, location, keys })
this.timer = setTimeout(() => this.setState({ message: undefined }), duration)
}
;(window as any).demo.hideMessage = () => {
this.clearTimer()
this.setState({ message: undefined })
}
}
public render() {
const positions: { [s: string]: number } = {
top: 0,
bottom: -65,
middle: -32,
}
const style = {
position: 'fixed' as 'fixed',
left: '5vw',
zIndex: 1000000,
margin: '30vw auto 50vw',
right: '5vw',
bottom: `${positions[this.state.location]}vh`,
}
const style2 = {
textAlign: 'center' as 'center',
fontSize: '4em',
color: 'white',
backgroundColor: 'rgba(0, 0, 0, 0.8)',
borderRadius: '16px',
}
if (!this.state.message) {
return null
}
let keys: Array<any> = []
if (this.state.keys.length > 0) {
keys = this.state.keys
.map(key => [<Key key={key} keyboardKey={key} />])
.reduce((prev, current) => {
return [prev, '+' as any, current]
})
}
return (
<div style={style}>
<div style={style2}>
<span>{this.state.message}</span>
{keys.length > 0 ? <div className={this.props.classes.keysStyle}>{keys}</div> : null}
</div>
</div>
)
}
}
const style = (theme: Theme) => ({
keysStyle: {
fontSize: '1em',
display: 'inline-block' as 'inline-block',
transform: 'translateY(0.3em) translateX(0.8em)',
},
})
export default withStyles(style)(Demo)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

-26
View File
@@ -1,26 +0,0 @@
import * as React from 'react'
import ShowText from './ShowText'
import Mouse from './Mouse'
let heapdump: any
function writeHeapdump(path?: string) {
if (!heapdump) {
heapdump = require('heapdump')
}
heapdump.writeSnapshot(path || `${Date.now()}.heapsnapshot`)
return path
}
;(window as any).demo = {
writeHeapdump,
}
export default function render(props: any) {
return (
<span>
<ShowText />
<Mouse />
</span>
)
}
-118
View File
@@ -1,118 +0,0 @@
import * as React from 'react'
import PersistentStorage from '../utils/PersistentStorage'
import SentimentDissatisfied from '@material-ui/icons/SentimentDissatisfied'
import Warning from '@material-ui/icons/Warning'
import { electronRendererTelementry } from 'electron-telemetry'
import { Theme, withStyles } from '@material-ui/core/styles'
import { Button, Modal, Paper, Toolbar, Typography } from '@material-ui/core'
interface State {
error?: Error
}
interface Props {
classes: any
}
class ErrorBoundary extends React.Component<Props, State> {
public static getDerivedStateFromError(error: Error) {
return { error }
}
constructor(props: Props) {
super(props)
this.state = {}
}
private restart = () => {
window.location = window.location
}
private clearStorage = () => {
PersistentStorage.clear()
window.location = window.location
}
public componentDidCatch(error: Error, errorInfo: any) {
electronRendererTelementry.trackError(error)
console.log('did catch', error)
}
public render() {
if (!this.state.error) {
return this.props.children
}
const { classes } = this.props
return (
<Modal open={true} disableAutoFocus={true}>
<Paper className={classes.root}>
<Toolbar style={{ padding: '0' }}>
<Typography className={classes.title} variant="h6" color="inherit">
<Warning /> Oooooops!
</Typography>
</Toolbar>
<Typography className={classes.centered}>
I hoped that you would never see this window, but MQTT-Explorer had an unexpected error.
</Typography>
<Typography className={classes.centered}>
<SentimentDissatisfied />
</Typography>
<pre className={classes.textColor} style={{ maxHeight: '35vh', overflow: 'scroll' }}>
<code className={classes.textColor}>{this.state.error.stack}</code>
</pre>
<Typography>
Please report this issue with a short description of what happened to
<span>
{' '}
<a className={classes.textColor} href="https://github.com/thomasnordquist/MQTT-Explorer/issues">
https://github.com/thomasnordquist/MQTT-Explorer/issues
</a>
</span>
</Typography>
<div>
<div className={classes.buttonPositioning}>
<Button className={classes.button} variant="contained" color="secondary" onClick={this.clearStorage}>
Start Fresh
</Button>
<Button className={classes.button} variant="contained" color="primary" onClick={this.restart}>
Restart
</Button>
</div>
</div>
</Paper>
</Modal>
)
}
}
const styles = (theme: Theme) => ({
button: {
margin: '0 8px 0 8px',
},
root: {
minWidth: 550,
maxWidth: 650,
backgroundColor: theme.palette.background.default,
margin: '10vh auto auto auto',
padding: theme.spacing(2),
outline: 'none',
},
title: {
color: theme.palette.text.primary,
margin: '0',
textAlign: 'center' as 'center',
},
textColor: {
color: theme.palette.text.primary,
userSelect: 'all' as 'all',
},
centered: {
textAlign: 'center' as 'center',
},
buttonPositioning: {
textAlign: 'center' as 'center',
marginTop: theme.spacing(2),
},
})
export default withStyles(styles)(ErrorBoundary)
-86
View File
@@ -1,86 +0,0 @@
import * as React from 'react'
import ChartPanel from '../ChartPanel'
import ReactSplitPane from 'react-split-pane'
import Tree from '../Tree/Tree'
import { AppState } from '../../reducers'
import { ChartParameters } from '../../reducers/Charts'
import { connect } from 'react-redux'
import { List } from 'immutable'
import { Sidebar } from '../Sidebar'
import ReactResizeDetector from 'react-resize-detector'
interface Props {
heightProperty: any
paneDefaults: any
connectionId?: string
chartPanelItems: List<ChartParameters>
}
function ContentView(props: Props) {
const [height, setHeight] = React.useState<string | number>('100%')
const [detectedHeight, setDetectedHeight] = React.useState(0)
const detectSize = React.useCallback((width, newHeight) => {
setDetectedHeight(newHeight)
}, [])
// Open chart panel on start and when a new chart is added but the panel is closed
React.useEffect(() => {
const almostClosed = !isNaN(height as any) && detectedHeight < 30
if ((!height || height === '100%' || almostClosed) && props.chartPanelItems.count() > 0) {
setHeight('calc(100% - 250px)')
}
if (props.chartPanelItems.count() === 0) {
setHeight('100%')
}
}, [props.chartPanelItems])
return (
<div className={props.paneDefaults}>
<ReactSplitPane
step={10}
split="horizontal"
minSize={0}
size={height}
defaultSize={'100%'}
allowResize={true}
style={{ height: 'calc(100vh - 64px)' }}
pane1Style={{ maxHeight: '100%' }}
pane2Style={{ borderTop: '1px solid #999', overflow: 'hidden scroll' }}
onChange={setHeight}
>
<span>
<ReactSplitPane
step={20}
primary="second"
className={props.heightProperty}
split="vertical"
minSize={250}
defaultSize={500}
allowResize={true}
style={{ height: '100%' }}
pane1Style={{ overflowX: 'hidden' }}
resizerStyle={{ height: '100%' }}
>
<Tree />
<div className={props.paneDefaults} style={{ height: '100%', overflowY: 'auto', overflowX: 'hidden' }}>
<Sidebar connectionId={props.connectionId} />
</div>
</ReactSplitPane>
</span>
<div>
<ReactResizeDetector handleHeight={true} onResize={detectSize} />
<ChartPanel />
</div>
</ReactSplitPane>
</div>
)
}
const mapStateToProps = (state: AppState) => {
return {
chartPanelItems: state.charts.get('charts'),
}
}
export default connect(mapStateToProps)(ContentView)
@@ -1,52 +0,0 @@
import * as React from 'react'
import { Snackbar, SnackbarContent } from '@material-ui/core'
import { Theme, withStyles } from '@material-ui/core/styles'
import { green, red } from '@material-ui/core/colors'
interface Props {
message?: string
type: 'error' | 'notification'
onClose: () => void
classes: any
}
class Notification extends React.Component<Props, {}> {
constructor(props: Props) {
super(props)
}
public static styles = (theme: Theme) => ({
notification: {
backgroundColor: green[600],
color: theme.typography.button.color,
},
error: {
backgroundColor: theme.palette.error.main,
color: theme.typography.button.color,
},
})
public render() {
const snackbarAnchor = {
vertical: 'bottom' as 'bottom',
horizontal: 'left' as 'left',
}
return (
<Snackbar
anchorOrigin={snackbarAnchor}
open={Boolean(this.props.message)}
autoHideDuration={this.props.type === 'error' ? 10000 : 2000}
onClose={this.props.onClose}
>
<SnackbarContent
className={this.props.type === 'error' ? this.props.classes.error : this.props.classes.notification}
message={this.props.message}
/>
</Snackbar>
)
}
}
export default withStyles(Notification.styles)(Notification)
-108
View File
@@ -1,108 +0,0 @@
import * as React from 'react'
import * as q from '../../../../backend/src/Model'
import CustomIconButton from '../helper/CustomIconButton'
import Pause from '@material-ui/icons/PauseCircleFilled'
import Resume from '@material-ui/icons/PlayCircleFilled'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { treeActions } from '../../actions'
import { withStyles, Theme } from '@material-ui/core/styles'
const styles = (theme: Theme) => ({
icon: {
color: theme.palette.primary.contrastText,
verticalAlign: 'middle' as 'middle',
},
bufferStats: {
minWidth: '8em',
},
})
interface Props {
classes: any
actions: {
tree: typeof treeActions
}
paused: boolean
tree?: q.Tree<any>
}
class PauseButton extends React.Component<Props, { changes: number }> {
private timer?: any
constructor(props: Props) {
super(props)
this.state = { changes: 0 }
}
private renderBufferStats() {
if (!this.props.tree) {
return
}
return (
<span className={this.props.classes.bufferStats}>
{this.state.changes} changes
<br />
buffer at {Math.round(this.props.tree.unmergedChanges().fillState() * 10000) / 100}%
</span>
)
}
public componentDidMount() {
this.timer = setInterval(() => {
if (!this.props.paused || !this.props.tree) {
return
}
const changes = this.props.tree.unmergedChanges()
if (this.state.changes !== changes.length) {
this.setState({ changes: changes.length })
}
}, 300)
}
public componentWillUnmount() {
this.timer && clearInterval(this.timer)
}
public render() {
const message = this.props.paused
? 'Resumes updating the tree, after applying all recorded changes'
: 'Stops all updates, records changes until the buffer is full.'
return (
<div style={{ display: 'inline-flex' }}>
<span>
<CustomIconButton onClick={this.props.actions.tree.togglePause} tooltip={message}>
{this.props.paused ? (
<Resume className={this.props.classes.icon} />
) : (
<Pause className={this.props.classes.icon} />
)}
</CustomIconButton>
</span>
{this.props.paused ? this.renderBufferStats() : null}
</div>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
paused: state.tree.get('paused'),
tree: state.tree.get('tree'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
tree: bindActionCreators(treeActions, dispatch),
},
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(PauseButton))
-180
View File
@@ -1,180 +0,0 @@
import * as React from 'react'
import ClearAdornment from '../helper/ClearAdornment'
import CloudOff from '@material-ui/icons/CloudOff'
import ConnectionHealthIndicator from '../helper/ConnectionHealthIndicator'
import Menu from '@material-ui/icons/Menu'
import PauseButton from './PauseButton'
import Search from '@material-ui/icons/Search'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectionActions, globalActions, settingsActions } from '../../actions'
import { fade } from '@material-ui/core/styles/colorManipulator'
import { Theme, withStyles } from '@material-ui/core/styles'
import { AppBar, Button, IconButton, InputBase, Toolbar, Typography } from '@material-ui/core'
const styles = (theme: Theme) => ({
title: {
display: 'none' as 'none',
[theme.breakpoints.up(750)]: {
display: 'block' as 'block',
},
whiteSpace: 'nowrap' as 'nowrap',
},
search: {
position: 'relative' as 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.white, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.common.white, 0.25),
},
marginRight: theme.spacing(2),
marginLeft: 0,
flexGrow: 1,
maxWidth: '60%',
[theme.breakpoints.up('md')]: {
maxWidth: '30%',
marginLeft: theme.spacing(4),
width: 'auto' as 'auto',
},
[theme.breakpoints.up(750)]: {
marginLeft: theme.spacing(4),
width: 'auto' as 'auto',
},
},
disconnectIcon: {
[theme.breakpoints.down('xs')]: {
display: 'none' as 'none',
},
marginRight: '8px',
paddingLeft: '8px',
},
searchIcon: {
width: theme.spacing(6),
height: '100%',
position: 'absolute' as 'absolute',
pointerEvents: 'none' as 'none',
display: 'flex' as 'flex',
alignItems: 'center' as 'center',
justifyContent: 'center' as 'center',
},
inputRoot: {
color: 'inherit' as 'inherit',
width: '100%',
},
inputInput: {
paddingTop: theme.spacing(1),
paddingRight: theme.spacing(1),
paddingBottom: theme.spacing(1),
paddingLeft: theme.spacing(6),
transition: theme.transitions.create('width'),
width: '100%',
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
disconnect: {
margin: 'auto 8px auto auto',
color: theme.palette.primary.contrastText,
},
})
interface Props {
classes: any
actions: {
settings: typeof settingsActions
connection: typeof connectionActions
global: typeof globalActions
}
topicFilter?: string
}
class TitleBar extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
this.state = {}
}
private renderSearch() {
const { classes, topicFilter } = this.props
return (
<div className={classes.search}>
<div className={classes.searchIcon}>
<Search />
</div>
<InputBase
value={topicFilter}
onChange={this.onFilterChange}
placeholder="Search…"
endAdornment={
<div style={{ width: '24px', paddingRight: '8px' }}>
<ClearAdornment variant="primary" action={this.clearFilter} value={topicFilter} />
</div>
}
classes={{ root: classes.inputRoot, input: classes.inputInput }}
/>
</div>
)
}
private clearFilter = () => {
this.props.actions.settings.filterTopics('')
}
private onFilterChange = (event: React.ChangeEvent<HTMLInputElement>) => {
this.props.actions.settings.filterTopics(event.target.value)
}
public render() {
const { actions, classes } = this.props
return (
<AppBar position="static">
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={actions.global.toggleSettingsVisibility}
>
<Menu />
</IconButton>
<Typography className={classes.title} variant="h6" color="inherit">
MQTT Explorer
</Typography>
{this.renderSearch()}
<PauseButton />
<Button className={classes.disconnect} onClick={actions.connection.disconnect}>
Disconnect <CloudOff className={classes.disconnectIcon} />
</Button>
<ConnectionHealthIndicator withBackground={true} />
</Toolbar>
</AppBar>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
topicFilter: state.settings.get('topicFilter'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
settings: bindActionCreators(settingsActions, dispatch),
global: bindActionCreators(globalActions, dispatch),
connection: bindActionCreators(connectionActions, dispatch),
},
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(TitleBar))
@@ -1,36 +0,0 @@
import * as React from 'react'
import { InputLabel, Switch, Theme, Tooltip } from '@material-ui/core'
import { withStyles } from '@material-ui/styles'
const sha1 = require('sha1')
function BooleanSwitch(props: { title: string; value: boolean; tooltip: string; action: () => void; classes: any }) {
const { tooltip, value, action, title, classes } = props
const clickHandler = (e: React.MouseEvent) => {
e.stopPropagation()
e.preventDefault()
action()
}
return (
<div style={{ padding: '8px', display: 'flex' }}>
<Tooltip title={tooltip}>
<InputLabel htmlFor={`toggle-${sha1(title)}`} onClick={clickHandler} className={classes.label}>
{title}
</InputLabel>
</Tooltip>
<Tooltip title={tooltip}>
<Switch name={`toggle-${sha1(title)}`} checked={value} onChange={action} color="primary" />
</Tooltip>
</div>
)
}
const styles = (theme: Theme) => ({
label: {
flex: '1',
paddingTop: theme.spacing(1.5),
},
})
export default withStyles(styles)(BooleanSwitch)
@@ -1,137 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import { AppState } from '../../reducers'
import { connect } from 'react-redux'
import { StyleRulesCallback, withStyles, Theme } from '@material-ui/core/styles'
import { TopicViewModel } from '../../model/TopicViewModel'
import { Typography } from '@material-ui/core'
import { Base64Message } from '../../../../backend/src/Model/Base64Message'
import teal from '@material-ui/core/colors/teal'
const abbreviate = require('number-abbreviate')
interface Stats {
topic: string
title: string
}
const styles = (theme: Theme) => ({
flex: {
display: 'flex',
width: '100%',
},
container: {
width: '100%',
height: '224px',
backgroundColor: theme.palette.type === 'dark' ? 'rebeccapurple' : '#ebebeb',
marginBottom: 0,
padding: '8px',
},
})
interface Props {
classes: any
tree?: q.Tree<TopicViewModel>
}
class BrokerStatistics extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
this.state = {}
}
private renderPair(tree: q.Tree<TopicViewModel>, a: Stats, b: Stats) {
return (
<div className={this.props.classes.flex}>
<div style={{ flex: 1 }}>{this.renderStat(tree, a)}</div>
<div style={{ flex: 1 }}>{this.renderStat(tree, b)}</div>
</div>
)
}
public render() {
const { tree, classes } = this.props
if (!tree || !tree.findNode('$SYS/broker/clients/total')) {
return null
}
const stats: any = {
broker: {
topic: '$SYS/broker/version',
title: 'Broker',
},
clients: {
topic: '$SYS/broker/clients/total',
title: 'Clients',
},
subscriptions: {
topic: '$SYS/broker/subscriptions/count',
title: 'Subscriptions',
},
received: {
topic: '$SYS/broker/messages/received',
title: 'Received',
},
sent: {
topic: '$SYS/broker/messages/sent',
title: 'Sent',
},
received5m: {
topic: '$SYS/broker/load/messages/received/5min',
title: 'Received last 5min',
},
sent5m: {
topic: '$SYS/broker/load/messages/sent/5min',
title: 'Sent 5m',
},
heap: {
topic: '$SYS/broker/heap/current',
title: 'Memory',
},
heapMax: {
topic: '$SYS/broker/heap/maximum',
title: 'Memory (max)',
},
}
return (
<div className={classes.container}>
{this.renderStat(tree, stats.broker)}
{this.renderPair(tree, stats.sent, stats.received)}
{this.renderPair(tree, stats.clients, stats.subscriptions)}
{this.renderPair(tree, stats.sent5m, stats.received5m)}
{this.renderPair(tree, stats.heap, stats.heapMax)}
</div>
)
}
public renderStat(tree: q.Tree<TopicViewModel>, stat: Stats) {
const node = tree.findNode(stat.topic)
if (!node || !node.message) {
return null
}
const str = node.message.value ? Base64Message.toUnicodeString(node.message.value) : ''
let value = node.message && node.message.value ? parseFloat(str) : NaN
value = !isNaN(value) ? abbreviate(value) : str
return (
<div key={stat.title}>
<Typography>
<b>{stat.title}</b>
</Typography>
<Typography style={{ paddingLeft: '8px' }}>
<i>{value}</i>
</Typography>
</div>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
tree: state.connection.tree,
}
}
export default withStyles(styles)(connect(mapStateToProps)(BrokerStatistics))
@@ -1,263 +0,0 @@
import * as React from 'react'
import BooleanSwitch from './BooleanSwitch'
import BrokerStatistics from './BrokerStatistics'
import ChevronRight from '@material-ui/icons/ChevronRight'
import TimeLocale from './TimeLocale'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { globalActions, settingsActions } from '../../actions'
import { shell } from 'electron'
import { Theme, withStyles } from '@material-ui/core/styles'
import { TopicOrder } from '../../reducers/Settings'
import {
Divider,
Drawer,
IconButton,
Input,
InputLabel,
MenuItem,
Select,
Typography,
Tooltip,
} from '@material-ui/core'
export const autoExpandLimitSet = [
{
limit: 0,
name: 'Collapsed',
},
{
limit: 2,
name: 'Few',
},
{
limit: 5,
name: 'Some',
},
{
limit: 15,
name: 'Most',
},
{
limit: 30,
name: 'Most',
},
{
limit: 1e6,
name: 'All',
},
]
const styles = (theme: Theme) => ({
drawer: {
backgroundColor: theme.palette.background.default,
flexShrink: 0,
userSelect: 'none' as 'none',
},
paper: {
width: '300px',
},
title: {
color: theme.palette.text.primary,
paddingTop: theme.spacing(1),
...theme.mixins.toolbar,
},
input: {
minWidth: '150px',
margin: `auto ${theme.spacing(1)} auto ${theme.spacing(2)}px`,
},
author: {
margin: 'auto 8px 8px auto',
color: theme.palette.text.hint,
cursor: 'pointer' as 'pointer',
},
})
interface Props {
actions: {
settings: typeof settingsActions
global: typeof globalActions
}
autoExpandLimit: number
classes: any
highlightTopicUpdates: boolean
selectTopicWithMouseOver: boolean
store?: any
topicOrder: TopicOrder
visible: boolean
theme: 'light' | 'dark'
}
class Settings extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
this.state = {}
}
private openGithubPage = () => {
shell.openExternal('https://github.com/thomasnordquist')
}
private renderHighlightTopicUpdates() {
const { highlightTopicUpdates, actions } = this.props
return (
<BooleanSwitch
title="Show Activity"
tooltip="Topics blink when a new message arrives"
value={highlightTopicUpdates}
action={actions.settings.toggleHighlightTopicUpdates}
/>
)
}
private selectTopicsOnMouseOver() {
const { actions, selectTopicWithMouseOver } = this.props
const toggle = () => actions.settings.selectTopicWithMouseOver(!selectTopicWithMouseOver)
return (
<BooleanSwitch
title="Quick Preview"
tooltip="Select topics on mouse over"
value={selectTopicWithMouseOver}
action={toggle}
/>
)
}
private toggleTheme() {
const { actions, theme } = this.props
return (
<BooleanSwitch
title="Dark Mode"
tooltip="Enable dark theme"
value={theme === 'dark'}
action={actions.settings.toggleTheme}
/>
)
}
private renderAutoExpand() {
const { classes, autoExpandLimit } = this.props
const limits = autoExpandLimitSet.map(limit => (
<MenuItem key={limit.limit} value={limit.limit}>
{limit.limit < 10000 && limit.limit > 0 ? `${limit.limit} topics` : limit.name}
</MenuItem>
))
return (
<div style={{ padding: '8px', display: 'flex' }}>
<InputLabel htmlFor="auto-expand" style={{ flex: '1', marginTop: '8px' }}>
Auto Expand
</InputLabel>
<Select
value={autoExpandLimit}
onChange={this.onChangeAutoExpand}
input={<Input name="auto-expand" id="auto-expand-label-placeholder" />}
name="auto-expand"
className={classes.input}
style={{ flex: '1' }}
>
{limits}
</Select>
</div>
)
}
private onChangeAutoExpand = (e: React.ChangeEvent<{ value: unknown }>) => {
this.props.actions.settings.setAutoExpandLimit(parseInt(String(e.target.value), 10))
}
private renderNodeOrder() {
const { classes, topicOrder } = this.props
return (
<div style={{ padding: '8px', display: 'flex' }}>
<InputLabel htmlFor="auto-expand" style={{ flex: '1', marginTop: '8px' }}>
Topic Order
</InputLabel>
<Select
value={topicOrder}
onChange={this.onChangeSorting}
input={<Input name="node-order" id="node-order-label-placeholder" />}
displayEmpty={true}
name="node-order"
className={classes.input}
style={{ flex: '1' }}
>
<MenuItem value={TopicOrder.none}>
<em>default</em>
</MenuItem>
<MenuItem value={TopicOrder.abc}>a-z</MenuItem>
<MenuItem value={TopicOrder.messages}>{TopicOrder.messages}</MenuItem>
<MenuItem value={TopicOrder.topics}>{TopicOrder.topics}</MenuItem>
</Select>
</div>
)
}
private onChangeSorting = (e: React.ChangeEvent<{ value: unknown }>) => {
this.props.actions.settings.setTopicOrder(e.target.value as TopicOrder)
}
public render() {
const { classes, actions, visible } = this.props
return (
<Drawer anchor="left" className={classes.drawer} open={visible} variant="persistent">
<div className={classes.paper} tabIndex={0} role="button">
<Typography className={classes.title} variant="h6" color="inherit">
<IconButton onClick={actions.global.toggleSettingsVisibility}>
<ChevronRight />
</IconButton>
Settings
</Typography>
<Divider style={{ userSelect: 'none' }} />
</div>
<div>
{this.renderAutoExpand()}
{this.renderNodeOrder()}
<TimeLocale />
{this.renderHighlightTopicUpdates()}
{this.selectTopicsOnMouseOver()}
{this.toggleTheme()}
</div>
<Tooltip placement="top" title="App Author">
<Typography className={classes.author} onClick={this.openGithubPage}>
by Thomas Nordquist
</Typography>
</Tooltip>
<BrokerStatistics />
</Drawer>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
autoExpandLimit: state.settings.get('autoExpandLimit'),
topicOrder: state.settings.get('topicOrder'),
visible: state.globalState.get('settingsVisible'),
highlightTopicUpdates: state.settings.get('highlightTopicUpdates'),
selectTopicWithMouseOver: state.settings.get('selectTopicWithMouseOver'),
theme: state.settings.get('theme'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
settings: bindActionCreators(settingsActions, dispatch),
global: bindActionCreators(globalActions, dispatch),
},
}
}
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(Settings)
)
@@ -1,90 +0,0 @@
import * as React from 'react'
import DateFormatter from '../helper/DateFormatter'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Input, InputLabel, MenuItem, Select, StyleRulesCallback, Theme } from '@material-ui/core'
import { settingsActions } from '../../actions'
import { withStyles } from '@material-ui/styles'
const moment = require('moment/min/moment-with-locales')
interface Props {
actions: {
settings: typeof settingsActions
}
timeLocale: string
classes: any
}
function TimeLocaleSettings(props: Props) {
const { classes, timeLocale, actions } = props
const locales = moment.locales()
const date = new Date()
const localeMenuItems = locales.map((l: string) => (
<MenuItem key={l} value={l}>
<div>
Locale: <b>{l}</b>, Format:{' '}
<b>
<DateFormatter date={date} overrideLocale={l} />
</b>
</div>
</MenuItem>
))
function updateLocale(e: React.ChangeEvent<{ value: unknown }>) {
const locale = e.target.value ? String(e.target.value) : ''
actions.settings.setTimeLocale(locale)
}
return (
<div style={{ padding: '8px', display: 'flex' }}>
<InputLabel htmlFor="time-locale" style={{ flex: '1', marginTop: '8px' }}>
Time Locale
</InputLabel>
<Select
value={timeLocale}
onChange={updateLocale}
input={<Input name="time-locale" id="time-locale-label-placeholder" />}
name="time-locale"
className={classes.input}
renderValue={v => <span>{String(v)}</span>}
style={{ flex: '1' }}
>
{localeMenuItems}
</Select>
</div>
)
}
const mapStateToProps = (state: AppState) => {
return {
timeLocale: state.settings.get('timeLocale'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
settings: bindActionCreators(settingsActions, dispatch),
},
}
}
const styles = (theme: Theme) => ({
input: {
minWidth: '150px',
margin: `auto ${theme.spacing(1)} auto ${theme.spacing(2)}px`,
},
selected: {
'& div': {
display: 'none',
},
},
})
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(TimeLocaleSettings)
)
@@ -1,19 +0,0 @@
export enum CodeBlockColors {
text = '#080808',
background = '#F9F9F9',
numeric = '#811F24',
boolean = '#811F24',
string = '#0B6125',
variable = '#234A97',
gutters = '#ebebeb',
}
export enum CodeBlockColorsBraceMonokai {
text = '#F8F8F2',
background = '#272822',
numeric = '#AE81FF',
boolean = '#AE81FF',
string = '#E6DB74',
variable = '#A6E22E',
gutters = '#2F3129',
}
@@ -1,83 +0,0 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import ShowChart from '@material-ui/icons/ShowChart'
import TopicPlot from '../../TopicPlot'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../../actions'
import { connect } from 'react-redux'
import { Fade, Paper, Popper, Tooltip } from '@material-ui/core'
import { JsonPropertyLocation } from '../../../../../backend/src/JsonAstParser'
interface Props {
treeNode: q.TreeNode<any>
classes: any
literal: JsonPropertyLocation
actions: {
chart: typeof chartActions
}
}
function ChartPreview(props: Props) {
const chartIconRef = React.useRef(null)
const [open, setOpen] = React.useState(false)
const onClick = React.useCallback(() => {
props.actions.chart.addChart({
topic: props.treeNode.path(),
dotPath: props.literal.path,
})
setOpen(false)
}, [props.literal.path, props.treeNode])
const mouseOver = React.useCallback(() => {
setOpen(true)
}, [])
const mouseOut = React.useCallback(() => {
setOpen(false)
}, [])
const hasEnoughDataToDisplayDiagrams = props.treeNode.messageHistory.count() > 1
const addChartToPanelButton = hasEnoughDataToDisplayDiagrams ? (
<Tooltip title="Click to add to chart panel">
<ShowChart
ref={chartIconRef}
className={props.classes.icon}
onMouseEnter={mouseOver}
onMouseLeave={mouseOut}
onClick={onClick}
/>
</Tooltip>
) : (
<Tooltip title="Click to add to chart panel, not enough data for preview">
<ShowChart onClick={onClick} className={props.classes.icon} style={{ color: '#aaa' }} />
</Tooltip>
)
return (
<span>
{addChartToPanelButton}
<Popper open={open} anchorEl={chartIconRef.current} placement="left-end">
<Fade in={open} timeout={300}>
<Paper style={{ width: '300px' }}>
{open ? <TopicPlot history={props.treeNode.messageHistory} dotPath={props.literal.path} /> : <span />}
</Paper>
</Fade>
</Popper>
</span>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
chart: bindActionCreators(chartActions, dispatch),
},
}
}
export default connect(
undefined,
mapDispatchToProps
)(ChartPreview)
@@ -1,45 +0,0 @@
import * as React from 'react'
import { Theme } from '@material-ui/core'
import { withStyles } from '@material-ui/styles'
interface Props {
changes: Array<Diff.Change>
classes: { [s: string]: any }
nameOfCompareMessage: string
}
function changeAmount(props: Props) {
const additions = props.changes.map(change => (change.added === true ? change.count || 0 : 0)).reduce((a, b) => a + b)
const deletions = props.changes
.map(change => (change.removed === true ? change.count || 0 : 0))
.reduce((a, b) => a + b)
if (additions === 0 && deletions === 0) {
return null
}
return (
<span style={{ display: 'block', marginBottom: '8px', float: 'right' }}>
<span>
Comparing with <b>{props.nameOfCompareMessage}</b> message:&nbsp;
<span className={props.classes.additions}>
+ {additions} line{additions === 1 ? '' : 's'}
</span>
,{' '}
<span className={props.classes.deletions}>
- {deletions} line{deletions === 1 ? '' : 's'}
</span>
</span>
</span>
)
}
const style = (theme: Theme) => ({
additions: {
color: 'rgb(10, 255, 10)',
},
deletions: {
color: 'rgb(255, 10, 10)',
},
})
export default withStyles(style)(changeAmount)
@@ -1,104 +0,0 @@
import * as diff from 'diff'
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import Add from '@material-ui/icons/Add'
import ChartPreview from './ChartPreview'
import Remove from '@material-ui/icons/Remove'
import { JsonPropertyLocation } from '../../../../../backend/src/JsonAstParser'
import { lineChangeStyle, trimNewlineRight } from './util'
import { Theme } from '@material-ui/core'
import { withStyles } from '@material-ui/styles'
interface Props {
changes: Array<diff.Change>
literalPositions: Array<JsonPropertyLocation>
classes: any
className: string
treeNode: q.TreeNode<any>
}
const style = (theme: Theme) => {
const icon = {
verticalAlign: 'top',
width: '12px',
height: '12px',
marginTop: '2px',
borderRadius: '50%',
}
return {
icon,
iconButton: {
...icon,
marginTop: '0px',
width: '16px',
height: '16px',
padding: '2px',
'&:hover': {
color: theme.palette.primary.contrastText,
backgroundColor: theme.palette.primary.main,
},
},
gutterLine: {
textAlign: 'right' as 'right',
paddingRight: theme.spacing(0.5),
height: '16px',
width: '100%',
},
}
}
function tokensForLine(change: diff.Change, line: number, props: Props) {
const { classes, literalPositions } = props
const literal = literalPositions[line]
const chartPreview = Boolean(literal) ? (
<ChartPreview
key="chartPreview"
treeNode={props.treeNode}
classes={{ icon: props.classes.iconButton }}
literal={literal}
/>
) : null
if (change.added) {
return [chartPreview, <Add key="add" className={classes.icon} />]
} else if (change.removed) {
return [<Remove key="remove" className={classes.icon} />]
} else {
return [
chartPreview,
<div
key="placeholder"
style={{ width: '12px', display: 'inline-block' }}
dangerouslySetInnerHTML={{ __html: '&nbsp;' }}
/>,
]
}
}
function Gutters(props: Props) {
let currentLine = -1
const gutters = props.changes
.map((change, key) => {
return trimNewlineRight(change.value)
.split('\n')
.map((_, idx) => {
currentLine = !change.removed ? currentLine + 1 : currentLine
return (
<div key={`${key}-${idx}`} style={lineChangeStyle(change)} className={props.classes.gutterLine}>
{tokensForLine(change, currentLine, props)}
</div>
)
})
})
.reduce((a, b) => a.concat(b), [])
return (
<span>
<pre className={props.className}>{gutters}</pre>
</span>
)
}
export default withStyles(style)(Gutters)
@@ -1,107 +0,0 @@
import * as diff from 'diff'
import * as Prism from 'prismjs'
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import DiffCount from './DiffCount'
import Gutters from './Gutters'
import { isPlottable, lineChangeStyle, trimNewlineRight } from './util'
import { JsonPropertyLocation, literalsMappedByLines } from '../../../../../backend/src/JsonAstParser'
import { selectTextWithCtrlA } from '../../../utils/handleTextSelectWithCtrlA'
import { style } from './style'
import { withStyles } from '@material-ui/core'
import 'prismjs/components/prism-json'
interface Props {
treeNode: q.TreeNode<any>
previous: string
current: string
nameOfCompareMessage: string
language?: 'json'
classes: any
}
interface State {}
class CodeDiff extends React.Component<Props, State> {
private handleCtrlA = selectTextWithCtrlA({ targetSelector: 'pre ~ pre' })
constructor(props: Props) {
super(props)
this.state = {}
}
private isValidJson(str: string) {
try {
JSON.parse(str)
return true
} catch (error) {
return false
}
}
private plottableLiteralsIndexedWithLineNumbers() {
const allLiterals = this.isValidJson(this.props.current) ? literalsMappedByLines(this.props.current) || [] : []
return allLiterals.map((l: JsonPropertyLocation) => (isPlottable(l.value) ? l : undefined)) as Array<
JsonPropertyLocation
>
}
private renderStyledCodeLines(changes: Array<Diff.Change>) {
const styledLines = Prism.highlight(this.props.current, Prism.languages.json, 'json').split('\n')
let lineNumber = 0
return changes
.map((change, key) => {
const hasStyledCode = change.removed !== true
const changedLines = change.count || 0
if (hasStyledCode && this.props.language === 'json') {
const currentLines = styledLines.slice(lineNumber, lineNumber + changedLines)
const lines = currentLines.map((html: string, idx: number) => {
return (
<div key={`${key}-${idx}`} style={lineChangeStyle(change)} className={this.props.classes.line}>
<span dangerouslySetInnerHTML={{ __html: html }} />
</div>
)
})
lineNumber += changedLines
return [<div key={key}>{lines}</div>]
}
return trimNewlineRight(change.value)
.split('\n')
.map((line, idx) => {
return (
<div key={`${key}-${idx}`} style={lineChangeStyle(change)} className={this.props.classes.line}>
<span>{line}</span>
</div>
)
})
})
.reduce((a, b) => a.concat(b), [])
}
public render() {
const changes = diff.diffLines(this.props.previous, this.props.current)
const literalPositions = this.plottableLiteralsIndexedWithLineNumbers()
const code = this.renderStyledCodeLines(changes)
return (
<div>
<div tabIndex={0} onKeyDown={this.handleCtrlA} className={this.props.classes.codeWrapper}>
<Gutters
className={this.props.classes.gutters}
changes={changes}
treeNode={this.props.treeNode}
literalPositions={literalPositions}
/>
<pre className={this.props.classes.codeBlock}>{code}</pre>
</div>
<DiffCount changes={changes} nameOfCompareMessage={this.props.nameOfCompareMessage} />
</div>
)
}
}
export default withStyles(style)(CodeDiff)
@@ -1,63 +0,0 @@
import { CodeBlockColors, CodeBlockColorsBraceMonokai } from '../CodeBlockColors'
import { Theme } from '@material-ui/core'
export const style = (theme: Theme) => {
const codeBlockColors = theme.palette.type === 'light' ? CodeBlockColors : CodeBlockColorsBraceMonokai
const codeBaseStyle = {
font: "12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace",
display: 'inline-grid' as 'inline-grid',
margin: '0',
padding: '1px 0 0 0',
}
return {
line: {
lineHeight: 'normal' as 'normal',
paddingLeft: '4px',
width: '100%',
height: '16px',
},
codeWrapper: {
display: 'flex',
maxHeight: '15em',
overflow: 'auto',
backgroundColor: `${codeBlockColors.background}`,
margin: '8px 0 0 0',
},
gutters: {
...codeBaseStyle,
width: '33px',
backgroundColor: codeBlockColors.gutters,
userSelect: 'none' as 'none',
},
codeBlock: {
...codeBaseStyle,
width: 'calc(100% - 33px)',
backgroundColor: 'inherit !important',
'& span': {
color: codeBlockColors.text,
},
'& .token.number': {
color: codeBlockColors.numeric,
},
'& .token.boolean': {
color: codeBlockColors.numeric,
},
'& .token.property': {
color: codeBlockColors.variable,
},
'& .token.string': {
color: codeBlockColors.string,
},
'& .token': {
color: codeBlockColors.text,
},
'& .token.operator': {
color: codeBlockColors.text,
},
'& .token.punctuation': {
color: codeBlockColors.text,
},
},
}
}
@@ -1,69 +0,0 @@
export function trimNewlineRight(str: string) {
if (str.slice(-1) === '\n') {
return str.slice(0, -1)
}
return str
}
const gutterBaseStyle = {}
const additionStyle = {
...gutterBaseStyle,
backgroundColor: 'rgba(10, 255, 10, 0.3)',
}
const deletionStyle = {
...gutterBaseStyle,
backgroundColor: 'rgba(255, 10, 10, 0.3)',
}
export function lineChangeStyle(change: Diff.Change) {
if (change.added === true) {
return additionStyle
}
if (change.removed === true) {
return deletionStyle
}
return gutterBaseStyle
}
export function toPlottableValue(value: any): number | undefined {
if (typeof value === 'number') {
return value
}
if (typeof value === 'boolean') {
return value ? 1 : 0
}
const isNumber = !isNaN(value)
const floatVal = parseFloat(value)
if (isNumber && !isNaN(floatVal)) {
return floatVal
}
const intVal = parseInt(value, undefined)
if (isNumber && !isNaN(intVal)) {
return intVal
}
// Convert "on" / "off" to int 1 / 0
if (typeof value === 'string') {
if (/^(on$)|(off$)/i.test(value)) {
return value.toLowerCase() === 'on' ? 1 : 0
}
if (/^[0-9]*,[0-9]+$/.test(value)) {
let parsedFloat = parseFloat(value.replace(',', '.'))
if (!isNaN(parsedFloat)) {
return parsedFloat
}
}
}
}
export function isPlottable(value: any) {
return !isNaN(toPlottableValue(value) as any)
}
@@ -1,105 +0,0 @@
import * as React from 'react'
import { Badge, Typography } from '@material-ui/core'
import { selectTextWithCtrlA } from '../../utils/handleTextSelectWithCtrlA'
import { Theme, withStyles } from '@material-ui/core/styles'
interface HistoryItem {
key: string
title: JSX.Element | string
value: string
selected?: boolean
}
interface Props {
items: Array<HistoryItem>
onClick?: (index: number, element: EventTarget) => void
classes: any
contentTypeIndicator?: JSX.Element
theme: Theme
}
interface State {
collapsed: boolean
}
class HistoryDrawer extends React.Component<Props, State> {
constructor(props: any) {
super(props)
this.state = {
collapsed: true,
}
}
private toggle = () => {
this.setState({ collapsed: !this.state.collapsed })
}
private handleCtrlA = selectTextWithCtrlA({ targetSelector: 'pre' })
public renderHistory() {
const style = (element: HistoryItem) => ({
backgroundColor: element.selected
? this.props.theme.palette.action.selected
: this.props.theme.palette.action.hover,
margin: '8px',
padding: '8px 8px 0 8px',
cursor: this.props.onClick ? 'pointer' : 'inherit',
})
const messageStyle: React.CSSProperties = { textOverflow: 'ellipsis', whiteSpace: 'nowrap', overflow: 'hidden' }
const elements = this.props.items.map((element, index) => (
<div
key={element.key}
style={style(element)}
onClick={(event: React.MouseEvent) => this.props.onClick && this.props.onClick(index, event.target)}
tabIndex={0}
onKeyDown={this.handleCtrlA}
>
<div>
<i>{element.title}</i>
</div>
<div style={messageStyle}>
<span>
<pre>{element.value}</pre>
</span>
</div>
</div>
))
const visible = this.props.items.length > 0 && this.state.collapsed
return (
<div className={this.props.classes.main}>
<Typography component={'span'} onClick={this.toggle} style={{ cursor: 'pointer' }}>
<Badge
classes={{ badge: this.props.classes.badge }}
invisible={!visible}
badgeContent={this.props.items.length}
color="primary"
>
{this.state.collapsed ? '▶ History' : '▼ History'}
</Badge>
<div style={{ float: 'right' }}>{this.state.collapsed ? this.props.contentTypeIndicator : null}</div>
</Typography>
<div style={{ maxHeight: '230px', overflowY: 'scroll' }}>
{this.state.collapsed ? null : this.props.children}
{this.state.collapsed ? null : elements}
</div>
</div>
)
}
public render() {
return <div style={{ display: 'block', width: '100%' }}>{this.renderHistory()}</div>
}
}
const styles = (theme: Theme) => ({
main: {
backgroundColor: 'rgba(170, 170, 170, 0.2)',
marginTop: '16px',
},
badge: { right: '-25px' },
})
export default withStyles(styles, { withTheme: true })(HistoryDrawer)
-28
View File
@@ -1,28 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import { TopicViewModel } from '../../model/TopicViewModel'
import { Typography } from '@material-ui/core'
interface Props {
node: q.TreeNode<TopicViewModel>
}
class NodeStats extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
}
public render() {
const { node } = this.props
return (
<div>
<Typography>Messages: #{node.messages}</Typography>
<Typography>Subtopics: {node.childTopicCount()}</Typography>
<Typography>Messages Subtopics: #{node.leafMessageCount()}</Typography>
</div>
)
}
}
export default NodeStats
-108
View File
@@ -1,108 +0,0 @@
import * as React from 'react'
import DateFormatter from '../helper/DateFormatter'
import { default as ReactResizeDetector } from 'react-resize-detector'
import { PlotCurveTypes } from '../../reducers/Charts'
import { Theme, withTheme } from '@material-ui/core'
import 'react-vis/dist/style.css'
const { XYPlot, LineMarkSeries, Hint, XAxis, YAxis, HorizontalGridLines } = require('react-vis')
const abbreviate = require('number-abbreviate')
interface Props {
data: Array<{ x: number; y: number }>
theme: Theme
interpolation?: PlotCurveTypes
range?: [number?, number?]
}
function mapCurveType(type: PlotCurveTypes | undefined) {
switch (type) {
case 'curve':
return 'curveMonotoneX'
case 'linear':
return 'curveLinear'
case 'cubic_basis_spline':
return 'curveBasis'
case 'step_after':
return 'curveStepAfter'
case 'step_before':
return 'curveStepBefore'
default:
return 'curveMonotoneX'
}
}
export default withTheme((props: Props) => {
const [width, setWidth] = React.useState(300)
const [tooltip, setTooltip] = React.useState({ value: undefined })
const detectResize = React.useCallback(newWidth => setWidth(newWidth), [])
const hintFormatter = React.useCallback((point: any) => {
return [
{ title: <b>Time</b>, value: <DateFormatter date={new Date(point.x)} /> },
{ title: <b>Value</b>, value: point.y },
]
}, [])
const hideTooltip = React.useCallback(() => {
setTooltip({ value: undefined })
}, [])
const showTooltip = React.useCallback((value: any) => {
setTooltip({ value })
}, [])
return React.useMemo(() => {
const data = props.data
const calculatedDomain = domainForData(data)
let yDomain: [number, number] = props.range
? [props.range[0] || calculatedDomain[0], props.range[1] || calculatedDomain[1]]
: calculatedDomain
return (
<div style={{ height: '150px', overflow: 'hidden' }}>
<XYPlot width={width} height={180} yDomain={yDomain}>
<HorizontalGridLines />
<XAxis />
<YAxis width={45} tickFormat={(num: number) => abbreviate(num)} />
<LineMarkSeries
color={
props.theme.palette.type === 'light'
? props.theme.palette.secondary.dark
: props.theme.palette.primary.light
}
onValueMouseOver={showTooltip}
onValueMouseOut={hideTooltip}
size={3}
data={data}
curve={mapCurveType(props.interpolation)}
/>
{tooltip.value ? <Hint format={hintFormatter} value={tooltip.value} /> : null}
</XYPlot>
<ReactResizeDetector handleWidth={true} onResize={detectResize} />
</div>
)
}, [width, props.data, tooltip, props.interpolation, props.range])
})
function domainForData(data: Array<{ x: number; y: number }>): [number, number] {
let max = data[0].y
let min = data[0].y
data.forEach(d => {
if (max < d.y) {
max = d.y
}
if (min > d.y) {
min = d.y
}
})
if ((max === 1 || max === 0) && (min === 1 || min === 0)) {
return [0, 1]
}
if (min === max) {
return [min - 0.5 * min, min + 0.5 * min]
}
return [min, max]
}
@@ -1,39 +0,0 @@
import * as React from 'react'
import { default as AceEditor } from 'react-ace'
import { Theme, withTheme } from '@material-ui/core'
import 'brace/mode/json'
import 'brace/theme/dawn'
import 'brace/theme/monokai'
import 'brace/mode/xml'
import 'brace/mode/text'
import 'react-ace'
function Editor(props: {
editorMode: string
theme: Theme
value: string | undefined
onChange: (value: string) => void
}) {
const editorOptions = {
showLineNumbers: false,
tabSize: 2,
}
return (
<AceEditor
style={{}}
mode={props.editorMode}
theme={props.theme.palette.type === 'dark' ? 'monokai' : 'dawn'}
name="UNIQUE_ID_OF_DIV"
width="100%"
height="200px"
showGutter={true}
value={props.value}
onChange={props.onChange}
setOptions={editorOptions}
editorProps={{ $blockScrolling: true }}
/>
)
}
export default withTheme(Editor)
@@ -1,40 +0,0 @@
import * as React from 'react'
import { FormControlLabel, Radio, RadioGroup } from '@material-ui/core'
interface Props {
value: string
onChange: (event: React.ChangeEvent<{}>, value: string) => void
}
export function EditorModeSelect(props: Props) {
const labelStyle = { margin: '0 8px 0 8px' }
return (
<RadioGroup
style={{ display: 'inline-block', float: 'left' }}
value={props.value}
onChange={props.onChange}
row={true}
>
<FormControlLabel
value="text"
style={labelStyle}
control={<Radio color="primary" />}
label="raw"
labelPlacement="top"
/>
<FormControlLabel
value="xml"
style={labelStyle}
control={<Radio color="primary" />}
label="xml"
labelPlacement="top"
/>
<FormControlLabel
value="json"
style={labelStyle}
control={<Radio color="primary" />}
label="json"
labelPlacement="top"
/>
</RadioGroup>
)
}
@@ -1,7 +0,0 @@
interface Message {
topic: string
payload?: string
sent: Date
}
export default Message
@@ -1,243 +0,0 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import ClearAdornment from '../../helper/ClearAdornment'
import FormatAlignLeft from '@material-ui/icons/FormatAlignLeft'
import History from '../HistoryDrawer'
import Message from './Model/Message'
import Navigation from '@material-ui/icons/Navigation'
import { AppState } from '../../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { globalActions, publishActions } from '../../../actions'
import {
Button,
FormControlLabel,
FormControl,
InputLabel,
Input,
Checkbox,
Tooltip,
Fab,
Theme,
withTheme,
} from '@material-ui/core'
import { EditorModeSelect } from './EditorModeSelect'
import QosSelect from './QosSelect'
import Editor from './Editor'
const sha1 = require('sha1')
interface Props {
connectionId?: string
topic?: string
payload?: string
actions: typeof publishActions
globalActions: typeof globalActions
retain: boolean
editorMode: string
theme: Theme
}
interface State {
history: Array<Message>
}
class Publish extends React.Component<Props, State> {
constructor(props: any) {
super(props)
this.state = { history: [] }
}
private updatePayload = (payload: string) => {
this.props.actions.setPayload(payload)
}
private updateTopic = (e: React.ChangeEvent<HTMLInputElement>) => {
this.props.actions.setTopic(e.target.value)
}
private updateMode = (e: React.ChangeEvent<{}>, value: string) => {
this.props.actions.setEditorMode(value)
}
private publish = (e: React.MouseEvent) => {
e.stopPropagation()
if (!this.props.connectionId) {
return
}
this.props.actions.publish(this.props.connectionId)
const topic = this.props.topic || ''
const payload = this.props.payload
if (this.props.connectionId && topic) {
this.addMessageToHistory(topic, payload)
}
}
private addMessageToHistory(topic: string, payload?: string) {
// Remove duplicates
let filteredHistory = this.state.history.filter(e => e.payload !== payload || e.topic !== topic)
filteredHistory = filteredHistory.slice(-7)
const history: Array<Message> = [...filteredHistory, { topic, payload, sent: new Date() }]
this.setState({ history })
}
private clearTopic = () => {
this.props.actions.setTopic('')
}
private topic() {
const topicStr = this.props.topic || ''
return (
<div>
<FormControl style={{ width: '100%' }}>
<InputLabel htmlFor="publish-topic">Topic</InputLabel>
<Input
id="publish-topic"
value={topicStr}
startAdornment={<span />}
endAdornment={<ClearAdornment action={this.clearTopic} value={topicStr} />}
onBlur={this.onTopicBlur}
onChange={this.updateTopic}
multiline={true}
placeholder="example/topic"
/>
</FormControl>
</div>
)
}
private onTopicBlur = (e: React.FocusEvent<HTMLInputElement>) => {
if (!e.target.value) {
this.props.actions.setTopic(undefined)
}
}
private publishButton() {
return (
<Button variant="contained" size="small" color="primary" onClick={this.publish} id="publish-button">
<Navigation style={{ marginRight: '8px' }} /> Publish
</Button>
)
}
private formatJson = () => {
if (this.props.payload) {
try {
const str = JSON.stringify(JSON.parse(this.props.payload), undefined, ' ')
this.updatePayload(str)
} catch (error) {
this.props.globalActions.showError(`Format error: ${error.message}`)
}
}
}
private renderFormatJson() {
if (this.props.editorMode !== 'json') {
return null
}
return (
<Tooltip title="Format JSON">
<Fab
style={{ width: '36px', height: '36px', marginLeft: '8px' }}
onClick={this.formatJson}
id="sidebar-publish-format-json"
>
<FormatAlignLeft style={{ fontSize: '20px' }} />
</Fab>
</Tooltip>
)
}
private editorMode() {
return (
<div style={{ marginTop: '16px' }}>
<div style={{ width: '100%', lineHeight: '64px' }}>
<EditorModeSelect value={this.props.editorMode} onChange={this.updateMode} />
{this.renderFormatJson()}
<div style={{ float: 'right', marginRight: '16px' }}>{this.publishButton()}</div>
</div>
</div>
)
}
private publishMode() {
const labelStyle = { margin: '0 8px 0 8px' }
return (
<div style={{ marginTop: '8px', clear: 'both' }}>
<div style={{ width: '100%', textAlign: 'right' }}>
<FormControlLabel style={labelStyle} control={<QosSelect />} label="QoS" labelPlacement="start" />
<Tooltip
title="Retained messages only appear to be retained, when client subscribes after the initial publish."
placement="top"
>
<FormControlLabel
value="retain"
style={labelStyle}
control={
<Checkbox color="primary" checked={this.props.retain} onChange={this.props.actions.toggleRetain} />
}
label="retain"
labelPlacement="end"
/>
</Tooltip>
</div>
</div>
)
}
private history() {
const items = this.state.history.reverse().map(message => ({
key: sha1(message.topic + message.payload),
title: message.topic,
value: message.payload || '',
}))
return <History items={items} onClick={this.didSelectHistoryEntry} />
}
private didSelectHistoryEntry = (index: number) => {
const message = this.state.history[index]
this.props.actions.setTopic(message.topic)
this.props.actions.setPayload(message.payload)
}
public render() {
return (
<div style={{ flexGrow: 1, marginLeft: '8px' }}>
{this.topic()}
<div style={{ width: '100%', display: 'block' }}>
{this.editorMode()}
<Editor value={this.props.payload} editorMode={this.props.editorMode} onChange={this.updatePayload} />
{this.publishMode()}
</div>
{this.history()}
</div>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(publishActions, dispatch),
globalActions: bindActionCreators(globalActions, dispatch),
}
}
const mapStateToProps = (state: AppState) => {
return {
topic: state.publish.topic,
payload: state.publish.payload,
editorMode: state.publish.editorMode,
retain: state.publish.retain,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(withTheme(Publish))
@@ -1,75 +0,0 @@
import * as React from 'react'
import { TextField, MenuItem, Tooltip } from '@material-ui/core'
import { connect } from 'react-redux'
import { AppState } from '../../../reducers'
import { bindActionCreators } from 'redux'
import { publishActions } from '../../../actions'
interface Props {
qos: 0 | 1 | 2
actions: {
publish: typeof publishActions
}
}
function QosSelect(props: Props) {
const tooltipStyle = { textAlign: 'center' as 'center', width: '100%' }
const itemStyle = { padding: '0' }
const onChangeQos = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
const value = parseInt(event.target.value, 10)
if (value !== 0 && value !== 1 && value !== 2) {
return
}
props.actions.publish.setQoS(value)
},
[props.actions.publish]
)
return (
<TextField
select={true}
value={props.qos}
margin="normal"
style={{ margin: '8px 0 8px 8px' }}
onChange={onChangeQos}
>
<MenuItem key={0} value={0} style={itemStyle}>
<Tooltip title="At most once">
<div style={tooltipStyle}>0</div>
</Tooltip>
</MenuItem>
<MenuItem key={1} value={1} style={itemStyle}>
<Tooltip title="At least once">
<div style={tooltipStyle}>1</div>
</Tooltip>
</MenuItem>
<MenuItem key={2} value={2} style={itemStyle}>
<Tooltip title="Exactly once">
<div style={tooltipStyle}>2</div>
</Tooltip>
</MenuItem>
</TextField>
)
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
publish: bindActionCreators(publishActions, dispatch),
},
}
}
const mapStateToProps = (state: AppState) => {
return {
qos: state.publish.qos,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(QosSelect)
-209
View File
@@ -1,209 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import Copy from '../helper/Copy'
import CustomIconButton from '../helper/CustomIconButton'
import Delete from '@material-ui/icons/Delete'
import ExpandMore from '@material-ui/icons/ExpandMore'
import NodeStats from './NodeStats'
import Topic from './Topic'
import ValuePanel from './ValueRenderer/ValuePanel'
import { AppState } from '../../reducers'
import { Badge, ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography } from '@material-ui/core'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { settingsActions, sidebarActions } from '../../actions'
import { Theme, withStyles } from '@material-ui/core/styles'
import { TopicViewModel } from '../../model/TopicViewModel'
const throttle = require('lodash.throttle')
const Publish = React.lazy(() => import('./Publish/Publish'))
interface Props {
node?: q.TreeNode<TopicViewModel>
actions: typeof sidebarActions
settingsActions: typeof settingsActions
classes: any
connectionId?: string
}
interface State {
compareMessage?: q.Message
valueRenderWidth: number
}
class Sidebar extends React.Component<Props, State> {
private updateNode = throttle(() => {
this.setState(this.state)
}, 300)
private detailsStyle = { padding: '0px 16px 8px 8px', display: 'block' }
constructor(props: any) {
super(props)
this.state = { valueRenderWidth: 300 }
}
private registerUpdateListener(node: q.TreeNode<TopicViewModel>) {
node.onMerge.subscribe(this.updateNode)
node.onMessage.subscribe(this.updateNode)
}
private removeUpdateListener(node: q.TreeNode<TopicViewModel>) {
node.onMerge.unsubscribe(this.updateNode)
node.onMessage.unsubscribe(this.updateNode)
}
private renderTopicDeleteButton() {
if (!this.props.node || (!this.props.node.message || !this.props.node.message.value)) {
return null
}
return (
<CustomIconButton onClick={() => this.deleteTopic(this.props.node)} tooltip="Clear this topic">
<Delete style={{ marginTop: '-3px' }} />
</CustomIconButton>
)
}
private renderRecursiveTopicDeleteButton() {
const deleteLimit = 50
const topicCount = this.props.node ? this.props.node.childTopicCount() : 0
if (!this.props.node || topicCount === 0 || (this.props.node.message && topicCount === 1)) {
return null
}
return (
<Badge
classes={{ badge: this.props.classes.badge }}
badgeContent={<span style={{ whiteSpace: 'nowrap' }}>{topicCount >= deleteLimit ? '50+' : topicCount}</span>}
color="secondary"
>
<CustomIconButton
onClick={() => this.deleteTopic(this.props.node, true, deleteLimit)}
tooltip={`Deletes up to ${deleteLimit} sub-topics with a single click`}
>
<Delete style={{ marginTop: '-3px' }} color="action" />
</CustomIconButton>
</Badge>
)
}
private deleteTopic = (topic?: q.TreeNode<TopicViewModel>, recursive: boolean = false, maxCount = 50) => {
if (!topic) {
return
}
this.props.actions.clearTopic(topic, recursive, maxCount)
}
private renderNode() {
const { classes, node } = this.props
const copyTopic = node ? <Copy value={node.path()} /> : null
const deleteTopic = this.renderTopicDeleteButton()
const deleteRecursiveTopic = this.renderRecursiveTopicDeleteButton()
const summaryStyle = { minHeight: '0' }
return (
<div>
<ExpansionPanel key="topic" defaultExpanded={true} disabled={!Boolean(this.props.node)}>
<ExpansionPanelSummary expandIcon={<ExpandMore />} style={summaryStyle}>
<Typography className={classes.heading}>
Topic {copyTopic} {deleteTopic} {deleteRecursiveTopic}
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails style={this.detailsStyle}>
<Topic node={this.props.node} didSelectNode={this.updateNode} />
</ExpansionPanelDetails>
</ExpansionPanel>
<ValuePanel lastUpdate={this.props.node ? this.props.node.lastUpdate : 0} />
<ExpansionPanel defaultExpanded={true}>
<ExpansionPanelSummary expandIcon={<ExpandMore />} style={summaryStyle}>
<Typography className={classes.heading}>Publish</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails style={this.detailsStyle}>
<React.Suspense fallback={<div>Loading...</div>}>
<Publish connectionId={this.props.connectionId} />
</React.Suspense>
</ExpansionPanelDetails>
</ExpansionPanel>
<ExpansionPanel defaultExpanded={Boolean(this.props.node)}>
<ExpansionPanelSummary expandIcon={<ExpandMore />} style={summaryStyle}>
<Typography className={classes.heading}>Stats</Typography>
</ExpansionPanelSummary>
{this.renderNodeStats()}
</ExpansionPanel>
</div>
)
}
private renderNodeStats() {
if (!this.props.node) {
return null
}
return (
<ExpansionPanelDetails style={this.detailsStyle}>
<NodeStats node={this.props.node} />
</ExpansionPanelDetails>
)
}
public componentWillReceiveProps(nextProps: Props) {
this.props.node && this.removeUpdateListener(this.props.node)
nextProps.node && this.registerUpdateListener(nextProps.node)
if (this.props.node !== nextProps.node) {
this.setState({ compareMessage: undefined })
}
}
public componentWillUnmount() {
this.props.node && this.removeUpdateListener(this.props.node)
}
public render() {
return (
<div id="Sidebar" className={this.props.classes.drawer}>
{this.renderNode()}
</div>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
node: state.tree.get('selectedTopic'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(sidebarActions, dispatch),
settingsActions: bindActionCreators(settingsActions, dispatch),
}
}
const styles = (theme: Theme) => ({
drawer: {
display: 'block' as 'block',
},
badge: {
top: '3px',
right: '3px',
},
valuePaper: {
margin: theme.spacing(1),
},
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
})
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(Sidebar)
)
-73
View File
@@ -1,73 +0,0 @@
import * as React from 'react'
import * as q from '../../../../backend/src/Model'
import Button from '@material-ui/core/Button'
import { withStyles, Theme } from '@material-ui/core/styles'
import { treeActions } from '../../actions'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { TopicViewModel } from '../../model/TopicViewModel'
interface Props {
classes: any
theme: Theme
node?: q.TreeNode<TopicViewModel>
selected?: q.TreeNode<TopicViewModel>
actions: typeof treeActions
didSelectNode: (node: q.TreeNode<TopicViewModel>) => void
}
const styles = (theme: Theme) => ({
button: {
textTransform: 'none' as 'none',
padding: '3px 5px 3px 5px',
minWidth: '30px',
},
})
class Topic extends React.Component<Props, {}> {
public render() {
const { node, theme } = this.props
if (!node) {
return null
}
let key = 0
const breadCrumps = node
.branch()
.map(node => node.sourceEdge)
.filter(edge => Boolean(edge))
.map(edge => [
<Button
onClick={() => this.props.actions.selectTopic(edge!.target)}
size="small"
variant={theme.palette.type === 'light' ? 'contained' : undefined}
color={theme.palette.type === 'light' ? 'primary' : 'secondary'}
className={this.props.classes.button}
key={edge!.hash()}
>
{edge!.name || <span dangerouslySetInnerHTML={{ __html: '&nbsp;' }} />}
</Button>,
])
if (breadCrumps.length === 0) {
return null
}
const joinedBreadCrumps = breadCrumps.reduce((prev, current) =>
prev.concat([<span key={(key += 1)}> / </span>]).concat(current)
)
return <span style={{ lineHeight: '2.2em' }}>{joinedBreadCrumps}</span>
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(treeActions, dispatch),
}
}
export default connect(
null,
mapDispatchToProps
)(withStyles(styles, { withTheme: true })(Topic))
@@ -1,131 +0,0 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import ShowChart from '@material-ui/icons/ShowChart'
import Copy from '../../helper/Copy'
import DateFormatter from '../../helper/DateFormatter'
import History from '../HistoryDrawer'
import TopicPlot from '../../TopicPlot'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { isPlottable } from '../CodeDiff/util'
import { TopicViewModel } from '../../../model/TopicViewModel'
import { bindActionCreators } from 'redux'
import { chartActions } from '../../../actions'
import { connect } from 'react-redux'
const throttle = require('lodash.throttle')
interface Props {
node?: q.TreeNode<TopicViewModel>
selected?: q.Message
onSelect: (message: q.Message) => void
actions: {
charts: typeof chartActions
}
}
interface State {
displayMessage?: q.Message
anchorEl?: HTMLElement
}
class MessageHistory extends React.Component<Props, State> {
private updateNode = throttle(() => {
this.setState(this.state)
}, 300)
constructor(props: any) {
super(props)
this.state = {}
}
private addNodeToCharts = (event: React.MouseEvent) => {
event.preventDefault()
event.stopPropagation()
const { node } = this.props
if (!node) {
return null
}
this.props.actions.charts.addChart({ topic: node.path() })
}
private displayMessage = (index: number, eventTarget: EventTarget) => {
const message = this.props.node && this.props.node.messageHistory.toArray().reverse()[index]
if (message) {
this.props.onSelect(message)
}
}
public componentWillReceiveProps(nextProps: Props) {
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
nextProps.node && nextProps.node.onMessage.subscribe(this.updateNode)
}
public componentDidMount() {
this.props.node && this.props.node.onMessage.subscribe(this.updateNode)
}
public componentWillUnMount() {
this.props.node && this.props.node.onMessage.unsubscribe(this.updateNode)
}
public render() {
const { node } = this.props
if (!node) {
return null
}
const history = node.messageHistory.toArray()
let previousMessage: q.Message | undefined = node.message
const historyElements = history.reverse().map((message, idx) => {
const value = message.value ? Base64Message.toUnicodeString(message.value) : ''
const element = {
value,
key: `${message.messageNumber}-${message.received}`,
title: (
<span>
<DateFormatter date={message.received} />
{previousMessage && previousMessage !== message ? (
<i>
(-
<DateFormatter date={message.received} intervalSince={previousMessage.received} />)
</i>
) : null}
<div style={{ float: 'right' }}>
<Copy value={value} />
</div>
</span>
),
selected: message && message === this.props.selected,
}
previousMessage = message
return element
})
const isMessagePlottable =
node.message && node.message.value && isPlottable(Base64Message.toUnicodeString(node.message.value))
return (
<div>
<History
items={historyElements}
contentTypeIndicator={isMessagePlottable ? <ShowChart onClick={this.addNodeToCharts} /> : undefined}
onClick={this.displayMessage}
>
{isMessagePlottable ? <TopicPlot history={node.messageHistory} /> : null}
</History>
</div>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: { charts: bindActionCreators(chartActions, dispatch) },
}
}
export default connect(
null,
mapDispatchToProps
)(MessageHistory)
@@ -1,215 +0,0 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import Clear from '@material-ui/icons/Clear'
import Code from '@material-ui/icons/Code'
import Copy from '../../helper/Copy'
import DateFormatter from '../../helper/DateFormatter'
import ExpandMore from '@material-ui/icons/ExpandMore'
import MessageHistory from './MessageHistory'
import Reorder from '@material-ui/icons/Reorder'
import ToggleButton from '@material-ui/lab/ToggleButton'
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup'
import ValueRenderer from './ValueRenderer'
import { AppState } from '../../../reducers'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { settingsActions, sidebarActions } from '../../../actions'
import { ValueRendererDisplayMode } from '../../../reducers/Settings'
import {
Button,
ExpansionPanel,
ExpansionPanelDetails,
ExpansionPanelSummary,
Tooltip,
Typography,
StyleRulesCallback,
withStyles,
Theme,
} from '@material-ui/core'
interface Props {
node?: q.TreeNode<any>
valueRendererDisplayMode: ValueRendererDisplayMode
sidebarActions: typeof sidebarActions
settingsActions: typeof settingsActions
classes: any
lastUpdate: number
compareMessage?: q.Message
}
interface State {}
class ValuePanel extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {}
}
private renderValue() {
const node = this.props.node
if (!node || !node.message) {
return null
}
return <ValueRenderer treeNode={node} message={node.message} compareWith={this.props.compareMessage} />
}
private renderViewOptions() {
if (!this.props.node || !this.props.node.message || !this.props.node.mqttMessage) {
return null
}
const retainedButton = (
<Tooltip title="Delete retained topic" placement="top">
<Button
size="small"
color="secondary"
variant="contained"
style={{ marginTop: '11px', padding: '0px 4px', minHeight: '24px' }}
onClick={this.props.sidebarActions.clearRetainedTopic}
>
retained <Clear style={{ fontSize: '16px', marginLeft: '2px' }} />
</Button>
</Tooltip>
)
return (
<div style={{ width: '100%', display: 'flex', paddingLeft: '8px' }}>
<span style={{ marginTop: '2px', flexGrow: 1 }}>{this.renderActionButtons()}</span>
<div style={{ flex: 6, textAlign: 'right' }}>{this.props.node.mqttMessage.retain ? retainedButton : null}</div>
{this.messageMetaInfo()}
</div>
)
}
private messageMetaInfo() {
if (!this.props.node || !this.props.node.message || !this.props.node.mqttMessage) {
return null
}
return (
<span style={{ width: '100%', paddingLeft: '8px', flex: 6 }}>
<Typography style={{ textAlign: 'right' }}>QoS: {this.props.node.mqttMessage.qos}</Typography>
<Typography style={{ textAlign: 'right' }}>
<i>
<DateFormatter date={this.props.node.message.received} />
</i>
</Typography>
</span>
)
}
private renderActionButtons() {
const handleValue = (mouseEvent: React.MouseEvent, value: any) => {
if (value === null) {
return
}
this.props.settingsActions.setValueDisplayMode(value)
}
return (
<ToggleButtonGroup
id="valueRendererDisplayMode"
value={this.props.valueRendererDisplayMode}
exclusive={true}
onChange={handleValue}
>
<ToggleButton className={this.props.classes.toggleButton} value="diff" id="valueRendererDisplayMode-diff">
<Tooltip title="Show difference between the current and the last message">
<span>
<Code className={this.props.classes.toggleButtonIcon} />
</span>
</Tooltip>
</ToggleButton>
<ToggleButton className={this.props.classes.toggleButton} value="raw" id="valueRendererDisplayMode-raw">
<Tooltip title="Raw value">
<span>
<Reorder className={this.props.classes.toggleButtonIcon} />
</span>
</Tooltip>
</ToggleButton>
</ToggleButtonGroup>
)
}
private panelStyle() {
return {
detailsStyle: { padding: '0px 16px 8px 8px', display: 'block' },
summaryStyle: { minHeight: '0' },
}
}
private handleMessageHistorySelect = (message: q.Message) => {
if (message !== this.props.compareMessage) {
this.props.sidebarActions.setCompareMessage(message)
} else {
this.props.sidebarActions.setCompareMessage(undefined)
}
}
public render() {
const { node, classes } = this.props
const { detailsStyle, summaryStyle } = this.panelStyle()
const copyValue =
node && node.message && node.message.value ? (
<Copy value={Base64Message.toUnicodeString(node.message.value)} />
) : null
return (
<ExpansionPanel key="value" defaultExpanded={true}>
<ExpansionPanelSummary expandIcon={<ExpandMore />} style={summaryStyle}>
<Typography className={classes.heading}>Value {copyValue}</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails style={detailsStyle}>
{this.renderViewOptions()}
<div>
<React.Suspense fallback={<div>Loading...</div>}>{this.renderValue()}</React.Suspense>
</div>
<div>
<MessageHistory
onSelect={this.handleMessageHistorySelect}
selected={this.props.compareMessage}
node={this.props.node}
/>
</div>
</ExpansionPanelDetails>
</ExpansionPanel>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
sidebarActions: bindActionCreators(sidebarActions, dispatch),
settingsActions: bindActionCreators(settingsActions, dispatch),
}
}
const mapStateToProps = (state: AppState) => {
return {
valueRendererDisplayMode: state.settings.get('valueRendererDisplayMode'),
node: state.tree.get('selectedTopic'),
compareMessage: state.sidebar.get('compareMessage'),
}
}
const styles = (theme: Theme) => ({
heading: {
fontSize: theme.typography.pxToRem(15),
fontWeight: theme.typography.fontWeightRegular,
},
toggleButton: {
height: '36px',
},
toggleButtonIcon: {
verticalAlign: 'middle',
},
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(ValuePanel))
@@ -1,112 +0,0 @@
import * as q from '../../../../../backend/src/Model'
import * as React from 'react'
import CodeDiff from '../CodeDiff'
import { AppState } from '../../../reducers'
import { Base64Message } from '../../../../../backend/src/Model/Base64Message'
import { connect } from 'react-redux'
import { default as ReactResizeDetector } from 'react-resize-detector'
import { ValueRendererDisplayMode } from '../../../reducers/Settings'
interface Props {
message: q.Message
treeNode: q.TreeNode<any>
compareWith?: q.Message
renderMode: ValueRendererDisplayMode
}
interface State {
width: number
}
class ValueRenderer extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { width: 0 }
}
private renderDiff(current: string = '', previous: string = '', language?: 'json') {
return (
<CodeDiff
treeNode={this.props.treeNode}
previous={previous}
current={current}
language={language}
nameOfCompareMessage={this.props.compareWith ? 'selected' : 'previous'}
/>
)
}
private messageToPrettyJson(str: string): string | undefined {
try {
const json = JSON.parse(str)
return JSON.stringify(json, undefined, ' ')
} catch {
return undefined
}
}
private updateWidth = (width: number) => {
if (width !== this.state.width) {
this.setState({ width })
}
}
private renderRawValue(value: string, compare: string) {
return this.renderDiff(value, compare)
}
public render() {
return (
<div style={{ padding: '0px 0px 8px 8px' }}>
<ReactResizeDetector handleWidth={true} onResize={this.updateWidth} />
{this.renderValue()}
</div>
)
}
public renderValue() {
const { message, treeNode, compareWith, renderMode } = this.props
const previousMessages = treeNode.messageHistory.toArray()
const previousMessage = previousMessages[previousMessages.length - 2]
let compareMessage = compareWith || previousMessage || message
if (renderMode === 'raw') {
compareMessage = message
}
if (!message.value) {
return null
}
const compareValue = compareMessage.value || message.value
const str = Base64Message.toUnicodeString(message.value)
const compareStr = Base64Message.toUnicodeString(compareValue)
let json
try {
json = JSON.parse(str)
} catch (error) {
return this.renderRawValue(str, compareStr)
}
if (typeof json === 'string') {
return this.renderRawValue(str, compareStr)
} else if (typeof json === 'number') {
return this.renderRawValue(str, compareStr)
} else if (typeof json === 'boolean') {
return this.renderRawValue(str, compareStr)
} else {
const current = this.messageToPrettyJson(str) || str
const compare = this.messageToPrettyJson(compareStr) || compareStr
const language = current && compare ? 'json' : undefined
return this.renderDiff(current, compare, language)
}
}
}
const mapStateToProps = (state: AppState) => {
return {
renderMode: state.settings.get('valueRendererDisplayMode'),
}
}
export default connect(mapStateToProps)(ValueRenderer)
-3
View File
@@ -1,3 +0,0 @@
import Sidebar from './Sidebar'
export { Sidebar }
-47
View File
@@ -1,47 +0,0 @@
import * as dotProp from 'dot-prop'
import * as q from '../../../backend/src/Model'
import * as React from 'react'
import PlotHistory from './Sidebar/PlotHistory'
import { Base64Message } from '../../../backend/src/Model/Base64Message'
import { toPlottableValue } from './Sidebar/CodeDiff/util'
import { PlotCurveTypes } from '../reducers/Charts'
interface Props {
history: q.MessageHistory
dotPath?: string
interpolation?: PlotCurveTypes
range?: [number?, number?]
}
function nodeToHistory(history: q.MessageHistory) {
return history
.toArray()
.map((message: q.Message) => {
const value = message.value ? toPlottableValue(Base64Message.toUnicodeString(message.value)) : NaN
return { x: message.received.getTime(), y: toPlottableValue(value) }
})
.filter(data => !isNaN(data.y as any)) as any
}
function nodeDotPathToHistory(history: q.MessageHistory, dotPath: string) {
return history
.toArray()
.map((message: q.Message) => {
let json = {}
try {
json = message.value ? JSON.parse(Base64Message.toUnicodeString(message.value)) : {}
} catch (ignore) {}
let value = dotProp.get(json, dotPath)
return { x: message.received.getTime(), y: toPlottableValue(value) }
})
.filter(data => !isNaN(data.y as any)) as any
}
function render(props: Props) {
const data = props.dotPath ? nodeDotPathToHistory(props.history, props.dotPath) : nodeToHistory(props.history)
return <PlotHistory range={props.range} interpolation={props.interpolation} data={data} />
}
export default render
-153
View File
@@ -1,153 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import TreeNode from './TreeNode'
import { AppState } from '../../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Record } from 'immutable'
import { SettingsState } from '../../reducers/Settings'
import { TopicViewModel } from '../../model/TopicViewModel'
import { treeActions } from '../../actions'
const MovingAverage = require('moving-average')
const averagingTimeInterval = 10 * 1000
const average = MovingAverage(averagingTimeInterval)
declare var window: any
interface Props {
actions: typeof treeActions
connectionId?: string
tree?: q.Tree<TopicViewModel>
filter: string
host?: string
paused: boolean
settings: Record<SettingsState>
}
interface State {
lastUpdate: number
}
class TreeComponent extends React.PureComponent<Props, State> {
private updateTimer?: any
private perf: number = 0
private renderTime = 0
constructor(props: any) {
super(props)
this.state = { lastUpdate: 0 }
}
private performanceCallback = (ms: number) => {
average.push(Date.now(), ms)
}
public time(): number {
const time = performance.now() - this.perf
this.perf = performance.now()
return time
}
public componentWillReceiveProps(nextProps: Props) {
if (this.props.tree !== nextProps.tree) {
if (this.props.tree) {
this.props.tree.didReceive.unsubscribe(this.throttledTreeUpdate)
}
if (nextProps.tree) {
nextProps.tree.didReceive.subscribe(this.throttledTreeUpdate)
}
this.setState(this.state)
}
}
public componentWillUnmount() {
this.props.tree && this.props.tree.didReceive.unsubscribe(this.throttledTreeUpdate)
}
public throttledTreeUpdate = () => {
if (this.updateTimer) {
return
}
const expectedRenderTime = average.forecast()
const updateInterval = Math.max(expectedRenderTime * 7, 300)
const timeUntilNextUpdate = updateInterval - (performance.now() - this.renderTime)
this.updateTimer = setTimeout(() => {
window.requestIdleCallback(
() => {
this.updateTimer && clearTimeout(this.updateTimer)
this.updateTimer = undefined
this.renderTime = performance.now()
if (!this.props.paused) {
this.props.tree && this.props.tree.applyUnmergedChanges()
}
window.requestIdleCallback(
() => {
this.setState({ lastUpdate: this.renderTime })
},
{ timeout: 100 }
)
},
{ timeout: 500 }
)
}, Math.max(0, timeUntilNextUpdate))
}
public render() {
const { tree, filter } = this.props
if (!tree) {
return null
}
const style: React.CSSProperties = {
lineHeight: '1.1',
cursor: 'default',
overflowY: 'scroll',
overflowX: 'hidden',
height: '100%',
paddingBottom: '16px', // avoid conflict with chart panel Resizer
}
return (
<div style={style}>
<TreeNode
key={tree.hash()}
isRoot={true}
treeNode={tree}
name={this.props.host}
collapsed={false}
performanceCallback={this.performanceCallback}
settings={this.props.settings}
lastUpdate={tree.lastUpdate}
didSelectTopic={this.props.actions.selectTopic}
/>
</div>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
tree: state.tree.get('tree'),
paused: state.tree.get('paused'),
filter: state.tree.get('filter'),
host: state.connection.host,
settings: state.settings,
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(treeActions, dispatch),
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(TreeComponent)
-255
View File
@@ -1,255 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import TreeNodeSubnodes from './TreeNodeSubnodes'
import TreeNodeTitle from './TreeNodeTitle'
import { Record } from 'immutable'
import { SettingsState } from '../../reducers/Settings'
import { Theme, withStyles } from '@material-ui/core/styles'
import { TopicViewModel } from '../../model/TopicViewModel'
const debounce = require('lodash.debounce')
declare var performance: any
const styles = (theme: Theme) => {
return {
collapsedSubnodes: {
color: theme.palette.text.secondary,
},
displayBlock: {
display: 'block',
},
node: {
display: 'block',
marginLeft: '10px',
},
topicSelect: {
float: 'right' as 'right',
opacity: 0,
cursor: 'pointer',
marginTop: '-1px',
},
subnodes: {
marginLeft: theme.spacing(1.5),
},
selected: {
backgroundColor: theme.palette.type === 'dark' ? 'rgba(170, 170, 170, 0.55)' : 'rgba(170, 170, 170, 0.55)',
},
hover: {
backgroundColor: theme.palette.type === 'dark' ? 'rgba(100, 100, 100, 0.55)' : 'rgba(200, 200, 200, 0.55)',
},
title: {
borderRadius: '4px',
lineHeight: '1em',
display: 'inline-block' as 'inline-block',
whiteSpace: 'nowrap' as 'nowrap',
padding: '1px 4px 0px 4px',
height: '14px',
margin: '1px 0px 2px 0px',
},
}
}
interface Props {
isRoot?: boolean
treeNode: q.TreeNode<TopicViewModel>
name?: string | undefined
collapsed?: boolean | undefined
performanceCallback?: ((ms: number) => void) | undefined
classes: any
className?: string
lastUpdate: number
didSelectTopic: any
theme: Theme
settings: Record<SettingsState>
}
interface State {
collapsedOverride: boolean | undefined
mouseOver: boolean
selected: boolean
}
class TreeNodeComponent extends React.Component<Props, State> {
private animationDirty: boolean = false
private cssAnimationWasSetAt?: number
private willUpdateTime: number = performance.now()
private nodeRef?: React.RefObject<HTMLDivElement> = React.createRef<HTMLDivElement>()
private setHover = debounce((hover: boolean) => {
this.setState({ mouseOver: hover })
}, 45)
constructor(props: Props) {
super(props)
this.state = {
collapsedOverride: props.collapsed,
mouseOver: false,
selected: false,
}
}
private addSubscriber(treeNode: q.TreeNode<TopicViewModel>) {
treeNode.viewModel = new TopicViewModel()
treeNode.viewModel.change.subscribe(this.viewStateHasChanged)
}
private viewStateHasChanged = () => {
this.props.treeNode.viewModel && this.setState({ selected: this.props.treeNode.viewModel.isSelected() })
}
private removeSubscriber(treeNode: q.TreeNode<TopicViewModel>) {
treeNode.viewModel && treeNode.viewModel.change.unsubscribe(this.viewStateHasChanged)
treeNode.viewModel = undefined
}
private stateHasChanged(newState: State) {
return (
this.state.collapsedOverride !== newState.collapsedOverride ||
this.state.mouseOver !== newState.mouseOver ||
this.state.selected !== newState.selected
)
}
private toggle() {
this.setState({ collapsedOverride: !this.collapsed() })
}
private collapsed() {
if (this.state.collapsedOverride !== undefined) {
return this.state.collapsedOverride
}
return this.props.treeNode.edgeCount() > this.props.settings.get('autoExpandLimit')
}
private didSelectTopic = () => {
this.props.didSelectTopic(this.props.treeNode)
}
private didClickTitle = (event: React.MouseEvent) => {
event.preventDefault()
this.props.didSelectTopic(this.props.treeNode)
this.toggle()
}
private mouseOver = (event: React.MouseEvent) => {
event.stopPropagation()
this.setHover(true)
if (
this.props.settings.get('selectTopicWithMouseOver') &&
this.props.treeNode &&
this.props.treeNode.message &&
this.props.treeNode.message.value
) {
this.props.didSelectTopic(this.props.treeNode)
}
}
private mouseOut = (event: React.MouseEvent) => {
event.stopPropagation()
this.setHover(false)
}
private toggleCollapsed = (event: React.MouseEvent) => {
event.stopPropagation()
this.toggle()
}
private renderNodes() {
if (this.collapsed()) {
return null
}
return (
<TreeNodeSubnodes
collapsed={this.collapsed()}
treeNode={this.props.treeNode}
lastUpdate={this.props.treeNode.lastUpdate}
didSelectTopic={this.props.didSelectTopic}
settings={this.props.settings}
/>
)
}
public componentDidMount() {
const { treeNode } = this.props
this.addSubscriber(treeNode)
}
public componentWillUnmount() {
const { treeNode } = this.props
this.removeSubscriber(treeNode)
this.nodeRef = undefined
}
public shouldComponentUpdate(nextProps: Props, nextState: State) {
const shouldRenderToRemoveCssAnimation = this.cssAnimationWasSetAt !== undefined
return (
this.stateHasChanged(nextState) ||
this.props.settings !== nextProps.settings ||
this.props.lastUpdate !== nextProps.lastUpdate ||
this.animationDirty ||
shouldRenderToRemoveCssAnimation
)
}
public componentDidUpdate() {
if (this.props.performanceCallback) {
const renderTime = performance.now() - this.willUpdateTime
this.props.performanceCallback(renderTime)
}
}
public componentWillUpdate() {
if (this.props.performanceCallback) {
this.willUpdateTime = performance.now()
}
}
public render() {
const { classes } = this.props
const shouldStartAnimation =
!this.animationDirty && !this.props.isRoot && this.props.settings.get('highlightTopicUpdates')
const animationName = this.props.theme.palette.type === 'light' ? 'updateLight' : 'updateDark'
const animation = shouldStartAnimation
? { willChange: 'auto', translateZ: 0, animation: `${animationName} 0.5s` }
: {}
this.animationDirty = shouldStartAnimation
const highlightClass = this.state.selected
? this.props.classes.selected
: this.state.mouseOver
? this.props.classes.hover
: ''
return (
<div>
<div
key={this.props.treeNode.hash()}
className={`${classes.node} ${this.props.className} ${highlightClass} ${classes.title}`}
style={animation}
onMouseOver={this.mouseOver}
onMouseOut={this.mouseOut}
onClick={this.didClickTitle}
ref={this.nodeRef}
>
<TreeNodeTitle
toggleCollapsed={this.toggleCollapsed}
didSelectNode={this.didSelectTopic}
collapsed={this.collapsed()}
treeNode={this.props.treeNode}
name={this.props.name}
/>
</div>
{this.renderNodes()}
</div>
)
}
}
export default withStyles(styles, { withTheme: true })(TreeNodeComponent)
@@ -1,100 +0,0 @@
import * as q from '../../../../backend/src/Model'
import * as React from 'react'
import TreeNode from './TreeNode'
import { Record } from 'immutable'
import { SettingsState, TopicOrder } from '../../reducers/Settings'
import { Theme, withStyles } from '@material-ui/core'
import { TopicViewModel } from '../../model/TopicViewModel'
export interface Props {
treeNode: q.TreeNode<TopicViewModel>
filter?: string
collapsed?: boolean | undefined
classes: any
lastUpdate: number
selectedTopic?: q.TreeNode<TopicViewModel>
didSelectTopic: any
settings: Record<SettingsState>
}
interface State {
alreadyAdded: number
}
class TreeNodeSubnodes extends React.Component<Props, State> {
private renderMoreAnimationFrame?: any
constructor(props: Props) {
super(props)
this.state = { alreadyAdded: 10 }
}
private sortedNodes(): Array<q.TreeNode<TopicViewModel>> {
const { settings, treeNode } = this.props
const topicOrder = settings.get('topicOrder')
let edges = treeNode.edgeArray
if (topicOrder === TopicOrder.abc) {
edges = edges.sort((a, b) => a.name.localeCompare(b.name))
}
let nodes = edges.map(edge => edge.target)
if (topicOrder === TopicOrder.messages) {
nodes = nodes.sort((a, b) => b.leafMessageCount() - a.leafMessageCount())
}
if (topicOrder === TopicOrder.topics) {
nodes = nodes.sort((a, b) => b.childTopicCount() - a.childTopicCount())
}
return nodes
}
private renderMore() {
this.renderMoreAnimationFrame = (window as any).requestIdleCallback(
() => {
this.setState({ ...this.state, alreadyAdded: this.state.alreadyAdded * 1.5 })
},
{ timeout: 500 }
)
}
public componentWillUnmount() {
;(window as any).cancelIdleCallback(this.renderMoreAnimationFrame)
}
public render() {
const edges = this.props.treeNode.edgeArray
if (edges.length === 0 || this.props.collapsed) {
return null
}
if (this.state.alreadyAdded < edges.length) {
this.renderMore()
}
const nodes = this.sortedNodes().slice(0, this.state.alreadyAdded)
const listItems = nodes.map(node => {
return (
<TreeNode
key={`${node.hash()}-${this.props.filter}`}
treeNode={node}
className={this.props.classes.listItem}
lastUpdate={node.lastUpdate}
didSelectTopic={this.props.didSelectTopic}
settings={this.props.settings}
/>
)
})
return <span className={this.props.classes.list}>{listItems}</span>
}
}
const styles = (theme: Theme) => ({
list: {
display: 'block' as 'block',
clear: 'both' as 'both',
marginLeft: theme.spacing(1.5),
},
})
export default withStyles(styles)(TreeNodeSubnodes)
-92
View File
@@ -1,92 +0,0 @@
import * as React from 'react'
import * as q from '../../../../backend/src/Model'
import { withStyles, Theme } from '@material-ui/core'
import { TopicViewModel } from '../../model/TopicViewModel'
import { Base64Message } from '../../../../backend/src/Model/Base64Message'
export interface TreeNodeProps extends React.HTMLAttributes<HTMLElement> {
treeNode: q.TreeNode<TopicViewModel>
name?: string | undefined
collapsed?: boolean | undefined
didSelectNode: any
toggleCollapsed: any
classes: any
}
class TreeNodeTitle extends React.Component<TreeNodeProps, {}> {
private renderSourceEdge() {
const name = this.props.name || (this.props.treeNode.sourceEdge && this.props.treeNode.sourceEdge.name)
return (
<span key="edge" className={this.props.classes.sourceEdge}>
{name}
</span>
)
}
private renderValue() {
return this.props.treeNode.message &&
this.props.treeNode.message.value &&
this.props.treeNode.message.length > 0 ? (
<span key="value" className={this.props.classes.value}>
{' '}
= {Base64Message.toUnicodeString(this.props.treeNode.message.value).slice(0, 120)}
</span>
) : null
}
private renderExpander() {
if (this.props.treeNode.edgeCount() === 0) {
return null
}
return (
<span key="expander" className={this.props.classes.expander} onClick={this.props.toggleCollapsed}>
{this.props.collapsed ? '▶' : '▼'}
</span>
)
}
private renderMetadata() {
if (this.props.treeNode.edgeCount() === 0 || !this.props.collapsed) {
return null
}
const messages = this.props.treeNode.leafMessageCount()
return (
<span
key="metadata"
className={this.props.classes.collapsedSubnodes}
>{`(${this.props.treeNode.childTopicCount()} topics, ${messages} messages)`}</span>
)
}
public render() {
return [this.renderExpander(), this.renderSourceEdge(), this.renderMetadata(), this.renderValue()]
}
}
const styles = (theme: Theme) => ({
value: {
whiteSpace: 'nowrap' as 'nowrap',
overflow: 'hidden' as 'hidden',
textOverflow: 'ellipsis' as 'ellipsis',
padding: '0',
},
sourceEdge: {
fontWeight: 'bold' as 'bold',
overflow: 'hidden' as 'hidden',
},
expander: {
color: theme.palette.type === 'light' ? '#222' : '#eee',
cursor: 'pointer' as 'pointer',
paddingRight: theme.spacing(0.25),
userSelect: 'none' as 'none',
},
collapsedSubnodes: {
color: theme.palette.text.secondary,
userSelect: 'none' as 'none',
},
})
export default withStyles(styles)(TreeNodeTitle)
-274
View File
@@ -1,274 +0,0 @@
import * as compareVersions from 'compare-versions'
import * as electron from 'electron'
import * as os from 'os'
import * as React from 'react'
import axios from 'axios'
import Close from '@material-ui/icons/Close'
import CloudDownload from '@material-ui/icons/CloudDownload'
import { AppState } from '../reducers'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { green } from '@material-ui/core/colors'
import { Theme, withStyles } from '@material-ui/core/styles'
import { updateNotifierActions } from '../actions'
import { Button, IconButton, Modal, Paper, Snackbar, SnackbarContent, Typography } from '@material-ui/core'
interface Props {
showUpdateNotification: boolean
showUpdateDetails: boolean
classes: any
actions: any
}
interface GithubRelease {
url: string
assets?: Array<GithubAsset>
published_at: string // "2019-01-25T20:14:39Z"
body_html: string
body: string
body_text: string
tag_name: string
prerelease: boolean
}
interface GithubAsset {
id: number
node_id: string
url: string
browser_download_url: string
name: string
label: string
}
interface State {
newerVersions: Array<GithubRelease>
}
class UpdateNotifier extends React.Component<Props, State> {
constructor(props: any) {
super(props)
this.state = { newerVersions: [] }
const ownVersion = electron.remote.app.getVersion()
this.fetchReleases().then(releases => {
const newerVersions = releases
.filter(release => this.allowPrereleaseIfOwnVersionIsBeta(release, ownVersion))
.filter(release => compareVersions(release.tag_name, ownVersion) > 0)
.sort((a, b) => compareVersions(b.tag_name, a.tag_name))
if (newerVersions.length > 0) {
this.setState({ newerVersions })
this.props.actions.showUpdateNotification(true)
}
})
}
private allowPrereleaseIfOwnVersionIsBeta(release: GithubRelease, ownVersion: string) {
const ownVersionIsBeta = !/alpha|beta/.test(ownVersion)
return ownVersionIsBeta || !release.prerelease
}
private async fetchReleases(): Promise<Array<GithubRelease>> {
const res = await axios.get('https://api.github.com/repos/thomasnordquist/mqtt-explorer/releases', {
headers: {
accept: 'application/vnd.github.v3.full+json',
},
})
return res.data as Array<GithubRelease>
}
private onCloseNotification = (event: React.SyntheticEvent<any>, reason: string) => {
if (reason === 'clickaway') {
return
}
this.props.actions.showUpdateNotification(false)
}
private closeNotification = () => {
this.props.actions.showUpdateNotification(false)
}
private showDetails = () => {
this.props.actions.showUpdateNotification(false)
this.props.actions.showUpdateDetails(true)
}
private hideDetails = () => {
this.props.actions.showUpdateDetails(false)
}
private renderUpdateNotification() {
const snackbarAnchor: any = {
vertical: 'top',
horizontal: 'right',
}
return (
<Snackbar
anchorOrigin={snackbarAnchor}
open={this.props.showUpdateNotification}
autoHideDuration={12000}
onClose={this.onCloseNotification}
>
<SnackbarContent
className={this.props.classes.success}
message={`${this.state.newerVersions.length} Update(s) available`}
action={this.notificationActions()}
/>
</Snackbar>
)
}
private notificationActions() {
return [
<Button key="undo" size="small" onClick={this.showDetails}>
Details
</Button>,
<IconButton
key="close"
aria-label="Close"
color="inherit"
className={this.props.classes.close}
onClick={this.closeNotification}
>
<Close />
</IconButton>,
]
}
private renderUpdateDetails() {
const latestUpdate = this.state.newerVersions[0]
if (!latestUpdate) {
return null
}
const releaseNotes = this.state.newerVersions
.map(release => `<p><h3>${release.tag_name}</h3><p/><p>${release.body_html}</p>`)
.join('<hr />')
return (
<Modal open={this.props.showUpdateDetails} disableAutoFocus={true} onClose={this.hideDetails}>
<Paper className={this.props.classes.root}>
<Typography variant="h6" className={this.props.classes.title}>
Version {latestUpdate.tag_name}
</Typography>
<Typography className={this.props.classes.title}>Changelog</Typography>
<div className={this.props.classes.releaseNotes} dangerouslySetInnerHTML={{ __html: releaseNotes }} />
{this.renderDownloads()}
<Button className={this.props.classes.download} onClick={this.openHomePage}>
Github Page
</Button>
<Button className={this.props.classes.closeButton} color="secondary" onClick={this.hideDetails}>
Close
</Button>
</Paper>
</Modal>
)
}
private openHomePage = () => {
this.openUrl('https://mqtt-explorer.com')
}
private openUrl = (url: string) => {
electron.shell.openExternal(url)
}
private assetForCurrentPlatform(asset: GithubAsset) {
let regex: RegExp
if (os.platform() === 'darwin') {
regex = /\.dmg$/
} else if (os.platform() === 'darwin') {
regex = /\.exe$/
} else {
regex = /\.AppImage$/
}
return regex.test(asset.name)
}
private renderDownloads() {
const latestUpdate = this.state.newerVersions[0]
if (!latestUpdate || !latestUpdate.assets) {
return null
}
return latestUpdate.assets.filter(this.assetForCurrentPlatform).map(asset => (
<div>
<Button className={this.props.classes.download} onClick={() => this.openUrl(asset.browser_download_url)}>
<CloudDownload />
&nbsp;{asset.name}
</Button>
</div>
))
}
public render() {
return (
<div>
{this.renderUpdateNotification()}
{this.renderUpdateDetails()}
</div>
)
}
}
const styles = (theme: Theme) => ({
success: {
backgroundColor: green[600],
color: theme.typography.button.color,
},
close: {
padding: '4px',
},
root: {
minWidth: '350px',
maxWidth: '500px',
backgroundColor: theme.palette.background.default,
margin: '20vh auto auto auto',
padding: theme.spacing(2),
outline: 'none',
},
title: {
color: theme.palette.text.primary,
},
releaseNotes: {
overflow: 'auto scroll',
color: theme.palette.text.secondary,
backgroundColor: 'rgba(60, 60, 60, 0.6)',
maxHeight: '28vh',
},
paper: {
padding: theme.spacing(2),
color: theme.palette.text.secondary,
},
download: {
width: '100%',
},
closeButton: {
display: 'block',
margin: '0 0 0 auto',
},
})
const mapStateToProps = (state: AppState) => {
return {
showUpdateNotification: state.globalState.get('showUpdateNotification'),
showUpdateDetails: state.globalState.get('showUpdateDetails'),
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: bindActionCreators(updateNotifierActions, dispatch),
}
}
export default withStyles(styles)(
connect(
mapStateToProps,
mapDispatchToProps
)(UpdateNotifier)
)
@@ -1,30 +0,0 @@
import * as React from 'react'
import Clear from '@material-ui/icons/Clear'
import { IconButton, Theme } from '@material-ui/core'
import { withTheme } from '@material-ui/core/styles'
interface Props {
value?: string
action: any
style?: React.CSSProperties
variant?: 'primary'
theme: Theme
}
/**
* Clear button for text input fields
*/
function ClearAdornment(props: Props) {
if (!props.value) {
return null
}
const color = props.variant === 'primary' ? props.theme.palette.primary.contrastText : undefined
return (
<IconButton style={{ ...props.style, padding: '1px' }} onClick={props.action}>
<Clear style={{ color, fontSize: '16px' }} />
</IconButton>
)
}
export default withTheme(ClearAdornment)
@@ -1,68 +0,0 @@
import * as React from 'react'
import DeviceHubOutlined from '@material-ui/icons/DeviceHubOutlined'
import { AppState } from '../../reducers'
import { connect } from 'react-redux'
import { ConnectionHealth } from '../../reducers/Connection'
import { green, orange, red } from '@material-ui/core/colors'
import { withStyles, Theme } from '@material-ui/core/styles'
import { Tooltip } from '@material-ui/core'
const styles = (theme: Theme) => ({
offline: {
color: red[700],
},
online: {
color: green[400],
},
connecting: {
color: orange[600],
},
icon: {
boxShadow: theme.shadows[2]
.split('),')
.map(s => `inset ${s}`)
.join('),'),
padding: '6px',
borderRadius: '50%',
backgroundColor: '#eee',
width: '35px',
height: '35px',
},
})
interface Props {
classes: any
connected: boolean
health?: ConnectionHealth
withBackground?: boolean
}
class ConnectionHealthIndicator extends React.Component<Props, {}> {
constructor(props: any) {
super(props)
}
public render() {
const { classes, health, connected } = this.props
if (!health || !connected) {
return null
}
return (
<Tooltip title={`Connection health "${health}"`}>
<div style={{ display: 'inherit' }}>
<DeviceHubOutlined className={`${[classes[health]]} ${this.props.withBackground ? classes.icon : ''}`} />
</div>
</Tooltip>
)
}
}
const mapStateToProps = (state: AppState) => {
return {
health: state.connection.health,
connected: state.connection.connected || state.connection.connecting,
}
}
export default connect(mapStateToProps)(withStyles(styles)(ConnectionHealthIndicator))
-69
View File
@@ -1,69 +0,0 @@
import * as React from 'react'
import Check from '@material-ui/icons/Check'
import CustomIconButton from './CustomIconButton'
import FileCopy from '@material-ui/icons/FileCopy'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { globalActions } from '../../actions'
const copy = require('copy-text-to-clipboard')
interface Props {
value: string
actions: {
global: typeof globalActions
}
}
interface State {
didCopy: boolean
}
class Copy extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { didCopy: false }
}
private handleClick = (event: React.MouseEvent) => {
event.stopPropagation()
copy(this.props.value)
this.props.actions.global.showNotification('Copied to clipboard')
this.setState({ didCopy: true })
setTimeout(() => {
this.setState({ didCopy: false })
}, 1500)
}
public render() {
const icon = !this.state.didCopy ? (
<FileCopy fontSize="inherit" />
) : (
<Check fontSize="inherit" style={{ cursor: 'default' }} />
)
return (
<span>
<span style={{ fontSize: '16px' }}>
<CustomIconButton onClick={this.handleClick} tooltip="Copy to clipboard">
{icon}
</CustomIconButton>
</span>
</span>
)
}
}
const mapDispatchToProps = (dispatch: any) => {
return {
actions: {
global: bindActionCreators(globalActions, dispatch),
},
}
}
export default connect(
undefined,
mapDispatchToProps
)(Copy)
@@ -1,44 +0,0 @@
import * as React from 'react'
import { IconButton, Tooltip } from '@material-ui/core'
import { Theme, withStyles } from '@material-ui/core/styles'
interface Props {
onClick: any
tooltip: string
classes: any
}
const styles = (theme: Theme) => ({
button: {
padding: '6px',
fontSize: '1.2em',
width: '32px',
height: '32px',
},
label: {
marginTop: '-2px',
},
})
class CustomIconButton extends React.Component<Props, {}> {
constructor(props: Props) {
super(props)
}
private onClick = (event: React.MouseEvent) => {
event.stopPropagation()
this.props.onClick(event)
}
public render() {
return (
<IconButton className={this.props.classes.button} onClick={this.onClick}>
<Tooltip title={this.props.tooltip} className={this.props.classes.label}>
<span>{this.props.children}</span>
</Tooltip>
</IconButton>
)
}
}
export default withStyles(styles)(CustomIconButton)
@@ -1,66 +0,0 @@
import * as moment from 'moment'
import * as React from 'react'
import { AppState } from '../../reducers'
import { connect } from 'react-redux'
interface Props {
date: Date
overrideLocale?: string
locale?: string
intervalSince?: Date
}
const unitMapping = {
s: 'seconds',
m: 'minutes',
h: 'hours',
}
class DateFormatter extends React.Component<Props, {}> {
private intervalSince(intervalSince: Date) {
const interval = intervalSince.getTime() - this.props.date.getTime()
const unit = this.unitForInterval(interval)
return `${Math.round(moment.duration(interval).as(unit) * 100) / 100} ${unitMapping[unit]}`
}
private legacyDate() {
return `${this.props.date.toLocaleDateString()} ${this.props.date.toLocaleTimeString()}`
}
private localizedDate(locale: string) {
return moment(this.props.date)
.locale(locale)
.format('L LTS')
}
private unitForInterval(milliseconds: number) {
const oneMinute = 1000 * 60
const oneHour = oneMinute * 60
if (milliseconds > oneHour * 2) {
return 'h'
}
if (milliseconds > oneMinute * 2) {
return 'm'
}
return 's'
}
public render() {
const locale = this.props.overrideLocale || this.props.locale
if (this.props.intervalSince) {
return <span>{this.intervalSince(this.props.intervalSince)}</span>
}
return <span>{locale ? this.localizedDate(locale) : this.legacyDate()}</span>
}
}
const mapStateToProps = (state: AppState) => {
return {
locale: state.settings.get('timeLocale'),
}
}
export default connect(mapStateToProps)(DateFormatter)
@@ -1,12 +0,0 @@
declare const window: any
declare const document: any
export function isElementInViewport(el: any) {
const rect = el.getBoundingClientRect()
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) /*or $(window).height() */ &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
)
}
-39
View File
@@ -1,39 +0,0 @@
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import App from './components/App'
import Demo from './components/Demo'
import reducers, { AppState } from './reducers'
import reduxThunk from 'redux-thunk'
import { applyMiddleware, compose, createStore } from 'redux'
import { batchDispatchMiddleware } from 'redux-batched-actions'
import { connect, Provider } from 'react-redux'
import { ThemeProvider } from '@material-ui/styles'
import './utils/tracking'
import { themes } from './theme'
const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(reducers, composeEnhancers(applyMiddleware(reduxThunk, batchDispatchMiddleware)))
function ApplicationRenderer(props: { theme: 'light' | 'dark' }) {
return (
<ThemeProvider theme={props.theme === 'light' ? themes.lightTheme : themes.darkTheme}>
<App />
<Demo />
</ThemeProvider>
)
}
const mapStateToProps = (state: AppState) => {
return {
theme: state.settings.get('theme'),
}
}
const Application = connect(mapStateToProps)(ApplicationRenderer)
ReactDOM.render(
<Provider store={store}>
<Application />
</Provider>,
document.getElementById('app')
)
-82
View File
@@ -1,82 +0,0 @@
import { MqttOptions } from '../../../backend/src/DataSource'
import { v4 } from 'uuid'
const sha1 = require('sha1')
export interface CertificateParameters {
name: string
/** @property data base64 encoded data */
data: string
}
export interface ConnectionOptions {
type: 'mqtt'
id: string
host: string
protocol: 'mqtt' | 'ws'
basePath?: string
port: number
name: string
username?: string
password?: string
encryption: boolean
certValidation: boolean
selfSignedCertificate?: CertificateParameters
clientId?: string
subscriptions: Array<string>
}
export function toMqttConnection(options: ConnectionOptions): MqttOptions | undefined {
if (options.type !== 'mqtt') {
return
}
return {
url: `${options.protocol}://${options.host}:${options.port}/${options.basePath || ''}`,
username: options.username,
password: options.password,
tls: options.encryption,
clientId: options.clientId,
certValidation: options.certValidation,
subscriptions: options.subscriptions,
certificateAuthority: options.selfSignedCertificate ? options.selfSignedCertificate.data : undefined,
}
}
function generateClientId() {
const clientIdSha = sha1(`${Math.random()}`).slice(0, 8)
return `mqtt-explorer-${clientIdSha}`
}
export function createEmptyConnection(): ConnectionOptions {
return {
certValidation: true,
clientId: generateClientId(),
id: v4() as string,
name: 'new connection',
encryption: false,
password: undefined,
username: undefined,
subscriptions: ['#', '$SYS/#'],
type: 'mqtt',
host: '',
port: 1883,
protocol: 'mqtt',
}
}
export function makeDefaultConnections() {
return {
// remember: there was also iot.eclipse.org once
'mqtt.eclipse.org': {
...createEmptyConnection(),
id: 'mqtt.eclipse.org',
name: 'mqtt.eclipse.org',
host: 'mqtt.eclipse.org',
},
'test.mosquitto.org': {
...createEmptyConnection(),
id: 'test.mosquitto.org',
name: 'test.mosquitto.org',
host: 'test.mosquitto.org',
},
}
}
-59
View File
@@ -1,59 +0,0 @@
import { ConnectionOptions, createEmptyConnection } from './ConnectionOptions'
import { v4 } from 'uuid'
interface LegacyConnectionSettings {
host: string
protocol: string
port: number
tls: boolean
certValidation: boolean
clientId: string
connectionId?: string
username: string
password: string
}
export function clearLegacyConnectionOptions() {
window.localStorage.setItem('connectionSettings', '')
}
export function loadLegacyConnectionOptions(): { [s: string]: ConnectionOptions } | {} {
const legacySettingsString = window.localStorage.getItem('connectionSettings')
if (!legacySettingsString) {
return {}
}
let legacyConnection
try {
legacyConnection = JSON.parse(legacySettingsString) as LegacyConnectionSettings
} catch {
return {}
}
const protocolMap: { [s: string]: string } = {
'tcp://': 'mqtt',
'ws://': 'ws',
'mqtt://': 'mqtt',
}
const migratedOptions: Partial<ConnectionOptions> = {
certValidation: legacyConnection.certValidation,
host: legacyConnection.host,
name: legacyConnection.host,
protocol: protocolMap[legacyConnection.protocol] as any,
port: legacyConnection.port,
username: legacyConnection.username,
password: legacyConnection.password,
clientId: legacyConnection.clientId,
encryption: legacyConnection.tls,
}
const emptyConnection = createEmptyConnection()
return {
[emptyConnection.id]: {
...emptyConnection,
...migratedOptions,
},
}
}
-24
View File
@@ -1,24 +0,0 @@
import { Destroyable } from '../../../backend/src/Model/Destroyable'
import { EventDispatcher } from '../../../events'
export class TopicViewModel implements Destroyable {
private selected: boolean
public change = new EventDispatcher<void, TopicViewModel>()
public constructor() {
this.selected = false
}
public destroy() {
this.change.removeAllListeners()
}
public isSelected() {
return this.selected
}
public setSelected(selected: boolean) {
this.selected = selected
this.change.dispatch()
}
}
-85
View File
@@ -1,85 +0,0 @@
import { Action } from 'redux'
import { createReducer } from './lib'
import { Record, List } from 'immutable'
export type PlotCurveTypes = 'curve' | 'linear' | 'cubic_basis_spline' | 'step_after' | 'step_before'
export interface ChartParameters {
topic: string
dotPath?: string
interpolation?: PlotCurveTypes
range?: {
from?: number
to?: number
}
}
export interface ChartsStateModel {
charts: List<ChartParameters>
}
export type ChartsState = Record<ChartsStateModel>
export type Action = AddChart | RemoveChart | SetCharts | UpdateChart
export enum ActionTypes {
CHARTS_ADD = 'CHARTS_ADD',
CHARTS_REMOVE = 'CHARTS_REMOVE',
CHARTS_SET = 'CHARTS_SET',
CHARTS_UPDATE = 'CHARTS_UPDATE',
}
export interface AddChart {
type: ActionTypes.CHARTS_ADD
chart: ChartParameters
}
export interface UpdateChart {
type: ActionTypes.CHARTS_ADD
topic: string
dotPath?: string
parameters: Partial<ChartParameters>
}
export interface RemoveChart {
type: ActionTypes.CHARTS_REMOVE
chart: ChartParameters
}
export interface SetCharts {
type: ActionTypes.CHARTS_SET
charts: Array<ChartParameters>
}
const initialState = Record<ChartsStateModel>({
charts: List<ChartParameters>(),
})
export const chartsReducer = createReducer(initialState(), {
CHARTS_ADD: addChart,
CHARTS_REMOVE: removeChart,
CHARTS_SET: setCharts,
CHARTS_UPDATE: updateChart,
})
function addChart(state: ChartsState, action: AddChart) {
return state.set('charts', state.get('charts').push(action.chart))
}
function updateChart(state: ChartsState, action: UpdateChart) {
const charts = state.get('charts')
const chartIdx = charts.findIndex(chart => chart.topic === action.topic && chart.dotPath === action.dotPath)
const chart = charts.get(chartIdx)
return state.set('charts', chart ? charts.set(chartIdx, { ...chart, ...action.parameters }) : charts)
}
function removeChart(state: ChartsState, action: RemoveChart) {
const charts = state.get('charts')
const newCharts = charts.filter(chart => chart.topic !== action.chart.topic || chart.dotPath !== action.chart.dotPath)
return state.set('charts', newCharts)
}
function setCharts(state: ChartsState, action: SetCharts) {
return state.set('charts', List(action.charts))
}
-110
View File
@@ -1,110 +0,0 @@
import * as q from '../../../backend/src/Model'
import { Action } from 'redux'
import { createReducer } from './lib'
import { MqttOptions } from '../../../backend/src/DataSource'
import { TopicViewModel } from '../model/TopicViewModel'
export type ConnectionHealth = 'offline' | 'online' | 'connecting'
export interface ConnectionState {
host?: string
tree?: q.Tree<TopicViewModel>
connectionOptions?: MqttOptions
connectionId?: string
error?: string
connected: boolean
connecting: boolean
health?: ConnectionHealth
}
export type Action = SetConnecting | SetConnected | SetDisconnected | ShowError
export enum ActionTypes {
CONNECTION_SET_CONNECTING = 'CONNECTION_SET_CONNECTING',
CONNECTION_SET_CONNECTED = 'CONNECTION_SET_CONNECTED',
CONNECTION_SET_DISCONNECTED = 'CONNECTION_SET_DISCONNECTED',
CONNECTION_SET_SHOW_ERROR = 'CONNECTION_SET_SHOW_ERROR',
CONNECTION_SET_HEALTH = 'CONNECTION_SET_HEALTH',
}
export interface SetConnecting {
type: ActionTypes.CONNECTION_SET_CONNECTING
connectionId: string
}
export interface SetConnected {
type: ActionTypes.CONNECTION_SET_CONNECTED
host: string
tree: q.Tree<TopicViewModel>
}
export interface SetDisconnected {
type: ActionTypes.CONNECTION_SET_DISCONNECTED
}
export interface SetHealth {
health: ConnectionHealth
type: ActionTypes.CONNECTION_SET_DISCONNECTED
}
export interface ShowError {
type: ActionTypes.CONNECTION_SET_SHOW_ERROR
error?: Error
}
const initialState: ConnectionState = {
connected: false,
connecting: false,
health: undefined,
}
export const connectionReducer = createReducer(initialState, {
CONNECTION_SET_CONNECTING: setConnecting,
CONNECTION_SET_CONNECTED: setConnected,
CONNECTION_SET_DISCONNECTED: setDisconnected,
CONNECTION_SET_SHOW_ERROR: showError,
CONNECTION_SET_HEALTH: setHealth,
})
function setConnecting(state: ConnectionState, action: SetConnecting): ConnectionState {
return {
...state,
connecting: true,
connected: false,
connectionId: action.connectionId,
}
}
function setHealth(state: ConnectionState, action: SetHealth): ConnectionState {
return {
...state,
health: action.health,
}
}
function setConnected(state: ConnectionState, action: SetConnected): ConnectionState {
return {
...state,
host: action.host,
connecting: false,
connected: true,
tree: action.tree,
}
}
function setDisconnected(state: ConnectionState, action: SetDisconnected): ConnectionState {
return {
...state,
host: undefined,
connecting: false,
connected: false,
connectionId: undefined,
tree: undefined,
}
}
function showError(state: ConnectionState, action: ShowError) {
return {
...state,
error: action.error,
}
}
-182
View File
@@ -1,182 +0,0 @@
import { Action } from 'redux'
import { ConnectionOptions } from '../model/ConnectionOptions'
import { createReducer } from './lib'
export interface ConnectionManagerState {
connections: { [s: string]: ConnectionOptions }
selected?: string
showAdvancedSettings: boolean
}
const initialState: ConnectionManagerState = {
connections: {},
selected: undefined,
showAdvancedSettings: false,
}
export type Action =
| SetConnections
| SelectConnection
| UpdateConnection
| AddConnection
| DeleteConnection
| ToggleAdvancedSettings
| DeleteSubscription
| AddSubscription
export enum ActionTypes {
CONNECTION_MANAGER_SET_CONNECTIONS = 'CONNECTION_MANAGER_SET_CONNECTIONS',
CONNECTION_MANAGER_SELECT_CONNECTION = 'CONNECTION_MANAGER_SELECT_CONNECTION',
CONNECTION_MANAGER_UPDATE_CONNECTION = 'CONNECTION_MANAGER_UPDATE_CONNECTION',
CONNECTION_MANAGER_ADD_CONNECTION = 'CONNECTION_MANAGER_ADD_CONNECTION',
CONNECTION_MANAGER_DELETE_CONNECTION = 'CONNECTION_MANAGER_DELETE_CONNECTION',
CONNECTION_MANAGER_TOGGLE_ADVANCED_SETTINGS = 'CONNECTION_MANAGER_TOGGLE_ADVANCED_SETTINGS',
CONNECTION_MANAGER_ADD_SUBSCRIPTION = 'CONNECTION_MANAGER_ADD_SUBSCRIPTION',
CONNECTION_MANAGER_DELETE_SUBSCRIPTION = 'CONNECTION_MANAGER_DELETE_SUBSCRIPTION',
}
export interface SetConnections {
type: ActionTypes.CONNECTION_MANAGER_SET_CONNECTIONS
connections: { [s: string]: ConnectionOptions }
}
export interface SelectConnection {
type: ActionTypes.CONNECTION_MANAGER_SELECT_CONNECTION
selected: string
}
export interface AddSubscription {
type: ActionTypes.CONNECTION_MANAGER_ADD_SUBSCRIPTION
subscription: string
connectionId: string
}
export interface DeleteSubscription {
type: ActionTypes.CONNECTION_MANAGER_DELETE_SUBSCRIPTION
subscription: string
connectionId: string
}
export interface UpdateConnection {
type: ActionTypes.CONNECTION_MANAGER_UPDATE_CONNECTION
connectionId: string
changeSet: any
}
export interface AddConnection {
type: ActionTypes.CONNECTION_MANAGER_ADD_CONNECTION
connection: ConnectionOptions
}
export interface DeleteConnection {
type: ActionTypes.CONNECTION_MANAGER_DELETE_CONNECTION
connectionId: string
}
export interface ToggleAdvancedSettings {
type: ActionTypes.CONNECTION_MANAGER_TOGGLE_ADVANCED_SETTINGS
}
export const connectionManagerReducer = createReducer(initialState, {
CONNECTION_MANAGER_SET_CONNECTIONS: setConnections,
CONNECTION_MANAGER_SELECT_CONNECTION: selectConnection,
CONNECTION_MANAGER_UPDATE_CONNECTION: updateConnection,
CONNECTION_MANAGER_ADD_CONNECTION: addConnection,
CONNECTION_MANAGER_DELETE_CONNECTION: deleteConnection,
CONNECTION_MANAGER_TOGGLE_ADVANCED_SETTINGS: toggleAdvancedSettings,
CONNECTION_MANAGER_DELETE_SUBSCRIPTION: deleteSubscription,
CONNECTION_MANAGER_ADD_SUBSCRIPTION: addSubscription,
})
function setConnections(state: ConnectionManagerState, action: SetConnections): ConnectionManagerState {
return {
...state,
connections: action.connections,
}
}
function selectConnection(state: ConnectionManagerState, action: SelectConnection): ConnectionManagerState {
return {
...state,
selected: action.selected,
}
}
function toggleAdvancedSettings(state: ConnectionManagerState, action: ToggleAdvancedSettings): ConnectionManagerState {
return {
...state,
showAdvancedSettings: !state.showAdvancedSettings,
}
}
function addConnection(state: ConnectionManagerState, action: AddConnection): ConnectionManagerState {
return {
...state,
connections: {
...state.connections,
[action.connection.id]: action.connection,
},
}
}
function addSubscription(state: ConnectionManagerState, action: AddSubscription): ConnectionManagerState {
const connection = state.connections[action.connectionId]
const alreadyExists = connection.subscriptions.indexOf(action.subscription) !== -1
if (alreadyExists) {
return state
}
const newSubscriptions = connection.subscriptions.slice()
newSubscriptions.push(action.subscription)
return {
...state,
connections: {
...state.connections,
[action.connectionId]: {
...connection,
subscriptions: newSubscriptions,
},
},
}
}
function deleteSubscription(state: ConnectionManagerState, action: AddSubscription): ConnectionManagerState {
const connection = state.connections[action.connectionId]
const newSubscriptions = connection.subscriptions.filter(s => s !== action.subscription)
return {
...state,
connections: {
...state.connections,
[action.connectionId]: {
...connection,
subscriptions: newSubscriptions,
},
},
}
}
function deleteConnection(state: ConnectionManagerState, action: DeleteConnection): ConnectionManagerState {
const connections = { ...state.connections }
delete connections[action.connectionId]
return {
...state,
connections,
}
}
function updateConnection(state: ConnectionManagerState, action: UpdateConnection): ConnectionManagerState {
let connection = state.connections[action.connectionId]
connection = {
...connection,
...action.changeSet,
}
return {
...state,
connections: {
...state.connections,
[action.connectionId]: connection,
},
}
}
-74
View File
@@ -1,74 +0,0 @@
import { Action, Reducer } from 'redux'
import { Record } from 'immutable'
import { trackEvent } from '../utils/tracking'
export enum ActionTypes {
showUpdateNotification = 'SHOW_UPDATE_NOTIFICATION',
showUpdateDetails = 'SHOW_UPDATE_DETAILS',
showError = 'SHOW_ERROR',
showNotification = 'SHOW_NOTIFICATION',
didLaunch = 'DID_LAUNCH',
toggleSettingsVisibility = 'TOGGLE_SETTINGS_VISIBILITY',
}
export interface GlobalAction extends Action {
type: ActionTypes
showUpdateNotification?: boolean
showUpdateDetails?: boolean
error?: string
notification?: string
}
interface GlobalStateInterface {
showUpdateNotification?: boolean
showUpdateDetails: boolean
error?: string
notification?: string
launching: boolean
settingsVisible: boolean
}
export type GlobalState = Record<GlobalStateInterface>
const initialStateFactory = Record<GlobalStateInterface>({
showUpdateNotification: false,
showUpdateDetails: false,
error: undefined,
notification: undefined,
launching: true,
settingsVisible: false,
})
export const globalState: Reducer<Record<GlobalStateInterface>, GlobalAction> = (
state = initialStateFactory(),
action
): GlobalState => {
trackEvent(action.type)
console.log(action.type)
switch (action.type) {
case ActionTypes.showUpdateNotification:
return state.set('showUpdateNotification', action.showUpdateNotification)
case ActionTypes.toggleSettingsVisibility:
return state.set('settingsVisible', !state.get('settingsVisible'))
case ActionTypes.showError:
return state.set('error', action.error)
case ActionTypes.showNotification:
return state.set('notification', action.notification)
case ActionTypes.didLaunch:
return state.set('launching', false)
case ActionTypes.showUpdateDetails:
if (action.showUpdateDetails === undefined) {
return state
}
return state.set('showUpdateDetails', action.showUpdateDetails)
default:
return state
}
}
-93
View File
@@ -1,93 +0,0 @@
import { Action } from 'redux'
import { createReducer } from './lib'
export interface PublishState {
topic?: string
payload?: string
retain: boolean
editorMode: string
qos: 0 | 1 | 2
}
export type Action = SetPayload | SetTopic | ToggleRetain | SetEditorMode | SetQoS
export enum ActionTypes {
PUBLISH_SET_TOPIC = 'PUBLISH_SET_TOPIC',
PUBLISH_SET_PAYLOAD = 'PUBLISH_SET_PAYLOAD',
PUBLISH_TOGGLE_RETAIN = 'PUBLISH_TOGGLE_RETAIN',
PUBLISH_SET_EDITOR_MODE = 'PUBLISH_SET_EDITOR_MODE',
PUBLISH_SET_QOS = 'PUBLISH_SET_QOS',
}
export interface SetPayload {
type: ActionTypes.PUBLISH_SET_PAYLOAD
payload?: string
}
export interface SetTopic {
type: ActionTypes.PUBLISH_SET_TOPIC
topic?: string
}
export interface SetQoS {
type: ActionTypes.PUBLISH_SET_QOS
qos: 0 | 1 | 2
}
export interface SetEditorMode {
type: ActionTypes.PUBLISH_SET_EDITOR_MODE
editorMode: string
}
export interface ToggleRetain {
type: ActionTypes.PUBLISH_TOGGLE_RETAIN
}
const initialState: PublishState = {
editorMode: 'json',
retain: false,
qos: 0,
}
export const publishReducer = createReducer(initialState, {
PUBLISH_SET_TOPIC: setTopic,
PUBLISH_SET_PAYLOAD: setPayload,
PUBLISH_TOGGLE_RETAIN: toggleRetain,
PUBLISH_SET_EDITOR_MODE: setEditorMode,
PUBLISH_SET_QOS: setQoS,
})
function setTopic(state: PublishState, action: SetTopic) {
return {
...state,
topic: action.topic,
}
}
function setPayload(state: PublishState, action: SetPayload) {
return {
...state,
payload: action.payload,
}
}
function setQoS(state: PublishState, action: SetQoS) {
return {
...state,
qos: action.qos,
}
}
function setEditorMode(state: PublishState, action: SetEditorMode) {
return {
...state,
editorMode: action.editorMode,
}
}
function toggleRetain(state: PublishState) {
return {
...state,
retain: !state.retain,
}
}
-154
View File
@@ -1,154 +0,0 @@
import { createReducer } from './lib'
import { Record } from 'immutable'
export enum TopicOrder {
none = 'none',
messages = '#messages',
abc = 'abc',
topics = '#topics',
}
export type ValueRendererDisplayMode = 'diff' | 'raw'
export interface SettingsState {
autoExpandLimit: number
timeLocale: string
topicOrder: TopicOrder
topicFilter?: string
highlightTopicUpdates: boolean
valueRendererDisplayMode: ValueRendererDisplayMode
selectTopicWithMouseOver: boolean
theme: 'light' | 'dark'
}
export type Actions = SetAutoExpandLimitAction &
DidLoadSettingsAction &
SetTopicOrderAction &
FilterTopicsAction &
ToggleHighlightTopicUpdatesAction &
SetValueRendererDisplayModeAction &
SetTheme &
SetSelectTopicWithMouseOverAction &
SetTimeLocale
export enum ActionTypes {
SETTINGS_SET_AUTO_EXPAND_LIMIT = 'SETTINGS_SET_AUTO_EXPAND_LIMIT',
SETTINGS_SET_TOPIC_ORDER = 'SETTINGS_SET_TOPIC_ORDER',
SETTINGS_FILTER_TOPICS = 'SETTINGS_FILTER_TOPICS',
SETTINGS_TOGGLE_HIGHLIGHT_ACTIVITY = 'SETTINGS_TOGGLE_HIGHLIGHT_ACTIVITY',
SETTINGS_DID_LOAD_SETTINGS = 'SETTINGS_DID_LOAD_SETTINGS',
SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE = 'SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE',
SETTINGS_SET_SELECT_TOPIC_WITH_MOUSE_OVER = 'SETTINGS_SET_SELECT_TOPIC_WITH_MOUSE_OVER',
SETTINGS_SET_THEME_LIGHT = 'SETTINGS_SET_THEME_LIGHT',
SETTINGS_SET_THEME_DARK = 'SETTINGS_SET_THEME_DARK',
SETTINGS_SET_TIME_LOCALE = 'SETTINGS_SET_TIME_LOCALE',
}
const initialState = Record<SettingsState>({
timeLocale: window.navigator.language,
autoExpandLimit: 0,
topicOrder: TopicOrder.none,
highlightTopicUpdates: true,
valueRendererDisplayMode: 'diff',
selectTopicWithMouseOver: false,
theme: 'light',
topicFilter: undefined,
})
const setTheme = (theme: 'light' | 'dark') => (state: Record<SettingsState>) => {
return state.set('theme', theme)
}
const reducerActions: {
[s: string]: (state: Record<SettingsState>, action: Actions) => Record<SettingsState>
} = {
SETTINGS_SET_AUTO_EXPAND_LIMIT: setAutoExpandLimit,
SETTINGS_SET_TOPIC_ORDER: setTopicOrder,
SETTINGS_FILTER_TOPICS: filterTopics,
SETTINGS_TOGGLE_HIGHLIGHT_ACTIVITY: toggleHighlightTopicUpdates,
SETTINGS_DID_LOAD_SETTINGS: didLoadSettings,
SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE: setValueRendererDisplayMode,
SETTINGS_SET_SELECT_TOPIC_WITH_MOUSE_OVER: setSelectTopicWithMouseOver,
SETTINGS_SET_THEME_LIGHT: setTheme('light'),
SETTINGS_SET_THEME_DARK: setTheme('dark'),
SETTINGS_SET_TIME_LOCALE: setTimeLocale,
}
export const settingsReducer = createReducer(initialState(), reducerActions)
export interface SetTheme {
type: ActionTypes.SETTINGS_SET_THEME_LIGHT | ActionTypes.SETTINGS_SET_THEME_DARK
theme: 'light' | 'dark'
}
export interface DidLoadSettingsAction {
type: ActionTypes.SETTINGS_DID_LOAD_SETTINGS
settings: Partial<SettingsState>
}
function didLoadSettings(state: Record<SettingsState>, action: DidLoadSettingsAction) {
return state.merge(action.settings)
}
export interface SetSelectTopicWithMouseOverAction {
type: ActionTypes.SETTINGS_SET_SELECT_TOPIC_WITH_MOUSE_OVER
selectTopicWithMouseOver: boolean
}
export function setSelectTopicWithMouseOver(state: Record<SettingsState>, action: SetSelectTopicWithMouseOverAction) {
return state.set('selectTopicWithMouseOver', !state.get('selectTopicWithMouseOver'))
}
export interface SetTimeLocale {
type: ActionTypes.SETTINGS_SET_TIME_LOCALE
timeLocale: string
}
export function setTimeLocale(state: Record<SettingsState>, action: SetTimeLocale): Record<SettingsState> {
return state.set('timeLocale', action.timeLocale)
}
export interface SetValueRendererDisplayModeAction {
type: ActionTypes.SETTINGS_SET_VALUE_RENDERER_DISPLAY_MODE
valueRendererDisplayMode: ValueRendererDisplayMode
}
export function setValueRendererDisplayMode(state: Record<SettingsState>, action: SetValueRendererDisplayModeAction) {
return state.set('valueRendererDisplayMode', action.valueRendererDisplayMode)
}
export interface SetAutoExpandLimitAction {
type: ActionTypes.SETTINGS_SET_AUTO_EXPAND_LIMIT
autoExpandLimit: number
}
function setAutoExpandLimit(state: Record<SettingsState>, action: SetAutoExpandLimitAction) {
return state.set('autoExpandLimit', action.autoExpandLimit)
}
export interface ToggleHighlightTopicUpdatesAction {
type: ActionTypes.SETTINGS_TOGGLE_HIGHLIGHT_ACTIVITY
}
function toggleHighlightTopicUpdates(state: Record<SettingsState>, action: ToggleHighlightTopicUpdatesAction) {
return state.set('highlightTopicUpdates', !state.get('highlightTopicUpdates'))
}
export interface SetTopicOrderAction {
type: ActionTypes.SETTINGS_SET_TOPIC_ORDER
topicOrder: TopicOrder
}
function setTopicOrder(state: Record<SettingsState>, action: SetTopicOrderAction) {
return state.set('topicOrder', action.topicOrder)
}
export interface FilterTopicsAction {
type: ActionTypes.SETTINGS_FILTER_TOPICS
topicFilter: string
}
// @Todo: move to tree reducer, should not be persisted / is no application setting
function filterTopics(state: Record<SettingsState>, action: FilterTopicsAction) {
return state.set('topicFilter', action.topicFilter)
}
-46
View File
@@ -1,46 +0,0 @@
import * as q from '../../../backend/src/Model'
import { Action } from 'redux'
import { createReducer } from './lib'
import { Record } from 'immutable'
interface SidebarModel {
compareMessage?: q.Message
}
const initialStateFactory = Record<SidebarModel>({
compareMessage: undefined,
})
export type Action = SetCompareMessage
export enum ActionTypes {
SIDEBAR_SET_COMPARE_MESSAGE = 'SIDEBAR_SET_COMPARE_MESSAGE',
SIDEBAR_RESET_STORE = 'SIDEBAR_RESET_STORE',
}
export type SidebarState = Record<SidebarModel>
const actions: {
[s: string]: (state: SidebarState, action: Action) => SidebarState
} = {
SIDEBAR_SET_COMPARE_MESSAGE: setCompareMessage,
SIDEBAR_RESET_STORE: resetStore,
}
export const sidebarReducer = createReducer(initialStateFactory(), actions)
export interface SetCompareMessage {
type: ActionTypes.SIDEBAR_SET_COMPARE_MESSAGE
message?: q.Message
}
function setCompareMessage(state: SidebarState, action: SetCompareMessage): SidebarState {
return state.set('compareMessage', action.message)
}
export interface ResetStore {
type: ActionTypes.SIDEBAR_RESET_STORE
}
function resetStore(): SidebarState {
return initialStateFactory()
}
-81
View File
@@ -1,81 +0,0 @@
import * as q from '../../../backend/src/Model'
import { Action } from 'redux'
import { createReducer } from './lib'
import { Record } from 'immutable'
import { TopicViewModel } from '../model/TopicViewModel'
interface TreeStateModel {
tree?: q.Tree<TopicViewModel>
selectedTopic?: q.TreeNode<TopicViewModel>
filter?: string
paused: boolean
}
export type TreeState = Record<TreeStateModel>
export type Action = ShowTree | SelectTopic | ResetStore
export enum ActionTypes {
TREE_SHOW_TREE = 'TREE_SHOW_TREE',
TREE_SELECT_TOPIC = 'TREE_SELECT_TOPIC',
TREE_RESUME_UPDATES = 'TREE_RESUME_UPDATES',
TREE_PAUSE_UPDATES = 'TREE_PAUSE_UPDATES',
TREE_RESET_STORE = 'TREE_RESET_STORE',
}
export interface ShowTree {
type: ActionTypes.TREE_SHOW_TREE
tree?: q.Tree<TopicViewModel>
filter?: string
}
export interface SelectTopic {
type: ActionTypes.TREE_SELECT_TOPIC
selectedTopic?: q.TreeNode<TopicViewModel>
}
export interface SetPause {
type: ActionTypes.TREE_PAUSE_UPDATES | ActionTypes.TREE_RESUME_UPDATES
}
const initialStateFactory = Record<TreeStateModel>({
paused: false,
tree: undefined,
selectedTopic: undefined,
filter: undefined,
})
const setPaused = (pause: boolean) => (state: TreeState, action: ShowTree): TreeState => {
return state.set('paused', pause)
}
const actions: {
[s: string]: (state: TreeState, action: Action) => TreeState
} = {
TREE_SHOW_TREE: showTree,
TREE_SELECT_TOPIC: selectTopic,
TREE_PAUSE_UPDATES: setPaused(true),
TREE_RESUME_UPDATES: setPaused(false),
TREE_RESET_STORE: resetStore,
}
export const treeReducer = createReducer(initialStateFactory(), actions)
function showTree(state: TreeState, action: ShowTree): TreeState {
return state.merge({
tree: action.tree,
filter: action.filter,
})
}
function selectTopic(state: TreeState, action: SelectTopic): TreeState {
return state.set('selectedTopic', action.selectedTopic)
}
export interface ResetStore {
type: ActionTypes.TREE_RESET_STORE
}
function resetStore(state: TreeState, action: ResetStore): TreeState {
return initialStateFactory()
}
-32
View File
@@ -1,32 +0,0 @@
import { chartsReducer, ChartsState } from './Charts'
import { combineReducers } from 'redux'
import { connectionManagerReducer, ConnectionManagerState } from './ConnectionManager'
import { connectionReducer, ConnectionState } from './Connection'
import { GlobalState, globalState } from './Global'
import { publishReducer, PublishState } from './Publish'
import { Record } from 'immutable'
import { settingsReducer, SettingsState } from './Settings'
import { sidebarReducer, SidebarState } from './Sidebar'
import { treeReducer, TreeState } from './Tree'
export interface AppState {
globalState: GlobalState
tree: TreeState
settings: Record<SettingsState>
publish: PublishState
charts: ChartsState
sidebar: SidebarState
connection: ConnectionState
connectionManager: ConnectionManagerState
}
export default combineReducers({
globalState,
charts: chartsReducer,
publish: publishReducer,
sidebar: sidebarReducer,
connection: connectionReducer,
settings: settingsReducer,
tree: treeReducer,
connectionManager: connectionManagerReducer,
})

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