mirror of
https://github.com/thomasnordquist/MQTT-Explorer.git
synced 2026-09-11 09:03:33 +00:00
Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e12d0544e6 | ||
|
|
9e48b8613e | ||
|
|
6f8ad41ef5 | ||
|
|
1ec10bb007 | ||
|
|
70e75061b2 | ||
|
|
c0b2950ecb | ||
|
|
f946ae39d7 | ||
|
|
43ff3e81f0 | ||
|
|
79a8cdf1fd | ||
|
|
16c190818c | ||
|
|
de367e755f | ||
|
|
6e355decbf | ||
|
|
d4dbc36a8a | ||
|
|
0e82a8baad | ||
|
|
0016f2d364 | ||
|
|
e6ecb77d01 | ||
|
|
2afddb8d63 | ||
|
|
dfdf473b27 | ||
|
|
4fcdd47e65 | ||
|
|
b2a8e84479 | ||
|
|
8d665e0e52 | ||
|
|
9e1c229a5d | ||
|
|
0d34f86893 | ||
|
|
73c48f388b | ||
|
|
a36a630466 | ||
|
|
fe6ccc8e16 | ||
|
|
d91718cf80 | ||
|
|
66610bcb54 | ||
|
|
7437c796a0 | ||
|
|
bb1e52feae | ||
|
|
d69d5af2ae | ||
|
|
0c1d09a8a0 | ||
|
|
308b748d0e | ||
|
|
85475a9201 | ||
|
|
2c147a92ad | ||
|
|
a143c5fb45 | ||
|
|
eb605a884c | ||
|
|
9868ac67fc | ||
|
|
229414de28 | ||
|
|
6c041cba02 | ||
|
|
a7136bd572 | ||
|
|
a5629b8c77 | ||
|
|
da122e06f1 | ||
|
|
e0a79f61af | ||
|
|
26ed0aadd2 | ||
|
|
578bb510f9 | ||
|
|
e725b1d012 | ||
|
|
c55c3a8245 |
@@ -2,7 +2,7 @@
|
||||
"name": "MQTT Explorer Development",
|
||||
"dockerComposeFile": "docker-compose.yml",
|
||||
"service": "app",
|
||||
"workspaceFolder": "/workspace",
|
||||
"workspaceFolder": "/workspace/MQTT-Explorer",
|
||||
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
@@ -15,7 +15,6 @@
|
||||
],
|
||||
"settings": {
|
||||
"editor.formatOnSave": true,
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": "explicit"
|
||||
@@ -24,7 +23,7 @@
|
||||
}
|
||||
},
|
||||
|
||||
"forwardPorts": [3000, 8080, 1883],
|
||||
"forwardPorts": [3000, 8080, 1883, 5900, 6080],
|
||||
"portsAttributes": {
|
||||
"3000": {
|
||||
"label": "MQTT Explorer Server",
|
||||
@@ -37,10 +36,29 @@
|
||||
"1883": {
|
||||
"label": "MQTT Broker",
|
||||
"onAutoForward": "ignore"
|
||||
},
|
||||
"5900": {
|
||||
"label": "VNC Server",
|
||||
"onAutoForward": "ignore"
|
||||
},
|
||||
"6080": {
|
||||
"label": "noVNC Web Client",
|
||||
"onAutoForward": "notify"
|
||||
}
|
||||
},
|
||||
|
||||
"postCreateCommand": "yarn install",
|
||||
|
||||
"postStartCommand": "sudo apt-get update && sudo apt-get install -y mosquitto xvfb x11vnc ffmpeg tmux python3 python3-pip && sudo pip3 install --break-system-packages websockify",
|
||||
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/common-utils:2": {
|
||||
"installZsh": true,
|
||||
"installOhMyZsh": true,
|
||||
"upgradePackages": true
|
||||
}
|
||||
},
|
||||
|
||||
"remoteUser": "node"
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@ version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
image: mcr.microsoft.com/devcontainers/javascript-node:20
|
||||
image: mcr.microsoft.com/devcontainers/javascript-node:24
|
||||
volumes:
|
||||
- ../..:/workspace:cached
|
||||
- ..:/workspaces/MQTT-Explorer:cached
|
||||
command: sleep infinity
|
||||
network_mode: service:mosquitto
|
||||
environment:
|
||||
@@ -14,8 +14,10 @@ services:
|
||||
mosquitto:
|
||||
image: eclipse-mosquitto:2
|
||||
ports:
|
||||
- "1883:1883"
|
||||
- "3000:3000"
|
||||
- "8080:8080"
|
||||
- '1883:1883'
|
||||
- '3000:3000'
|
||||
- '8080:8080'
|
||||
- '5900:5900'
|
||||
- '6080:6080'
|
||||
volumes:
|
||||
- ./mosquitto.conf:/mosquitto/config/mosquitto.conf:ro
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
.github
|
||||
|
||||
# Dependencies
|
||||
node_modules
|
||||
app/node_modules
|
||||
backend/node_modules
|
||||
|
||||
# Build artifacts
|
||||
build
|
||||
dist
|
||||
app/dist
|
||||
|
||||
# Testing
|
||||
coverage
|
||||
.nyc_output
|
||||
test-screenshot-*.png
|
||||
ui-test.mp4
|
||||
ui-test.gif
|
||||
|
||||
# Development
|
||||
.vscode
|
||||
.devcontainer
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.idea
|
||||
|
||||
# Documentation
|
||||
*.md
|
||||
!Readme.md
|
||||
LICENSE.md
|
||||
|
||||
# CI/CD files
|
||||
.releaserc
|
||||
appveyor.yml
|
||||
|
||||
# Misc
|
||||
res
|
||||
scripts
|
||||
docker
|
||||
icon.xcf
|
||||
greenkeeper.json
|
||||
prettier.config.js
|
||||
.prettierignore
|
||||
.eslintrc.json
|
||||
.cspell.json
|
||||
tslint.json
|
||||
mcp.json
|
||||
|
||||
# Data directory (will be created in container)
|
||||
data
|
||||
+61
-361
@@ -1,383 +1,83 @@
|
||||
# GitHub Copilot Agent Instructions for MQTT Explorer
|
||||
# copilot-instructions.md - Agent Long-Term Memory
|
||||
|
||||
## Overview
|
||||
## META-INSTRUCTIONS (IMMUTABLE)
|
||||
|
||||
MQTT Explorer is an Electron-based desktop application for exploring MQTT brokers. It provides a comprehensive UI for connecting to MQTT brokers, browsing topics, and analyzing message flows.
|
||||
1. **Long-term memory**: If you learn something during a session that would save time in future sessions, add it to `.github/copilot-instructions.md`
|
||||
2. **Paper knowledge must go**: If something is no longer true, update or remove it immediately
|
||||
3. **Evaluate after every session**: Consider whether the instructions need updates based on what you learned
|
||||
4. **Concise and useful**: All information must be actionable, current, and concise
|
||||
|
||||
## Technology Stack
|
||||
## Test Commands
|
||||
|
||||
- **Frontend**: React 16.x with Material-UI
|
||||
- **Backend**: Node.js with TypeScript
|
||||
- **Desktop Framework**: Electron 29.x
|
||||
- **MQTT Client**: [mqttjs](https://github.com/mqttjs/MQTT.js) v4.x
|
||||
- **State Management**: Redux with redux-thunk
|
||||
- **Build Tools**: webpack, TypeScript compiler
|
||||
- **Testing**: Mocha + Chai for unit tests, Playwright for MCP introspection tests
|
||||
**Unit tests:**
|
||||
- `yarn test` - All unit tests (app + backend)
|
||||
- `yarn test:app` - Frontend tests only
|
||||
- `yarn test:backend` - Backend tests only
|
||||
|
||||
## Project Setup
|
||||
**Integration tests:**
|
||||
- `yarn test:ui` - Browser tests (requires `yarn build` first)
|
||||
- `yarn test:demo-video` - UI recording (requires Xvfb, mosquitto, tmux, ffmpeg)
|
||||
- `yarn test:mcp` - Model Context Protocol tests
|
||||
- `yarn test:all` - All tests (unit + demo-video)
|
||||
- `./scripts/runBrowserTests.sh` - Browser mode UI tests (requires mosquitto service)
|
||||
|
||||
### Building and Running
|
||||
**CI jobs:** `test`, `ui-tests`, `demo-video`, `test-browser`, `browser-ui-tests`
|
||||
|
||||
**Important:** Browser UI tests require MQTT broker. In CI, GitHub Actions health checks ensure the mosquitto service is ready before tests run.
|
||||
|
||||
## Browser Mode
|
||||
|
||||
**Prerequisites:** Node.js ≥24, Yarn, Mosquitto broker (for testing)
|
||||
|
||||
**Development (hot reload):**
|
||||
```bash
|
||||
# Install dependencies
|
||||
yarn install
|
||||
|
||||
# Build the project
|
||||
yarn build
|
||||
|
||||
# Set password for browser testing
|
||||
export MQTT_EXPLORER_USERNAME=admin
|
||||
export MQTT_EXPLORER_PASSWORD=secretpassword
|
||||
|
||||
# Start the application
|
||||
yarn start
|
||||
|
||||
# Start in development mode
|
||||
yarn dev
|
||||
export MQTT_EXPLORER_USERNAME=admin MQTT_EXPLORER_PASSWORD=yourpass
|
||||
yarn dev:server
|
||||
# Backend: http://localhost:3000, Frontend: http://localhost:8080 (use this one)
|
||||
```
|
||||
|
||||
### Running with MCP Introspection (for testing)
|
||||
|
||||
**Production:**
|
||||
```bash
|
||||
# Build first
|
||||
yarn build
|
||||
|
||||
# Start with MCP introspection enabled
|
||||
electron . --enable-mcp-introspection
|
||||
|
||||
# Or with custom port
|
||||
electron . --enable-mcp-introspection --remote-debugging-port=9223
|
||||
yarn build:server
|
||||
export MQTT_EXPLORER_USERNAME=admin MQTT_EXPLORER_PASSWORD=yourpass
|
||||
yarn start:server # http://localhost:3000
|
||||
```
|
||||
|
||||
## Writing Tests
|
||||
**Build artifacts:** `dist/src/server.js`, `app/build/*.js`, `app/build/index.html`
|
||||
|
||||
### Requirements for All Tests
|
||||
## Debugging Browser Mode
|
||||
|
||||
1. **Tests MUST be deterministic** - They should produce the same results every time they run
|
||||
2. **Tests MUST be independent** - Each test should be able to run in isolation without depending on other tests
|
||||
3. **Include screenshots** - Visual verification is required for UI changes
|
||||
4. **Handle asynchronous operations properly** - This is an MQTT message queue tool
|
||||
**DevTools checks:**
|
||||
- Console: JavaScript errors, CSP errors (security headers), WebSocket issues
|
||||
- Network: Static asset loading, WebSocket status, API auth
|
||||
|
||||
### Best Practices for UI Tests
|
||||
**Common issues:**
|
||||
- **Blank page/CSP errors:** Add `'unsafe-eval'` to `scriptSrc` in `src/server.ts` helmet config
|
||||
- **Auth loop:** WebSocket auth failing - check Network → WS → Messages and server logs
|
||||
- **Theme errors:** Verify both ThemeProvider and LegacyThemeProvider in `app/src/index.tsx`
|
||||
|
||||
#### 1. Use Given-When-Then Pattern
|
||||
Structure tests with clear Given-When-Then comments to make them readable:
|
||||
|
||||
```typescript
|
||||
it('Given a JSON message sent to topic foo/bar/baz, the tree should display nested topics', async function () {
|
||||
// Given: Mock MQTT publishes JSON to foo/bar/baz
|
||||
// When: We wait for the topic to appear in the tree
|
||||
// Then: Topic hierarchy should be visible (foo -> bar -> baz)
|
||||
})
|
||||
```
|
||||
|
||||
#### 2. Wait for Elements, Don't Use Fixed Delays
|
||||
Prefer `waitFor` over `sleep` whenever possible:
|
||||
|
||||
```typescript
|
||||
// ✓ Good: Wait for specific element
|
||||
const topic = await page.locator('span[data-test-topic="kitchen"]')
|
||||
await topic.waitFor({ state: 'visible', timeout: 5000 })
|
||||
|
||||
// ✗ Bad: Fixed delay without verification
|
||||
await sleep(5000)
|
||||
```
|
||||
|
||||
#### 3. Use Meaningful Assertions
|
||||
Every test should have explicit assertions that verify the expected state:
|
||||
|
||||
```typescript
|
||||
// ✓ Good: Explicit assertion with meaningful message
|
||||
const treeNodes = await page.locator('[class*="TreeNode"]')
|
||||
const count = await treeNodes.count()
|
||||
expect(count).to.be.greaterThan(0, 'Topic tree should contain nodes')
|
||||
|
||||
// ✗ Bad: No assertion, only screenshot
|
||||
await page.screenshot({ path: 'test.png' })
|
||||
```
|
||||
|
||||
#### 4. Test Data-Driven Scenarios
|
||||
Write tests that describe the data flow:
|
||||
|
||||
```typescript
|
||||
it('Given messages sent to livingroom/lamp/state and livingroom/lamp/brightness, both should appear under livingroom/lamp', async function () {
|
||||
// Test implementation verifies the specific data flow
|
||||
})
|
||||
```
|
||||
|
||||
#### 5. Use Data Test Attributes
|
||||
Leverage `data-test-*` attributes for reliable selectors:
|
||||
|
||||
```typescript
|
||||
// ✓ Good: Use data-test attributes
|
||||
const topic = await page.locator('span[data-test-topic="kitchen"]')
|
||||
|
||||
// ⚠ Acceptable: Use role/text when data attributes aren't available
|
||||
const button = await page.locator('//button/span[contains(text(),"Connect")]')
|
||||
|
||||
// ✗ Bad: Rely on CSS classes that may change
|
||||
const topic = await page.locator('.MuiTreeItem-label')
|
||||
```
|
||||
|
||||
#### 6. Verify Multiple Aspects
|
||||
Test should verify both state and UI:
|
||||
|
||||
```typescript
|
||||
// Verify the action completed
|
||||
const isVisible = await disconnectButton.isVisible()
|
||||
expect(isVisible).to.be.true
|
||||
|
||||
// Capture screenshot for visual verification
|
||||
await page.screenshot({ path: 'test-screenshot-connection.png' })
|
||||
```
|
||||
|
||||
#### 7. Handle MQTT Asynchronous Nature
|
||||
Account for message propagation time:
|
||||
|
||||
```typescript
|
||||
// Publish message
|
||||
await mockClient.publish('topic/name', 'value')
|
||||
|
||||
// Wait for UI to update
|
||||
await page.locator(`text="value"`).waitFor({ timeout: 5000 })
|
||||
|
||||
// Verify state
|
||||
const value = await page.textContent('.message-value')
|
||||
expect(value).toBe('value')
|
||||
```
|
||||
|
||||
### Handling MQTT Asynchronous Operations
|
||||
|
||||
MQTT is inherently asynchronous. When writing tests:
|
||||
|
||||
- **Wait for message propagation**: Use proper wait strategies (e.g., `await page.waitForSelector()`, `await sleep()`)
|
||||
- **Don't assume immediate updates**: Messages take time to send, receive, and update the UI
|
||||
- **Use event-based waiting**: Wait for specific UI elements or state changes rather than fixed timeouts when possible
|
||||
- **Account for network latency**: MQTT broker communication involves network round trips
|
||||
|
||||
### Example Test Pattern
|
||||
|
||||
```typescript
|
||||
// 1. Perform action (e.g., publish message)
|
||||
await publishMessage(topic, payload)
|
||||
|
||||
// 2. Wait for UI to update (not just arbitrary sleep)
|
||||
await page.waitForSelector(`text="${expectedValue}"`, { timeout: 5000 })
|
||||
|
||||
// 3. Verify state
|
||||
const value = await page.textContent('.message-value')
|
||||
expect(value).toBe(expectedValue)
|
||||
|
||||
// 4. Take screenshot for verification
|
||||
await page.screenshot({ path: 'test-result.png' })
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
**Expected warnings (non-fatal):**
|
||||
- React 18 + Material-UI v5 type warnings
|
||||
- IpcRendererEventBus errors (no Electron IPC in browser mode)
|
||||
- MUI locale, componentWillReceiveProps, ACE editor warnings
|
||||
|
||||
**WebSocket debugging:**
|
||||
```bash
|
||||
# Run all tests
|
||||
yarn test
|
||||
|
||||
# Run specific test suites
|
||||
yarn test:app
|
||||
yarn test:backend
|
||||
yarn test:mcp
|
||||
|
||||
# Run linters
|
||||
yarn lint
|
||||
yarn lint:fix
|
||||
node dist/src/server.js 2>&1 | tee server.log
|
||||
# Check DevTools → Network → WS → Messages for handshake
|
||||
# CORS: check ALLOWED_ORIGINS env var
|
||||
```
|
||||
|
||||
### Running UI Tests (yarn test:ui)
|
||||
**Security notes:**
|
||||
- `unsafe-eval` in CSP required for webpack (security tradeoff)
|
||||
- Never hardcode credentials (use env vars)
|
||||
- Production: use HTTPS with reverse proxy
|
||||
- Rate limit: 5 auth attempts/15min/IP
|
||||
- File upload limit: 16MB
|
||||
|
||||
The UI tests require specific setup in the test environment:
|
||||
|
||||
**Prerequisites:**
|
||||
1. **Xvfb (X Virtual Framebuffer)** - Required for headless Electron testing
|
||||
```bash
|
||||
# Start Xvfb on display :99
|
||||
Xvfb :99 -screen 0 1024x720x24 -ac &
|
||||
export DISPLAY=:99
|
||||
```
|
||||
|
||||
2. **Mosquitto MQTT Broker** - Required for MQTT message testing
|
||||
```bash
|
||||
# Install mosquitto
|
||||
sudo apt-get install -y mosquitto mosquitto-clients
|
||||
|
||||
# Start mosquitto service
|
||||
sudo systemctl start mosquitto
|
||||
|
||||
# Verify it's running on port 1883
|
||||
sudo systemctl status mosquitto
|
||||
```
|
||||
|
||||
3. **@types/node** - Required for TypeScript compilation
|
||||
```bash
|
||||
yarn add -D @types/node
|
||||
```
|
||||
|
||||
**Running UI Tests:**
|
||||
```bash
|
||||
# Build the application first
|
||||
yarn build
|
||||
|
||||
# Run UI tests with proper display
|
||||
DISPLAY=:99 yarn test:ui
|
||||
```
|
||||
|
||||
**Common Issues:**
|
||||
- **"Timeout exceeded" in before hook**: Mosquitto is not running or not accessible on port 1883
|
||||
- **"Cannot find type definition file for 'node'"**: Run `yarn add -D @types/node`
|
||||
- **Electron fails to launch**: Xvfb is not running or DISPLAY variable not set
|
||||
- **Tests hang**: Check if old Electron/mosquitto processes are still running and kill them
|
||||
|
||||
**Environment Cleanup:**
|
||||
```bash
|
||||
# Kill old Electron processes
|
||||
ps aux | grep electron | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null
|
||||
|
||||
# Kill old mosquitto processes (if running custom instance)
|
||||
ps aux | grep mosquitto | grep -v grep | awk '{print $2}' | xargs kill -9 2>/dev/null
|
||||
```
|
||||
|
||||
## MCP Introspection Testing
|
||||
|
||||
The project supports MCP (Model Context Protocol) for automated testing with Playwright:
|
||||
|
||||
- Use `yarn test:mcp` to run automated UI tests
|
||||
- Tests launch the app with remote debugging enabled on port 9222
|
||||
- Connect to `http://localhost:9222` via Chrome DevTools Protocol
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `app/` - Frontend React application
|
||||
- `backend/` - Backend models, tests, and connection management
|
||||
- `src/` - Electron main process and bindings
|
||||
- `src/spec/` - Test specifications including MCP introspection tests
|
||||
|
||||
## Code Style and Formatting
|
||||
|
||||
### Linting
|
||||
|
||||
The project uses TSLint with Airbnb config and Prettier for code formatting:
|
||||
|
||||
```bash
|
||||
# Run all linters
|
||||
yarn lint
|
||||
|
||||
# Run linters individually
|
||||
yarn lint:prettier # Check Prettier formatting
|
||||
yarn lint:tslint # Check TSLint rules
|
||||
yarn lint:spellcheck # Check spelling in code
|
||||
|
||||
# Auto-fix issues
|
||||
yarn lint:fix # Fix TSLint and Prettier issues
|
||||
yarn lint:tslint:fix # Fix TSLint issues only
|
||||
yarn lint:prettier:fix # Fix Prettier issues only
|
||||
```
|
||||
|
||||
### Code Style Rules
|
||||
|
||||
- **Semicolons**: Never use semicolons (enforced by TSLint and Prettier)
|
||||
- **Quotes**: Single quotes for strings
|
||||
- **Indentation**: 2 spaces
|
||||
- **Line length**: Maximum 120 characters (Prettier) / 200 characters (TSLint)
|
||||
- **Arrow functions**: No parentheses for single parameters (`x => x + 1`)
|
||||
- **Trailing commas**: Required for multiline objects and arrays (ES5 compatible)
|
||||
|
||||
### TypeScript Guidelines
|
||||
|
||||
- Enable strict null checks and no implicit any
|
||||
- Use TypeScript interfaces for data structures
|
||||
- Prefer `const` over `let`, avoid `var`
|
||||
- Use type inference when possible, explicit types when clarity is needed
|
||||
|
||||
## Dependency Management
|
||||
|
||||
### Adding Dependencies
|
||||
|
||||
```bash
|
||||
# Add to root project
|
||||
yarn add <package-name>
|
||||
|
||||
# Add to app (frontend)
|
||||
cd app && yarn add <package-name>
|
||||
|
||||
# Add to backend
|
||||
cd backend && yarn add <package-name>
|
||||
|
||||
# Add dev dependencies
|
||||
yarn add -D <package-name>
|
||||
```
|
||||
|
||||
### Important Dependency Notes
|
||||
|
||||
- Main dependencies are in the root `package.json`
|
||||
- Frontend React app has its own dependencies in `app/package.json`
|
||||
- Backend models and logic have dependencies in `backend/package.json`
|
||||
- Always use `--frozen-lockfile` in CI to ensure reproducible builds
|
||||
- Run `yarn install` after pulling changes that modify `yarn.lock`
|
||||
|
||||
## Debugging
|
||||
|
||||
### Development Mode
|
||||
|
||||
```bash
|
||||
# Start with hot reload for frontend
|
||||
yarn dev
|
||||
|
||||
# This runs two processes in parallel:
|
||||
# 1. webpack-dev-server for the React app (port varies)
|
||||
# 2. Electron in development mode with the --development flag
|
||||
```
|
||||
|
||||
### Debugging TypeScript
|
||||
|
||||
- Source maps are enabled in `tsconfig.json`
|
||||
- Use `ts-node` for running TypeScript files directly
|
||||
- Backend tests can be debugged with: `cd backend && yarn test-inspect`
|
||||
|
||||
### Common Issues
|
||||
|
||||
- **Build fails**: Clear `dist/` and `app/build/` directories, then rebuild
|
||||
- **Electron won't start**: Ensure `yarn build` completed successfully
|
||||
- **Tests fail**: Check if MQTT broker (mosquitto) is running for integration tests
|
||||
- **UI not updating**: In dev mode, ensure webpack-dev-server is running
|
||||
|
||||
## Deployment and Packaging
|
||||
|
||||
### Creating Releases
|
||||
|
||||
```bash
|
||||
# Prepare release (updates version, changelog)
|
||||
yarn prepare-release
|
||||
|
||||
# Package the application for distribution
|
||||
yarn package
|
||||
|
||||
# Package with Docker (for consistent builds)
|
||||
yarn package-with-docker
|
||||
```
|
||||
|
||||
### Release Workflow
|
||||
|
||||
- **Beta releases**: Create PR to `beta` branch with "feat:" or "fix:" commits
|
||||
- **Production releases**: Create PR to `release` branch with "feat:" or "fix:" commits
|
||||
- Semantic release automatically handles versioning and changelog
|
||||
- Builds are created for Windows, macOS, and Linux
|
||||
|
||||
### Build Artifacts
|
||||
|
||||
- Output directory: `build/`
|
||||
- Supported formats: DMG (macOS), EXE/NSIS (Windows), AppImage/Snap (Linux), AppX (Windows Store)
|
||||
- Code signing is configured via `res/` directory certificates and provisioning profiles
|
||||
|
||||
## Important Notes
|
||||
|
||||
- Always run `yarn build` before starting the application
|
||||
- The app uses Electron (see `package.json` for version)
|
||||
- MQTT communication is handled via [mqttjs](https://github.com/mqttjs/MQTT.js)
|
||||
- All code changes should pass linting (`yarn lint`)
|
||||
- Node.js version requirement: >= 20
|
||||
- The project uses workspace-like structure with separate package.json files for app and backend
|
||||
**Key files:**
|
||||
- `src/server.ts` - Express server, security middleware
|
||||
- `app/webpack.browser.config.mjs` - Browser webpack config
|
||||
- `app/src/browserEventBus.ts` - Socket.io client
|
||||
- `app/src/components/BrowserAuthWrapper.tsx` - Auth dialog
|
||||
- `app/src/index.tsx` - React entry, theme providers
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
|
||||
@@ -1,25 +1,41 @@
|
||||
name: Copilot Agent Setup
|
||||
name: 'Copilot Setup Steps'
|
||||
|
||||
# Automatically run the setup steps when they are changed to allow for easy validation, and
|
||||
# allow manual testing through the repository's "Actions" tab
|
||||
on:
|
||||
workflow_call:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
paths:
|
||||
- .github/workflows/copilot-setup-steps.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/copilot-setup-steps.yml
|
||||
|
||||
jobs:
|
||||
setup:
|
||||
copilot-setup-steps:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
env:
|
||||
TESTS_MQTT_BROKER_HOST: localhost
|
||||
TESTS_MQTT_BROKER_PORT: 1883
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y xvfb mosquitto
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
node-version: '24'
|
||||
|
||||
- name: Get yarn cache directory path
|
||||
id: yarn-cache-dir-path
|
||||
run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT
|
||||
|
||||
|
||||
- name: Cache yarn dependencies
|
||||
uses: actions/cache@v4
|
||||
id: yarn-cache
|
||||
@@ -31,9 +47,6 @@ jobs:
|
||||
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-yarn-
|
||||
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Build project
|
||||
run: yarn build
|
||||
run: yarn
|
||||
@@ -0,0 +1,226 @@
|
||||
name: Docker Browser Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- release
|
||||
- beta
|
||||
paths:
|
||||
- 'Dockerfile.browser'
|
||||
- 'src/server.ts'
|
||||
- 'src/AuthManager.ts'
|
||||
- 'app/**'
|
||||
- 'backend/**'
|
||||
- 'package.json'
|
||||
- 'yarn.lock'
|
||||
- '.github/workflows/docker-browser.yml'
|
||||
- 'tsconfig.json'
|
||||
- 'events/**'
|
||||
schedule:
|
||||
# Run every two weeks (1st and 15th of each month) at 2:00 AM UTC
|
||||
- cron: '0 2 1,15 * *'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
TESTS_MQTT_BROKER_HOST: localhost
|
||||
TESTS_MQTT_BROKER_PORT: 1883
|
||||
|
||||
services:
|
||||
# MQTT broker for testing
|
||||
mosquitto:
|
||||
image: eclipse-mosquitto:2
|
||||
ports:
|
||||
- 1883:1883
|
||||
options: >-
|
||||
--health-cmd "mosquitto_sub -t '$SYS/#' -C 1"
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
--entrypoint sh
|
||||
command: -c "mkdir -p /mosquitto/config && echo 'listener 1883' > /mosquitto/config/mosquitto.conf && echo 'allow_anonymous true' >> /mosquitto/config/mosquitto.conf && exec mosquitto -c /mosquitto/config/mosquitto.conf"
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ghcr.io/${{ github.repository }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=sha,prefix={{branch}}-
|
||||
type=raw,value=latest,enable={{is_default_branch}}
|
||||
|
||||
- name: Build Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.browser
|
||||
platforms: linux/amd64
|
||||
push: false
|
||||
load: true
|
||||
tags: mqtt-explorer:test
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Test Docker image - Basic startup
|
||||
run: |
|
||||
# Start container with test credentials
|
||||
docker run -d \
|
||||
--name mqtt-explorer-test \
|
||||
-p 3000:3000 \
|
||||
-e MQTT_EXPLORER_USERNAME=test \
|
||||
-e MQTT_EXPLORER_PASSWORD=test123 \
|
||||
-e PORT=3000 \
|
||||
mqtt-explorer:test
|
||||
|
||||
# Wait for server to be ready (max 60 seconds)
|
||||
echo "Waiting for server to start..."
|
||||
for i in {1..60}; do
|
||||
if curl -f http://localhost:3000 > /dev/null 2>&1; then
|
||||
echo "Server started successfully after $i seconds"
|
||||
break
|
||||
fi
|
||||
if [ $i -eq 60 ]; then
|
||||
echo "Server failed to start within 60 seconds"
|
||||
docker logs mqtt-explorer-test
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
- name: Test Docker image - Health check
|
||||
run: |
|
||||
# Wait for health check to pass
|
||||
echo "Waiting for health check to pass..."
|
||||
for i in {1..30}; do
|
||||
health=$(docker inspect --format='{{.State.Health.Status}}' mqtt-explorer-test)
|
||||
if [ "$health" = "healthy" ]; then
|
||||
echo "Container is healthy"
|
||||
break
|
||||
fi
|
||||
if [ $i -eq 30 ]; then
|
||||
echo "Health check failed"
|
||||
docker logs mqtt-explorer-test
|
||||
exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
- name: Test Docker image - Verify response
|
||||
run: |
|
||||
# Test that the server responds with HTML
|
||||
response=$(curl -s http://localhost:3000)
|
||||
if echo "$response" | grep -q "MQTT Explorer"; then
|
||||
echo "Server is serving the application correctly"
|
||||
else
|
||||
echo "Server response does not contain expected content"
|
||||
echo "Response: $response"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Test Docker image - Verify data persistence
|
||||
run: |
|
||||
# Check that data directory was created
|
||||
docker exec mqtt-explorer-test sh -c '[ -d /app/data ] && echo "Data directory exists"'
|
||||
|
||||
- name: Clean up test container
|
||||
if: always()
|
||||
run: |
|
||||
docker stop mqtt-explorer-test || true
|
||||
docker rm mqtt-explorer-test || true
|
||||
|
||||
- name: Check Docker image size
|
||||
run: |
|
||||
echo "### Docker Image Size" >> $GITHUB_STEP_SUMMARY
|
||||
docker images mqtt-explorer:test --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
# Get size in bytes for detailed reporting
|
||||
SIZE_BYTES=$(docker inspect mqtt-explorer:test --format='{{.Size}}')
|
||||
SIZE_MB=$((SIZE_BYTES / 1024 / 1024))
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "**Image size**: ${SIZE_MB} MB (${SIZE_BYTES} bytes)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "Image size: ${SIZE_MB} MB"
|
||||
|
||||
- name: Setup Node.js for browser tests
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'yarn'
|
||||
|
||||
- name: Install dependencies for browser tests
|
||||
run: yarn install --frozen-lockfile
|
||||
|
||||
- name: Install Playwright Browsers
|
||||
run: npx playwright install --with-deps chromium
|
||||
|
||||
- name: Start Docker container for browser tests
|
||||
run: |
|
||||
docker run -d \
|
||||
--name mqtt-explorer-browser-test \
|
||||
--network host \
|
||||
-e MQTT_EXPLORER_USERNAME=test \
|
||||
-e MQTT_EXPLORER_PASSWORD=test123 \
|
||||
-e PORT=3000 \
|
||||
mqtt-explorer:test
|
||||
|
||||
# Wait for server to be ready
|
||||
echo "Waiting for Docker container to be ready..."
|
||||
timeout 60 bash -c 'until curl -f http://localhost:3000; do sleep 1; done'
|
||||
echo "Docker container is ready"
|
||||
|
||||
- name: Run browser test suite
|
||||
run: |
|
||||
yarn test:browser
|
||||
env:
|
||||
MQTT_EXPLORER_USERNAME: test
|
||||
MQTT_EXPLORER_PASSWORD: test123
|
||||
BROWSER_MODE_URL: http://localhost:3000
|
||||
|
||||
- name: Clean up browser test container
|
||||
if: always()
|
||||
run: |
|
||||
docker logs mqtt-explorer-browser-test || true
|
||||
docker stop mqtt-explorer-browser-test || true
|
||||
docker rm mqtt-explorer-browser-test || true
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.browser
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v1
|
||||
with:
|
||||
subject-name: ghcr.io/${{ github.repository }}
|
||||
subject-digest: ${{ steps.build.outputs.digest }}
|
||||
push-to-registry: true
|
||||
@@ -28,14 +28,14 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: 24
|
||||
- run: npm install -g yarn
|
||||
- run: yarn
|
||||
- id: create_token # get ReleaseBot access token
|
||||
uses: tibdex/github-app-token@v2
|
||||
uses: actions/create-github-app-token@v1
|
||||
with:
|
||||
app_id: ${{ secrets.RELEASE_BOT_APP_ID }}
|
||||
private_key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}
|
||||
app-id: ${{ secrets.RELEASE_BOT_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}
|
||||
- name: Semantic Release
|
||||
uses: cycjimmy/semantic-release-action@v4
|
||||
id: semantic # Need an `id` for output variables
|
||||
@@ -50,4 +50,7 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
SNAPCRAFT_STORE_CREDENTIALS: ${{ secrets.SNAPCRAFT_STORE_CREDENTIALS }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_APP_SPECIFIC_PASSWORD: ${{ secrets.APPLE_APP_SPECIFIC_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
|
||||
+119
-17
@@ -12,6 +12,8 @@ jobs:
|
||||
options: --user root
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Install Packages
|
||||
run: yarn install --frozen-lockfile
|
||||
- name: Build
|
||||
@@ -19,27 +21,34 @@ jobs:
|
||||
- name: Test
|
||||
run: yarn test
|
||||
|
||||
ui-tests:
|
||||
browser-ui-tests:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest
|
||||
volumes:
|
||||
- ./:/app
|
||||
options: --user root
|
||||
env:
|
||||
TESTS_MQTT_BROKER_HOST: mosquitto
|
||||
TESTS_MQTT_BROKER_PORT: 1883
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Start mosquitto
|
||||
run: mosquitto -c /etc/mosquitto/conf.d/default.conf -d
|
||||
- name: Install Packages
|
||||
run: yarn install --frozen-lockfile
|
||||
- name: Build
|
||||
run: yarn build
|
||||
- name: Run UI Tests
|
||||
- name: Build Browser Mode
|
||||
run: yarn build:server
|
||||
- name: Run Browser UI Tests
|
||||
timeout-minutes: 10
|
||||
run: ./scripts/runUiTests.sh
|
||||
run: ./scripts/runBrowserTests.sh
|
||||
- name: Upload Test Screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ui-test-screenshots
|
||||
name: browser-test-screenshots
|
||||
path: |
|
||||
test-screenshot-*.png
|
||||
retention-days: 30
|
||||
@@ -51,8 +60,15 @@ jobs:
|
||||
volumes:
|
||||
- ./:/app
|
||||
options: --user root
|
||||
env:
|
||||
TESTS_MQTT_BROKER_HOST: localhost
|
||||
TESTS_MQTT_BROKER_PORT: 1883
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Start mosquitto
|
||||
run: mosquitto -c /etc/mosquitto/conf.d/default.conf -d
|
||||
- name: Install Packages
|
||||
run: yarn install --frozen-lockfile
|
||||
- name: Build
|
||||
@@ -61,23 +77,103 @@ jobs:
|
||||
run: yarn ui-test
|
||||
- name: Post-processing
|
||||
run: ./scripts/prepareVideo.sh
|
||||
- uses: hkusu/s3-upload-action@v2
|
||||
id: upload # specify some ID for use in subsequent steps
|
||||
- name: Generate unique base path
|
||||
id: basepath
|
||||
run: |
|
||||
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
|
||||
BASEPATH="pr-${{ github.event.pull_request.number }}-${TIMESTAMP}"
|
||||
echo "basepath=${BASEPATH}" >> $GITHUB_OUTPUT
|
||||
- name: Install AWS CLI v2
|
||||
run: |
|
||||
apt-get update && apt-get install -y unzip
|
||||
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
|
||||
unzip -q awscliv2.zip
|
||||
./aws/install
|
||||
rm -rf aws awscliv2.zip
|
||||
- name: Configure AWS credentials
|
||||
uses: aws-actions/configure-aws-credentials@v4
|
||||
with:
|
||||
aws-access-key-id: ${{ vars.AWS_KEY_ID }}
|
||||
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
|
||||
aws-region: 'eu-central-1'
|
||||
aws-bucket: ${{ vars.AWS_BUCKET }}
|
||||
file-path: './ui-test.gif'
|
||||
content-type: image/gif
|
||||
output-file-url: 'true'
|
||||
- name: Show URL
|
||||
run: echo '${{ steps.upload.outputs.file-url }}'
|
||||
id: artifact-upload-step
|
||||
- run: echo '<picture><img src="${{ steps.upload.outputs.file-url }}"></picture>' >> $GITHUB_STEP_SUMMARY
|
||||
- name: Upload full video to S3
|
||||
env:
|
||||
AWS_BUCKET: ${{ vars.AWS_BUCKET }}
|
||||
BASEPATH: ${{ steps.basepath.outputs.basepath }}
|
||||
run: |
|
||||
# Upload GIF
|
||||
aws s3api put-object \
|
||||
--bucket ${AWS_BUCKET} \
|
||||
--key artifacts/${BASEPATH}/ui-test.gif \
|
||||
--body ./ui-test.gif \
|
||||
--content-type image/gif
|
||||
|
||||
# Upload MP4
|
||||
aws s3api put-object \
|
||||
--bucket ${AWS_BUCKET} \
|
||||
--key artifacts/${BASEPATH}/ui-test.mp4 \
|
||||
--body ./ui-test.mp4 \
|
||||
--content-type video/mp4
|
||||
- name: Upload video segments to S3
|
||||
env:
|
||||
AWS_BUCKET: ${{ vars.AWS_BUCKET }}
|
||||
BASEPATH: ${{ steps.basepath.outputs.basepath }}
|
||||
shell: bash
|
||||
run: |
|
||||
# Upload all GIF segment files if they exist
|
||||
shopt -s nullglob # Make glob return empty list if no matches
|
||||
for segment in segment-*.gif; do
|
||||
echo "Uploading $segment..."
|
||||
aws s3api put-object \
|
||||
--bucket ${AWS_BUCKET} \
|
||||
--key artifacts/${BASEPATH}/${segment} \
|
||||
--body ./${segment} \
|
||||
--content-type image/gif
|
||||
done
|
||||
shopt -u nullglob # Restore default behavior
|
||||
- name: Generate file URLs
|
||||
id: fileurl
|
||||
env:
|
||||
AWS_BUCKET: ${{ vars.AWS_BUCKET }}
|
||||
BASEPATH: ${{ steps.basepath.outputs.basepath }}
|
||||
run: |
|
||||
BASE_URL="https://${AWS_BUCKET}.s3.eu-central-1.amazonaws.com/artifacts/${BASEPATH}"
|
||||
echo "base-url=${BASE_URL}" >> $GITHUB_OUTPUT
|
||||
echo "Uploaded to: ${BASE_URL}"
|
||||
- name: Generate markdown summary
|
||||
id: markdown
|
||||
env:
|
||||
BASE_URL: ${{ steps.fileurl.outputs.base-url }}
|
||||
run: |
|
||||
MARKDOWN=$(node ./scripts/generateMarkdownSummary.js "${BASE_URL}")
|
||||
echo "markdown<<EOF" >> $GITHUB_OUTPUT
|
||||
echo "$MARKDOWN" >> $GITHUB_OUTPUT
|
||||
echo "EOF" >> $GITHUB_OUTPUT
|
||||
- name: Add to workflow summary
|
||||
env:
|
||||
MARKDOWN: ${{ steps.markdown.outputs.markdown }}
|
||||
run: |
|
||||
echo "$MARKDOWN" >> $GITHUB_STEP_SUMMARY
|
||||
- name: Post video to PR
|
||||
uses: actions/github-script@v7
|
||||
env:
|
||||
MARKDOWN: ${{ steps.markdown.outputs.markdown }}
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
script: |
|
||||
const markdown = process.env.MARKDOWN;
|
||||
github.rest.issues.createComment({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: markdown
|
||||
});
|
||||
|
||||
test-browser:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TESTS_MQTT_BROKER_HOST: localhost
|
||||
TESTS_MQTT_BROKER_PORT: 1883
|
||||
services:
|
||||
mosquitto:
|
||||
image: eclipse-mosquitto:2
|
||||
@@ -88,14 +184,20 @@ jobs:
|
||||
--health-interval 10s
|
||||
--health-timeout 5s
|
||||
--health-retries 5
|
||||
--entrypoint sh
|
||||
command: -c "mkdir -p /mosquitto/config && echo 'listener 1883' > /mosquitto/config/mosquitto.conf && echo 'allow_anonymous true' >> /mosquitto/config/mosquitto.conf && exec mosquitto -c /mosquitto/config/mosquitto.conf"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.head.sha }}
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
- name: Install Dependencies
|
||||
run: yarn install --frozen-lockfile
|
||||
- name: Install Playwright Browsers
|
||||
run: npx playwright install --with-deps chromium
|
||||
- name: Build Browser Mode
|
||||
run: yarn build:server
|
||||
- name: Test App
|
||||
|
||||
@@ -11,7 +11,7 @@ jobs:
|
||||
ref: gh-pages
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
node-version: '24'
|
||||
- run: npm install
|
||||
- run: npm run readme
|
||||
- uses: stefanzweifel/git-auto-commit-action@v5
|
||||
|
||||
+19
@@ -17,3 +17,22 @@ test-mcp-introspection.js
|
||||
|
||||
/data
|
||||
test-screenshot-*.png
|
||||
test-expand-*.png
|
||||
browser-debug-screenshot.png
|
||||
|
||||
app/.webpack-cache
|
||||
|
||||
# Temporary files
|
||||
/tmp
|
||||
|
||||
# Demo video artifacts
|
||||
scenes.json
|
||||
segment-*.mp4
|
||||
segment-*.gif
|
||||
ui-test.mp4
|
||||
ui-test.gif
|
||||
app.mp4
|
||||
app2.mp4
|
||||
app720.gif
|
||||
qrawvideorgb24.yuv
|
||||
intro.png
|
||||
+114
@@ -112,6 +112,120 @@ Both Electron IPC and Socket.io implement the same `EventBusInterface`, allowing
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Production Deployment
|
||||
|
||||
**CRITICAL**: The following security measures must be implemented for production deployments:
|
||||
|
||||
#### 1. HTTPS/TLS Encryption
|
||||
Always use HTTPS in production to protect credentials and MQTT data in transit:
|
||||
|
||||
```bash
|
||||
# Use a reverse proxy like nginx or Apache with TLS
|
||||
# Example nginx configuration:
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name mqtt-explorer.example.com;
|
||||
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/key.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 2. Environment Variables for Credentials
|
||||
**NEVER** use generated credentials in production. Always set secure credentials via environment variables:
|
||||
|
||||
```bash
|
||||
export MQTT_EXPLORER_USERNAME=your_secure_username
|
||||
export MQTT_EXPLORER_PASSWORD=your_strong_password_min_12_chars
|
||||
export NODE_ENV=production
|
||||
yarn start:server
|
||||
```
|
||||
|
||||
#### 3. CORS Configuration
|
||||
Configure allowed origins instead of using the wildcard (`*`):
|
||||
|
||||
```bash
|
||||
# Single origin
|
||||
export ALLOWED_ORIGINS=https://mqtt-explorer.example.com
|
||||
|
||||
# Multiple origins (comma-separated)
|
||||
export ALLOWED_ORIGINS=https://app1.example.com,https://app2.example.com
|
||||
|
||||
yarn start:server
|
||||
```
|
||||
|
||||
In production with `NODE_ENV=production`, wildcard CORS is automatically disabled for security.
|
||||
|
||||
#### 4. Network Security
|
||||
- Deploy behind a firewall or VPN
|
||||
- Use IP whitelisting if possible
|
||||
- Implement network-level rate limiting
|
||||
- Monitor for suspicious connection patterns
|
||||
|
||||
#### 5. File Upload Security
|
||||
The server implements several protections against malicious file uploads:
|
||||
- Maximum file size: 16MB (configurable via `MAX_FILE_SIZE` constant)
|
||||
- Path traversal protection via filename sanitization
|
||||
- Files stored in isolated directories
|
||||
- Real path validation to prevent directory escapes
|
||||
|
||||
#### 6. Authentication Security
|
||||
The server implements multiple layers of authentication security:
|
||||
- **Password Hashing**: bcrypt with 10 rounds
|
||||
- **Timing Attack Protection**: Constant-time string comparison for usernames
|
||||
- **Rate Limiting**: Maximum 5 failed attempts per IP per 15 minutes
|
||||
- **Session Tracking**: Failed attempts are tracked per client IP
|
||||
- **No Credential Logging**: In production mode, credentials are not logged
|
||||
|
||||
#### 7. HTTP Security Headers
|
||||
The server uses helmet.js to set security headers:
|
||||
- Content Security Policy (CSP)
|
||||
- HTTP Strict Transport Security (HSTS) in production
|
||||
- X-Content-Type-Options: nosniff
|
||||
- X-Frame-Options: DENY
|
||||
- X-XSS-Protection
|
||||
|
||||
### Security Best Practices
|
||||
|
||||
1. **Rotate Credentials Regularly**: Change authentication credentials periodically
|
||||
2. **Monitor Logs**: Watch for authentication failures and unusual patterns
|
||||
3. **Keep Dependencies Updated**: Run `yarn audit` regularly
|
||||
4. **Limit Network Exposure**: Don't expose the server directly to the internet
|
||||
5. **Use Strong Passwords**: Minimum 12 characters with mixed case, numbers, and symbols
|
||||
6. **Enable Logging**: Monitor access logs and error logs
|
||||
7. **Regular Backups**: Back up configuration and certificate data
|
||||
8. **Principle of Least Privilege**: Run the server with minimal required permissions
|
||||
|
||||
### Vulnerability Reporting
|
||||
|
||||
If you discover a security vulnerability, please report it via:
|
||||
- GitHub Security Advisories
|
||||
- Email to the maintainer
|
||||
- Do NOT create public issues for security vulnerabilities
|
||||
|
||||
### Security Audit Log
|
||||
|
||||
- **2024-12**: Initial security review and hardening
|
||||
- Added helmet.js for HTTP security headers
|
||||
- Implemented rate limiting for authentication
|
||||
- Added path traversal protection
|
||||
- Implemented constant-time comparison for credentials
|
||||
- Added input validation and size limits
|
||||
- Removed credential logging in production
|
||||
- Added configurable CORS origins
|
||||
- Created comprehensive security test suite
|
||||
|
||||
## Security Considerations (Legacy)
|
||||
|
||||
1. **HTTPS**: For production, always use HTTPS to encrypt credentials and MQTT data
|
||||
2. **Authentication**: Keep credentials secure and rotate them regularly
|
||||
3. **Network**: Ensure the server is on a trusted network or behind a firewall
|
||||
|
||||
@@ -10,6 +10,57 @@ MQTT Explorer uses GitHub Actions for continuous integration and testing. The pi
|
||||
|
||||
This workflow runs on pull requests to `master`, `beta`, and `release` branches.
|
||||
|
||||
### Docker Browser Build Workflow (`.github/workflows/docker-browser.yml`)
|
||||
|
||||
This workflow builds and publishes a Docker image for the browser mode.
|
||||
|
||||
**Triggers**:
|
||||
- Push to `master`, `beta`, or `release` branches (when relevant files change)
|
||||
- Schedule: Runs every two weeks (1st and 15th of each month at 2:00 AM UTC)
|
||||
- Manual trigger via workflow_dispatch
|
||||
|
||||
**Platforms**:
|
||||
- linux/amd64 (x86-64)
|
||||
- linux/arm64 (Raspberry Pi 3/4/5, Apple Silicon)
|
||||
- linux/arm/v7 (Raspberry Pi 2/3)
|
||||
|
||||
**Image Registry**: GitHub Container Registry (ghcr.io/thomasnordquist/mqtt-explorer)
|
||||
|
||||
**Tags**:
|
||||
- `latest` - Latest build from master branch
|
||||
- `master` - Latest build from master
|
||||
- `beta` - Latest build from beta branch
|
||||
- `release` - Latest build from release branch
|
||||
- `<branch>-<sha>` - Specific commit builds
|
||||
|
||||
**Steps**:
|
||||
1. Build Docker image with multi-stage build
|
||||
2. Test basic startup with test credentials
|
||||
3. Test health check
|
||||
4. Verify HTTP response
|
||||
5. Test data directory creation
|
||||
6. Check Docker image size
|
||||
7. Setup Node.js 24 for browser tests
|
||||
8. Install dependencies for browser tests
|
||||
9. Install Playwright browsers (`npx playwright install --with-deps chromium`)
|
||||
10. Start container for browser tests
|
||||
11. Run browser test suite with Playwright
|
||||
12. Push image to GitHub Container Registry
|
||||
13. Generate build attestation for supply chain security
|
||||
|
||||
**Image Features**:
|
||||
- Multi-stage build for minimal size
|
||||
- Alpine Linux base with Node.js 24 (~200MB final image)
|
||||
- Multi-platform support (amd64, arm64, arm/v7)
|
||||
- Non-root user (UID 1001)
|
||||
- Health check endpoint
|
||||
- Proper signal handling with dumb-init
|
||||
- Persistent data volume at `/app/data`
|
||||
|
||||
### Test Workflow (`.github/workflows/tests.yml`)
|
||||
|
||||
This workflow runs on pull requests to `master`, `beta`, and `release` branches.
|
||||
|
||||
#### Jobs
|
||||
|
||||
##### 1. `test` - Electron Mode Tests
|
||||
@@ -17,34 +68,45 @@ This workflow runs on pull requests to `master`, `beta`, and `release` branches.
|
||||
Tests the traditional Electron desktop application:
|
||||
|
||||
- **Environment**: Custom Docker container (`ghcr.io/thomasnordquist/mqtt-explorer-ui-tests:latest`)
|
||||
- Based on Node.js 24
|
||||
- Includes Xvfb for headless display
|
||||
- Includes FFmpeg for video recording
|
||||
- Includes Mosquitto MQTT broker
|
||||
- **Playwright browsers pre-installed** with system dependencies
|
||||
- **Steps**:
|
||||
1. Install dependencies with frozen lockfile
|
||||
2. Build the Electron application
|
||||
3. Run unit tests (app + backend)
|
||||
4. Run UI tests with video recording
|
||||
5. Upload test video to S3
|
||||
6. Display test results in GitHub summary
|
||||
5. Upload test video to S3 with 90-day expiration tag
|
||||
6. Post demo video to PR as comment
|
||||
7. Display test results in GitHub summary
|
||||
|
||||
**Artifacts**: UI test video (GIF format) uploaded to S3
|
||||
**Artifacts**:
|
||||
- UI test video (GIF format) uploaded to S3 using AWS CLI
|
||||
- Video is tagged with `expiration=90days` for automatic lifecycle deletion
|
||||
- Video is posted to the PR thread as an embedded image
|
||||
- Videos expire after 90 days via S3 lifecycle policy
|
||||
|
||||
##### 2. `test-browser` - Browser Mode Tests
|
||||
|
||||
Tests the new browser/server mode:
|
||||
|
||||
- **Environment**: Ubuntu latest with Node.js 20
|
||||
- **Environment**: Ubuntu latest with Node.js 24
|
||||
- **Services**:
|
||||
- **Mosquitto MQTT Broker**: Eclipse Mosquitto v2 on port 1883
|
||||
- Health checks enabled
|
||||
- Anonymous connections allowed
|
||||
- **Steps**:
|
||||
1. Setup Node.js 20
|
||||
1. Setup Node.js 24
|
||||
2. Install dependencies
|
||||
3. Build browser mode (`yarn build:server`)
|
||||
4. Run unit tests (app + backend)
|
||||
5. Start server in background with test credentials
|
||||
6. Wait for server to be ready
|
||||
7. Run browser smoke tests
|
||||
8. Clean up server process
|
||||
3. Install Playwright browsers (`npx playwright install --with-deps chromium`)
|
||||
4. Build browser mode (`yarn build:server`)
|
||||
5. Run unit tests (app + backend)
|
||||
6. Start server in background with test credentials
|
||||
7. Wait for server to be ready
|
||||
8. Run browser smoke tests
|
||||
9. Clean up server process
|
||||
|
||||
**Environment Variables**:
|
||||
- `MQTT_EXPLORER_USERNAME=test`
|
||||
@@ -92,6 +154,35 @@ Example:
|
||||
|
||||
## Local Testing
|
||||
|
||||
### Docker Browser Mode
|
||||
|
||||
```bash
|
||||
# Build the image locally (for your platform)
|
||||
docker build -f Dockerfile.browser -t mqtt-explorer:local .
|
||||
|
||||
# Build for specific platform (e.g., Raspberry Pi)
|
||||
docker buildx build --platform linux/arm64 -f Dockerfile.browser -t mqtt-explorer:local-arm64 .
|
||||
|
||||
# Run the container
|
||||
docker run -d \
|
||||
-p 3000:3000 \
|
||||
-e MQTT_EXPLORER_USERNAME=test \
|
||||
-e MQTT_EXPLORER_PASSWORD=test123 \
|
||||
mqtt-explorer:local
|
||||
|
||||
# Test the server
|
||||
curl http://localhost:3000
|
||||
|
||||
# Check logs
|
||||
docker logs <container-id>
|
||||
|
||||
# Stop and remove
|
||||
docker stop <container-id>
|
||||
docker rm <container-id>
|
||||
```
|
||||
|
||||
See [DOCKER.md](DOCKER.md) for complete documentation.
|
||||
|
||||
### Electron Mode
|
||||
|
||||
```bash
|
||||
@@ -127,6 +218,93 @@ The repository includes a devcontainer configuration that automatically sets up:
|
||||
|
||||
See [.devcontainer/README.md](.devcontainer/README.md) for details.
|
||||
|
||||
## S3 Configuration for Demo Videos
|
||||
|
||||
### Required S3 Lifecycle Policy
|
||||
|
||||
Demo videos uploaded from PRs are tagged with `expiration=90days` and require an S3 lifecycle policy to automatically delete them after 90 days.
|
||||
|
||||
**Important**: The `video.mp4` file in the gh-pages branch is NOT tagged and will NOT expire.
|
||||
|
||||
#### Setting up the Lifecycle Policy
|
||||
|
||||
1. Create a file named `s3-lifecycle-pr-videos.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"Rules": [
|
||||
{
|
||||
"ID": "ExpirePRDemoVideosAfter90Days",
|
||||
"Status": "Enabled",
|
||||
"Filter": {
|
||||
"Tag": {
|
||||
"Key": "expiration",
|
||||
"Value": "90days"
|
||||
}
|
||||
},
|
||||
"Expiration": {
|
||||
"Days": 90
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
2. Apply the policy to your S3 bucket:
|
||||
|
||||
```bash
|
||||
aws s3api put-bucket-lifecycle-configuration \
|
||||
--bucket YOUR_BUCKET_NAME \
|
||||
--lifecycle-configuration file://s3-lifecycle-pr-videos.json
|
||||
```
|
||||
|
||||
3. Verify the policy:
|
||||
|
||||
```bash
|
||||
aws s3api get-bucket-lifecycle-configuration --bucket YOUR_BUCKET_NAME
|
||||
```
|
||||
|
||||
#### How It Works
|
||||
|
||||
- **PR demo videos**: Uploaded with filename pattern `pr-{number}-{timestamp}.gif` and tagged with:
|
||||
- `expiration=90days` - Used by lifecycle policy for automatic deletion
|
||||
- `Source=github-actions` - Identifies source of upload
|
||||
- `Type=pr-demo-video` - Categorizes the object type
|
||||
- **S3 lifecycle rule**: Automatically deletes objects tagged with `expiration=90days` after 90 days
|
||||
- **Upload mechanism**: AWS CLI v2 is installed directly, authentication is configured via `aws-actions/configure-aws-credentials@v4` GitHub Action, then `aws s3api put-object` is used with object tagging support
|
||||
- **gh-pages video**: `video.mp4` in gh-pages branch is served from GitHub Pages, not S3, so it persists indefinitely
|
||||
|
||||
#### Required AWS Credentials
|
||||
|
||||
The workflow requires the following secrets/variables:
|
||||
- `vars.AWS_KEY_ID` - AWS access key ID (requires `s3:PutObject` and `s3:PutObjectTagging` permissions)
|
||||
- `secrets.AWS_SECRET_ACCESS_KEY` - AWS secret access key
|
||||
- `vars.AWS_BUCKET` - S3 bucket name
|
||||
- AWS region: `eu-central-1` (hardcoded in workflow)
|
||||
|
||||
The S3 bucket must have:
|
||||
- **Bucket policy for public read access**: Since ACLs are disabled (BucketOwnerEnforced), a bucket policy must grant public read access to uploaded objects
|
||||
- Object tagging enabled
|
||||
- Lifecycle policy configured as described above
|
||||
|
||||
**Example S3 Bucket Policy for Public Read Access**:
|
||||
```json
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "PublicReadGetObject",
|
||||
"Effect": "Allow",
|
||||
"Principal": "*",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::YOUR_BUCKET_NAME/*"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The workflow uses AWS CLI v2 installed directly and `aws-actions/configure-aws-credentials@v4` action for secure credential management.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Browser Tests Failing
|
||||
@@ -142,6 +320,7 @@ See [.devcontainer/README.md](.devcontainer/README.md) for details.
|
||||
|
||||
## Future Improvements
|
||||
|
||||
- [x] Add Playwright browser installation to workflows (browser tests can now use Playwright)
|
||||
- [ ] Add E2E browser tests with Playwright
|
||||
- [ ] Test WebSocket connections in browser mode
|
||||
- [ ] Add performance benchmarks
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
# MQTT Explorer - Docker Browser Mode
|
||||
|
||||
Docker image for running MQTT Explorer in browser mode.
|
||||
|
||||
## Try It Now
|
||||
|
||||
[](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/thomasnordquist/MQTT-Explorer/master/docker-compose.yml)
|
||||
|
||||
Click the badge above to instantly try MQTT Explorer in your browser using Play with Docker (requires free Docker Hub account).
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Using Pre-built Image
|
||||
|
||||
Pull and run the latest image from GitHub Container Registry:
|
||||
|
||||
```bash
|
||||
docker pull ghcr.io/thomasnordquist/mqtt-explorer:latest
|
||||
|
||||
docker run -d \
|
||||
-p 3000:3000 \
|
||||
-e MQTT_EXPLORER_USERNAME=admin \
|
||||
-e MQTT_EXPLORER_PASSWORD=your_secure_password \
|
||||
-v mqtt-explorer-data:/app/data \
|
||||
--name mqtt-explorer \
|
||||
ghcr.io/thomasnordquist/mqtt-explorer:latest
|
||||
```
|
||||
|
||||
Access the application at `http://localhost:3000`
|
||||
|
||||
### Using Docker Compose
|
||||
|
||||
Create a `docker-compose.yml` file:
|
||||
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
mqtt-explorer:
|
||||
image: ghcr.io/thomasnordquist/mqtt-explorer:latest
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- MQTT_EXPLORER_USERNAME=admin
|
||||
- MQTT_EXPLORER_PASSWORD=your_secure_password
|
||||
- PORT=3000
|
||||
volumes:
|
||||
- mqtt-explorer-data:/app/data
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
mqtt-explorer-data:
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Required | Default | Description |
|
||||
|----------|----------|---------|-------------|
|
||||
| `MQTT_EXPLORER_USERNAME` | No | Generated | Username for authentication |
|
||||
| `MQTT_EXPLORER_PASSWORD` | No | Generated | Password for authentication |
|
||||
| `MQTT_EXPLORER_SKIP_AUTH` | No | `false` | Set to `true` to disable authentication (use only behind a secure proxy!) |
|
||||
| `PORT` | No | `3000` | Port the server listens on |
|
||||
| `ALLOWED_ORIGINS` | No | `*` | Comma-separated list of allowed CORS origins |
|
||||
| `NODE_ENV` | No | - | Set to `production` for production deployments |
|
||||
|
||||
### Authentication Modes
|
||||
|
||||
**Standard Mode (Default):**
|
||||
- Requires username and password for access
|
||||
- Credentials can be set via environment variables or auto-generated
|
||||
- Auto-generated credentials are logged on first startup and saved to `/app/data/credentials.json`
|
||||
|
||||
**Skip Authentication Mode (Use with caution!):**
|
||||
```bash
|
||||
docker run -d -p 3000:3000 \
|
||||
-e MQTT_EXPLORER_SKIP_AUTH=true \
|
||||
ghcr.io/thomasnordquist/mqtt-explorer:latest
|
||||
```
|
||||
|
||||
⚠️ **WARNING**: When `MQTT_EXPLORER_SKIP_AUTH=true`, the application is **completely open** without any authentication. This should **only be used** when MQTT Explorer is deployed behind a secure authentication proxy (e.g., OAuth2 Proxy, Authelia, Nginx with auth_request) or in a trusted private network.
|
||||
|
||||
**Recommended use case**: Integration with enterprise SSO systems where authentication is handled by a reverse proxy.
|
||||
|
||||
**Note**: If credentials are not provided and auth is not skipped, they will be auto-generated and stored in `/app/data/credentials.json`. Check the container logs to see the generated credentials:
|
||||
|
||||
```bash
|
||||
docker logs mqtt-explorer
|
||||
```
|
||||
|
||||
## Data Persistence
|
||||
|
||||
The container stores data in `/app/data`, including:
|
||||
- User credentials (`credentials.json`)
|
||||
- Connection settings (`settings.json`)
|
||||
- Uploaded certificates (`certificates/`)
|
||||
- File uploads (`uploads/`)
|
||||
|
||||
Mount a volume to persist data across container restarts:
|
||||
|
||||
```bash
|
||||
docker run -v mqtt-explorer-data:/app/data ...
|
||||
```
|
||||
|
||||
## Building from Source
|
||||
|
||||
Build the Docker image locally:
|
||||
|
||||
```bash
|
||||
docker build -f Dockerfile.browser -t mqtt-explorer:local .
|
||||
```
|
||||
|
||||
Run the locally built image:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
-p 3000:3000 \
|
||||
-e MQTT_EXPLORER_USERNAME=admin \
|
||||
-e MQTT_EXPLORER_PASSWORD=secret \
|
||||
mqtt-explorer:local
|
||||
```
|
||||
|
||||
## Health Check
|
||||
|
||||
The container includes a health check that runs every 30 seconds. Check the health status:
|
||||
|
||||
```bash
|
||||
docker inspect --format='{{.State.Health.Status}}' mqtt-explorer
|
||||
```
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
1. **Use HTTPS in Production**: Put the container behind a reverse proxy (nginx, Traefik) with HTTPS
|
||||
2. **Set Strong Credentials**: Always set custom credentials via environment variables
|
||||
3. **Network Isolation**: Run in a private network when possible
|
||||
4. **Update Regularly**: Pull the latest image regularly for security updates
|
||||
|
||||
### Example with Nginx Reverse Proxy
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name mqtt-explorer.example.com;
|
||||
|
||||
ssl_certificate /path/to/cert.pem;
|
||||
ssl_certificate_key /path/to/key.pem;
|
||||
|
||||
location / {
|
||||
proxy_pass http://localhost:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Container won't start
|
||||
|
||||
Check the logs:
|
||||
```bash
|
||||
docker logs mqtt-explorer
|
||||
```
|
||||
|
||||
### Can't access the application
|
||||
|
||||
1. Verify the container is running: `docker ps`
|
||||
2. Check the port mapping: `docker port mqtt-explorer`
|
||||
3. Test connectivity: `curl http://localhost:3000`
|
||||
|
||||
### Authentication issues
|
||||
|
||||
1. Check generated credentials in logs: `docker logs mqtt-explorer`
|
||||
2. Verify environment variables: `docker inspect mqtt-explorer`
|
||||
3. Reset credentials by removing the data volume and restarting
|
||||
|
||||
### Permission issues
|
||||
|
||||
The container runs as a non-root user (UID 1001). If mounting host directories, ensure they're writable:
|
||||
|
||||
```bash
|
||||
chown -R 1001:1001 /path/to/host/data
|
||||
docker run -v /path/to/host/data:/app/data ...
|
||||
```
|
||||
|
||||
## Available Tags
|
||||
|
||||
- `latest` - Latest stable version from the master branch
|
||||
- `master` - Latest build from master branch
|
||||
- `beta` - Latest beta version
|
||||
- `release` - Latest release version
|
||||
- `master-<sha>` - Specific commit from master
|
||||
- `beta-<sha>` - Specific commit from beta
|
||||
- `release-<sha>` - Specific commit from release
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
The Docker image is built for multiple architectures:
|
||||
- `linux/amd64` - x86-64 (standard PCs, servers)
|
||||
- `linux/arm64` - ARM 64-bit (Raspberry Pi 3/4/5, Apple Silicon)
|
||||
- `linux/arm/v7` - ARM 32-bit (Raspberry Pi 2/3)
|
||||
|
||||
## One-Click Deployment Options
|
||||
|
||||
### Play with Docker (Free)
|
||||
|
||||
Try MQTT Explorer instantly in your browser without installing anything:
|
||||
|
||||
[](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/thomasnordquist/MQTT-Explorer/master/docker-compose.yml)
|
||||
|
||||
- **No installation required** - Runs entirely in your browser
|
||||
- **Free to use** - Requires only a Docker Hub account
|
||||
- **Perfect for demos** - Great for testing and demonstrations
|
||||
- **4-hour sessions** - Sessions automatically expire after 4 hours
|
||||
|
||||
### Cloud Platforms
|
||||
|
||||
Deploy MQTT Explorer to various cloud platforms with one click:
|
||||
|
||||
#### DigitalOcean App Platform
|
||||
|
||||
[](https://cloud.digitalocean.com/apps/new?repo=https://github.com/thomasnordquist/MQTT-Explorer/tree/master&refcode=docker)
|
||||
|
||||
- Automatically detects Docker configuration
|
||||
- Managed platform with auto-scaling
|
||||
- Starting at $5/month
|
||||
|
||||
#### Koyeb
|
||||
|
||||
[](https://app.koyeb.com/deploy?type=docker&name=mqtt-explorer&image=ghcr.io/thomasnordquist/mqtt-explorer:latest&ports=3000;http;/)
|
||||
|
||||
- Deploy directly from Docker image
|
||||
- Global edge network
|
||||
- Free tier available
|
||||
|
||||
**Note:** Remember to set the environment variables `MQTT_EXPLORER_USERNAME` and `MQTT_EXPLORER_PASSWORD` when deploying to cloud platforms.
|
||||
|
||||
## License
|
||||
|
||||
See the main [LICENSE.md](LICENSE.md) file.
|
||||
+12
-1
@@ -1,4 +1,4 @@
|
||||
FROM node:20
|
||||
FROM node:24
|
||||
|
||||
RUN DEBIAN_FRONTEND="noninteractive" apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates nano ffmpeg xvfb git-core tmux locales mosquitto x11vnc
|
||||
@@ -10,6 +10,17 @@ ENV LANG en_US.UTF-8
|
||||
ENV LANGUAGE en_US:en
|
||||
ENV LC_ALL en_US.UTF-8
|
||||
|
||||
# Configure mosquitto for anonymous access (required for tests)
|
||||
RUN mkdir -p /etc/mosquitto/conf.d && \
|
||||
echo "listener 1883" > /etc/mosquitto/conf.d/default.conf && \
|
||||
echo "allow_anonymous true" >> /etc/mosquitto/conf.d/default.conf && \
|
||||
echo "persistence false" >> /etc/mosquitto/conf.d/default.conf
|
||||
|
||||
# Install Playwright and browsers
|
||||
# This ensures Playwright browsers are pre-installed in the container
|
||||
RUN npm install -g playwright@1.57.0 && \
|
||||
npx playwright install --with-deps chromium
|
||||
|
||||
CMD /bin/bash
|
||||
|
||||
VOLUME /app
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Multi-stage build for MQTT Explorer Browser Mode
|
||||
# Stage 1: Build and prepare production dependencies
|
||||
FROM node:24-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
# Copy all source files and dependencies
|
||||
COPY package.json yarn.lock ./
|
||||
COPY tsconfig.json ./
|
||||
COPY src ./src
|
||||
COPY backend ./backend
|
||||
COPY events ./events
|
||||
COPY app ./app
|
||||
|
||||
# Install ALL dependencies (needed for build)
|
||||
RUN yarn install --frozen-lockfile --network-timeout 100000
|
||||
|
||||
# Build the application (compiles TypeScript and webpack bundles)
|
||||
RUN yarn build:server
|
||||
|
||||
# Remove dev dependencies, keeping only production dependencies
|
||||
RUN yarn install --production --frozen-lockfile --network-timeout 100000 && \
|
||||
yarn cache clean && \
|
||||
rm -rf /tmp/*
|
||||
|
||||
# Stage 2: Production
|
||||
FROM node:24-alpine
|
||||
|
||||
# Install dumb-init in a single layer
|
||||
RUN apk add --no-cache dumb-init
|
||||
|
||||
# Create app user in a single layer
|
||||
RUN addgroup -g 1001 -S mqttexplorer && \
|
||||
adduser -u 1001 -S mqttexplorer -G mqttexplorer
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy ONLY the compiled dist folder (contains compiled TypeScript)
|
||||
COPY --from=builder --chown=mqttexplorer:mqttexplorer /build/dist ./dist
|
||||
|
||||
# Copy ONLY the built frontend app
|
||||
COPY --from=builder --chown=mqttexplorer:mqttexplorer /build/app/build ./app/build
|
||||
COPY --from=builder --chown=mqttexplorer:mqttexplorer /build/app/index.html ./app/
|
||||
|
||||
# Copy runtime node_modules (production dependencies only)
|
||||
COPY --from=builder --chown=mqttexplorer:mqttexplorer /build/node_modules ./node_modules
|
||||
|
||||
# Copy package.json for version info (needed by server)
|
||||
COPY --from=builder --chown=mqttexplorer:mqttexplorer /build/package.json ./
|
||||
|
||||
# Create data directory for persistent storage
|
||||
RUN mkdir -p /app/data && \
|
||||
chown -R mqttexplorer:mqttexplorer /app/data
|
||||
|
||||
# Switch to non-root user
|
||||
USER mqttexplorer
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3000
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
|
||||
CMD node -e "const http = require('http'); const req = http.get('http://localhost:3000', (r) => process.exit(r.statusCode === 200 ? 0 : 1)); req.on('error', () => process.exit(1));"
|
||||
|
||||
# Use dumb-init to handle signals properly
|
||||
ENTRYPOINT ["/usr/bin/dumb-init", "--"]
|
||||
|
||||
# Start the server
|
||||
CMD ["node", "dist/src/server.js"]
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
When redistributing, the attribution page may not be altered or made less accessible without explicit approval.
|
||||
When distributing, the attribution and donation page may not be altered or made less accessible without explicit approval.
|
||||
|
||||
# Creative Commons Attribution-ShareAlike 4.0 International
|
||||
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# macOS Notarization Setup
|
||||
|
||||
This document explains how to set up notarization for macOS builds of MQTT Explorer.
|
||||
|
||||
## Overview
|
||||
|
||||
macOS notarization is a security feature required by Apple for all software distributed outside the Mac App Store. Starting with macOS 10.15 (Catalina), all software must be notarized to run without warnings on macOS.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. An active Apple Developer account
|
||||
2. Xcode command line tools installed on the build machine
|
||||
3. An app-specific password for notarization
|
||||
|
||||
## Setup Steps
|
||||
|
||||
### 1. Create an App-Specific Password
|
||||
|
||||
1. Sign in to [appleid.apple.com](https://appleid.apple.com)
|
||||
2. Navigate to "Sign-In and Security" section
|
||||
3. Under "App-Specific Passwords", click "Generate an app-specific password"
|
||||
4. Enter a descriptive name (e.g., "MQTT Explorer Notarization")
|
||||
5. Copy the generated password (you won't be able to see it again)
|
||||
|
||||
### 2. Find Your Team ID
|
||||
|
||||
1. Sign in to [developer.apple.com](https://developer.apple.com/account)
|
||||
2. Navigate to "Membership Details"
|
||||
3. Copy your Team ID (a 10-character alphanumeric string)
|
||||
|
||||
### 3. Configure GitHub Secrets
|
||||
|
||||
Add the following secrets to your GitHub repository:
|
||||
|
||||
- `APPLE_ID`: Your Apple ID email address (e.g., `your.email@example.com`)
|
||||
- `APPLE_APP_SPECIFIC_PASSWORD`: The app-specific password created in step 1
|
||||
- `APPLE_TEAM_ID`: Your Team ID from step 2
|
||||
|
||||
To add secrets:
|
||||
1. Go to your repository on GitHub
|
||||
2. Navigate to Settings → Secrets and variables → Actions
|
||||
3. Click "New repository secret" for each of the above
|
||||
|
||||
## How It Works
|
||||
|
||||
### Build Configuration
|
||||
|
||||
The notarization process is configured in `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"build": {
|
||||
"mac": {
|
||||
"hardenedRuntime": true,
|
||||
"gatekeeperAssess": false,
|
||||
"entitlements": "res/entitlements.mac.plist",
|
||||
"entitlementsInherit": "res/entitlements.mac.inherit.plist"
|
||||
},
|
||||
"afterSign": "./dist/scripts/notarize.js"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Notarization Script
|
||||
|
||||
The `scripts/notarize.ts` script handles the notarization process:
|
||||
|
||||
1. Checks if the build is for macOS
|
||||
2. Verifies that required environment variables are set
|
||||
3. Submits the app to Apple's notarization service
|
||||
4. Waits for notarization to complete
|
||||
5. Staples the notarization ticket to the app
|
||||
|
||||
### Entitlements
|
||||
|
||||
Different entitlements are used for different build types:
|
||||
|
||||
- **DMG builds** (regular distribution):
|
||||
- `res/entitlements.mac.plist` - Main entitlements
|
||||
- `res/entitlements.mac.inherit.plist` - Inherited entitlements for child processes
|
||||
|
||||
- **MAS builds** (Mac App Store):
|
||||
- `res/entitlements.mas.plist` - App Store specific entitlements
|
||||
|
||||
### CI/CD Integration
|
||||
|
||||
The GitHub Actions workflow (`platform-builds.yml`) automatically:
|
||||
|
||||
1. Builds the macOS app when code is pushed to `release` or `beta` branches
|
||||
2. Signs the app with the developer certificate
|
||||
3. Notarizes the app using the configured secrets
|
||||
4. Publishes the notarized app to GitHub releases
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Notarization Fails
|
||||
|
||||
If notarization fails, check:
|
||||
|
||||
1. **Credentials**: Ensure all three secrets are correctly set in GitHub
|
||||
2. **App-specific password**: Verify it hasn't expired or been revoked
|
||||
3. **Team ID**: Confirm it matches your developer account
|
||||
4. **Entitlements**: Ensure the entitlements files are valid and appropriate for your app
|
||||
|
||||
### Checking Notarization Status
|
||||
|
||||
You can check the notarization status of a built app:
|
||||
|
||||
```bash
|
||||
# Check if an app is notarized
|
||||
spctl -a -vv /path/to/MQTT\ Explorer.app
|
||||
|
||||
# Check notarization history
|
||||
xcrun notarytool history --apple-id your.email@example.com --team-id YOUR_TEAM_ID
|
||||
```
|
||||
|
||||
### Local Testing
|
||||
|
||||
To test notarization locally:
|
||||
|
||||
```bash
|
||||
# Set environment variables
|
||||
export APPLE_ID="your.email@example.com"
|
||||
export APPLE_APP_SPECIFIC_PASSWORD="your-app-specific-password"
|
||||
export APPLE_TEAM_ID="YOUR_TEAM_ID"
|
||||
|
||||
# Build and notarize
|
||||
yarn build
|
||||
yarn package mac
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
- Never commit Apple credentials to the repository
|
||||
- Use app-specific passwords, not your main Apple ID password
|
||||
- Rotate app-specific passwords periodically
|
||||
- Limit access to GitHub secrets to trusted maintainers only
|
||||
|
||||
## References
|
||||
|
||||
- [Apple Notarization Documentation](https://developer.apple.com/documentation/security/notarizing_macos_software_before_distribution)
|
||||
- [electron-builder Code Signing](https://www.electron.build/code-signing)
|
||||
- [@electron/notarize](https://github.com/electron/notarize)
|
||||
@@ -54,6 +54,27 @@ yarn start:server
|
||||
|
||||
Then open your browser to `http://localhost:3000`. For more details, see [BROWSER_MODE.md](BROWSER_MODE.md).
|
||||
|
||||
### Docker (Browser Mode)
|
||||
|
||||
[](https://labs.play-with-docker.com/?stack=https://raw.githubusercontent.com/thomasnordquist/MQTT-Explorer/master/docker-compose.yml)
|
||||
|
||||
Run MQTT Explorer in a Docker container:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
-p 3000:3000 \
|
||||
-e MQTT_EXPLORER_USERNAME=admin \
|
||||
-e MQTT_EXPLORER_PASSWORD=your_secure_password \
|
||||
-v mqtt-explorer-data:/app/data \
|
||||
ghcr.io/thomasnordquist/mqtt-explorer:latest
|
||||
```
|
||||
|
||||
**Supports multiple platforms**: amd64, arm64 (Raspberry Pi 3/4/5), arm/v7 (Raspberry Pi 2/3).
|
||||
|
||||
**Enterprise integration**: Set `MQTT_EXPLORER_SKIP_AUTH=true` to disable built-in authentication when deploying behind a secure authentication proxy (e.g., OAuth2 Proxy, SSO).
|
||||
|
||||
For complete Docker documentation including authentication options, deployment examples, and security best practices, see [DOCKER.md](DOCKER.md).
|
||||
|
||||
## Develop
|
||||
|
||||
### Desktop Application
|
||||
@@ -80,12 +101,51 @@ The `app` directory contains all the rendering logic, the `backend` directory cu
|
||||
|
||||
## Automated Tests
|
||||
|
||||
To achieve a reliable product automated tests run regularly on CI.
|
||||
MQTT Explorer uses multiple test suites to ensure reliability and quality:
|
||||
|
||||
- **Data model tests**: `yarn test:backend`
|
||||
- **App tests**: `yarn test:app`
|
||||
- **UI test suite**: `yarn test:ui` (independent, deterministic tests)
|
||||
- **Demo video**: `yarn ui-test` (UI test recording for documentation)
|
||||
### Unit Tests
|
||||
|
||||
**App tests** - Frontend component and logic tests:
|
||||
```bash
|
||||
yarn test:app
|
||||
```
|
||||
|
||||
**Backend tests** - Data model and business logic tests:
|
||||
```bash
|
||||
yarn test:backend
|
||||
```
|
||||
|
||||
**Run all unit tests**:
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
### Integration & UI Tests
|
||||
|
||||
**UI test suite** - Independent, deterministic browser tests:
|
||||
```bash
|
||||
yarn build
|
||||
yarn test:ui
|
||||
```
|
||||
|
||||
**Demo video generation** - UI test recording for documentation:
|
||||
```bash
|
||||
yarn build
|
||||
yarn test:demo-video
|
||||
```
|
||||
Note: Requires Xvfb, mosquitto broker, tmux, and ffmpeg. For full video recording setup, use `./scripts/uiTests.sh`.
|
||||
|
||||
**MCP introspection tests** - Model Context Protocol validation:
|
||||
```bash
|
||||
yarn build
|
||||
yarn test:mcp
|
||||
```
|
||||
|
||||
**Run all tests** (unit tests + demo video):
|
||||
```bash
|
||||
yarn build
|
||||
yarn test:all
|
||||
```
|
||||
|
||||
### Run UI Test Suite
|
||||
|
||||
@@ -104,18 +164,36 @@ See [docs/UI-TEST-SUITE.md](docs/UI-TEST-SUITE.md) for more details.
|
||||
|
||||
### Run Demo Video Generation
|
||||
|
||||
A [mosquitto](https://mosquitto.org/) MQTT broker is required to generate the demo video.
|
||||
The demo video is used for documentation and showcases key features. It requires additional dependencies:
|
||||
|
||||
```bash
|
||||
yarn build
|
||||
yarn ui-test
|
||||
yarn test:demo-video
|
||||
```
|
||||
|
||||
**Requirements:**
|
||||
- mosquitto MQTT broker
|
||||
- Xvfb (virtual framebuffer)
|
||||
- tmux (terminal multiplexer)
|
||||
- ffmpeg (video encoding)
|
||||
|
||||
**For full video recording with post-processing:**
|
||||
```bash
|
||||
yarn build
|
||||
./scripts/uiTests.sh
|
||||
```
|
||||
|
||||
This script handles Xvfb setup, mosquitto startup, video recording, and cleanup.
|
||||
|
||||
## Create a release
|
||||
|
||||
Create a PR to `release` branch.
|
||||
There needs to be a "feat: some new feature" or "fix: some bugfix" commit for a new release to be created
|
||||
|
||||
### macOS Notarization
|
||||
|
||||
macOS builds are automatically notarized during the release process. To set up notarization credentials, see [NOTARIZATION.md](NOTARIZATION.md).
|
||||
|
||||
## Create a beta release
|
||||
|
||||
Create a PR to `beta` branch. A "feat" or "fix" commit is necessary to create a new version.
|
||||
@@ -145,7 +223,9 @@ The readme will be generated from the docs.
|
||||
|
||||
## License
|
||||
|
||||

|
||||
[CC-BY-Nc 4.0](https://creativecommons.org/licenses/by-nC/4.0/)
|
||||

|
||||
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/)
|
||||
|
||||
The license allows for anyone to adapt, share, and redistribute the material, as long as it is non-commercial.
|
||||
**Special requirement:** When distributing, the attribution and donation page may not be altered or made less accessible without explicit approval.
|
||||
|
||||
The license allows for anyone to adapt, share, and redistribute the material, as long as they give appropriate credit and distribute any derivative works under the same license.
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Security updates are provided for the latest release of MQTT Explorer.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | ------------------ |
|
||||
| 0.4.x | :white_check_mark: |
|
||||
| < 0.4 | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
We take security vulnerabilities seriously. If you discover a security issue, please follow these steps:
|
||||
|
||||
### How to Report
|
||||
|
||||
1. **DO NOT** create a public GitHub issue for security vulnerabilities
|
||||
2. Report via one of these channels:
|
||||
- GitHub Security Advisories (preferred): https://github.com/thomasnordquist/MQTT-Explorer/security/advisories/new
|
||||
- Email the maintainer directly
|
||||
3. Include the following information:
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact
|
||||
- Any suggested fixes (optional)
|
||||
|
||||
### What to Expect
|
||||
|
||||
- **Acknowledgment**: We will acknowledge receipt of your report within 48 hours
|
||||
- **Updates**: We will provide updates on the status of your report within 7 days
|
||||
- **Fix Timeline**: We aim to release security fixes within 30 days for critical issues
|
||||
- **Credit**: With your permission, we will credit you in the security advisory and release notes
|
||||
|
||||
## Security Features
|
||||
|
||||
### Browser Mode Security
|
||||
|
||||
MQTT Explorer's browser mode includes several security features:
|
||||
|
||||
#### Authentication
|
||||
- **bcrypt Password Hashing**: All passwords are hashed with bcrypt (10 rounds)
|
||||
- **Constant-Time Comparison**: Username comparison uses crypto.timingSafeEqual() to prevent timing attacks
|
||||
- **Environment Variable Configuration**: Credentials can be set via environment variables for production
|
||||
- **Automatic Credential Generation**: Secure random credentials generated if not provided
|
||||
|
||||
#### Rate Limiting
|
||||
- **Authentication Rate Limiting**: Maximum 5 failed authentication attempts per IP per 15 minutes
|
||||
- **Per-IP Tracking**: Failed attempts tracked separately for each client IP
|
||||
- **Automatic Reset**: Rate limit counters automatically reset after 15 minutes
|
||||
|
||||
#### HTTP Security Headers (helmet.js)
|
||||
- **Content Security Policy (CSP)**: Restricts resource loading to prevent XSS attacks
|
||||
- **HTTP Strict Transport Security (HSTS)**: Enforces HTTPS in production
|
||||
- **X-Content-Type-Options**: Prevents MIME type sniffing
|
||||
- **X-Frame-Options**: Prevents clickjacking attacks
|
||||
- **X-XSS-Protection**: Enables browser XSS protection
|
||||
|
||||
#### Input Validation
|
||||
- **File Size Limits**: Maximum 16MB for file uploads
|
||||
- **Path Traversal Protection**: All file paths validated and sanitized
|
||||
- **Filename Sanitization**: Removes path separators, null bytes, and validates against traversal patterns
|
||||
- **Real Path Validation**: Ensures resolved paths stay within allowed directories
|
||||
- **Base64 Validation**: All file data properly validated before processing
|
||||
|
||||
#### CORS Configuration
|
||||
- **Configurable Origins**: CORS origins configurable via ALLOWED_ORIGINS environment variable
|
||||
- **Production Restrictions**: Wildcard CORS automatically disabled in production
|
||||
- **Credential Support**: CORS configured with credentials: true for authenticated requests
|
||||
|
||||
#### Error Handling
|
||||
- **Generic Error Messages**: Detailed errors only shown in development mode
|
||||
- **No Information Leakage**: Error messages sanitized to prevent information disclosure
|
||||
- **Secure Logging**: Sensitive information not logged in production
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
### For Server Deployment
|
||||
|
||||
1. **Always Use HTTPS in Production**
|
||||
- Use a reverse proxy (nginx, Apache) with TLS certificates
|
||||
- Never expose the Node.js server directly to the internet
|
||||
- Use Let's Encrypt for free TLS certificates
|
||||
|
||||
2. **Set Strong Credentials**
|
||||
```bash
|
||||
export MQTT_EXPLORER_USERNAME=your_secure_username
|
||||
export MQTT_EXPLORER_PASSWORD=your_strong_password_min_12_chars
|
||||
export NODE_ENV=production
|
||||
```
|
||||
|
||||
3. **Configure CORS Properly**
|
||||
```bash
|
||||
# Single origin
|
||||
export ALLOWED_ORIGINS=https://mqtt-explorer.example.com
|
||||
|
||||
# Multiple origins
|
||||
export ALLOWED_ORIGINS=https://app1.example.com,https://app2.example.com
|
||||
```
|
||||
|
||||
4. **Network Security**
|
||||
- Deploy behind a firewall or VPN
|
||||
- Use IP whitelisting when possible
|
||||
- Implement network-level rate limiting
|
||||
- Monitor access logs regularly
|
||||
|
||||
5. **Keep Dependencies Updated**
|
||||
```bash
|
||||
yarn audit
|
||||
yarn upgrade-interactive
|
||||
```
|
||||
|
||||
6. **Regular Security Audits**
|
||||
- Run security tests: `yarn test:security`
|
||||
- Review access logs for suspicious activity
|
||||
- Monitor authentication failures
|
||||
- Check for outdated dependencies
|
||||
|
||||
### For MQTT Connections
|
||||
|
||||
1. **Use TLS/SSL**: Always connect to MQTT brokers using TLS encryption
|
||||
2. **Strong Credentials**: Use unique, strong passwords for MQTT authentication
|
||||
3. **Certificate Validation**: Verify broker certificates in production
|
||||
4. **Least Privilege**: Connect with minimal required permissions
|
||||
|
||||
## Security Testing
|
||||
|
||||
The project includes comprehensive security tests:
|
||||
|
||||
```bash
|
||||
# Run all tests including security tests
|
||||
yarn test
|
||||
|
||||
# Run only security tests
|
||||
npx mocha --require source-map-support/register dist/src/spec/security-tests.spec.js
|
||||
```
|
||||
|
||||
Security tests cover:
|
||||
- Path traversal attack prevention
|
||||
- Input validation and sanitization
|
||||
- Authentication security
|
||||
- CORS configuration
|
||||
- Rate limiting
|
||||
- Error handling
|
||||
- Data sanitization
|
||||
|
||||
## Security Audit History
|
||||
|
||||
### December 2024 - Initial Security Review
|
||||
- Added helmet.js for HTTP security headers
|
||||
- Implemented rate limiting for authentication
|
||||
- Added path traversal protection with sanitization
|
||||
- Implemented constant-time comparison for credentials
|
||||
- Added input validation and size limits
|
||||
- Removed credential logging in production
|
||||
- Added configurable CORS origins
|
||||
- Created comprehensive security test suite (19 tests)
|
||||
- Enhanced documentation with security best practices
|
||||
|
||||
## Known Limitations
|
||||
|
||||
### Browser Mode
|
||||
- File system access limited to server-side directories
|
||||
- No native OS dialogs (uses browser file input)
|
||||
- Session management is stateless (no persistent sessions)
|
||||
|
||||
### Desktop Mode (Electron)
|
||||
- Inherits security model from Electron framework
|
||||
- IPC communication between renderer and main process
|
||||
- No network exposure by default
|
||||
|
||||
## Recommended Security Tools
|
||||
|
||||
- **Dependency Scanning**: Dependabot, Snyk, or npm audit
|
||||
- **SAST**: SonarQube, ESLint security plugins
|
||||
- **Container Scanning**: If using Docker deployment
|
||||
- **TLS Testing**: SSL Labs, testssl.sh
|
||||
- **Penetration Testing**: OWASP ZAP, Burp Suite
|
||||
|
||||
## References
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
- [Node.js Security Best Practices](https://nodejs.org/en/docs/guides/security/)
|
||||
- [Express Security Best Practices](https://expressjs.com/en/advanced/best-practice-security.html)
|
||||
- [helmet.js Documentation](https://helmetjs.github.io/)
|
||||
- [MQTT Security](https://mqtt.org/mqtt-specification/)
|
||||
|
||||
## Contact
|
||||
|
||||
For security-related questions or concerns:
|
||||
- GitHub Security Advisories: https://github.com/thomasnordquist/MQTT-Explorer/security/advisories
|
||||
- Project Issues (for non-sensitive topics): https://github.com/thomasnordquist/MQTT-Explorer/issues
|
||||
|
||||
Thank you for helping keep MQTT Explorer secure!
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
# React Component Testing Guide
|
||||
|
||||
This guide explains how to write tests for React components in the MQTT-Explorer project using the generic testing utilities.
|
||||
|
||||
## Overview
|
||||
|
||||
We use the following testing stack:
|
||||
- **Mocha** - Test framework
|
||||
- **Chai** - Assertion library
|
||||
- **React Testing Library** - React component testing utilities
|
||||
- **JSDOM** - DOM implementation for Node.js
|
||||
- **Custom Test Utilities** - Located in `src/utils/spec/testUtils.tsx`
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Create a Test File
|
||||
|
||||
Test files should be placed next to the component they test with the `.spec.tsx` extension:
|
||||
|
||||
```
|
||||
src/components/MyComponent/
|
||||
├── MyComponent.tsx
|
||||
└── MyComponent.spec.tsx
|
||||
```
|
||||
|
||||
### 2. Basic Test Structure
|
||||
|
||||
```typescript
|
||||
import React from 'react'
|
||||
import { expect } from 'chai'
|
||||
import { describe, it } from 'mocha'
|
||||
import MyComponent from './MyComponent'
|
||||
import { renderWithProviders } from '../../utils/spec/testUtils'
|
||||
|
||||
describe('MyComponent', () => {
|
||||
it('should render correctly', () => {
|
||||
const { container } = renderWithProviders(<MyComponent />)
|
||||
expect(container).to.exist
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Using Test Utilities
|
||||
|
||||
### `renderWithProviders`
|
||||
|
||||
This function wraps your component with necessary providers (Theme, Redux).
|
||||
|
||||
```typescript
|
||||
import { renderWithProviders } from '../../utils/spec/testUtils'
|
||||
|
||||
// Render with theme only (default)
|
||||
const { container } = renderWithProviders(<MyComponent />, { withTheme: true })
|
||||
|
||||
// Render with both theme and Redux
|
||||
const { container } = renderWithProviders(<MyComponent />, {
|
||||
withTheme: true,
|
||||
withRedux: true
|
||||
})
|
||||
|
||||
// Render with custom theme
|
||||
import { createTheme } from '@mui/material/styles'
|
||||
const darkTheme = createTheme({ palette: { mode: 'dark' } })
|
||||
const { container } = renderWithProviders(<MyComponent />, {
|
||||
theme: darkTheme
|
||||
})
|
||||
|
||||
// Render with custom Redux store
|
||||
import { configureStore } from '@reduxjs/toolkit'
|
||||
const customStore = configureStore({ /* ... */ })
|
||||
const { container } = renderWithProviders(<MyComponent />, {
|
||||
store: customStore,
|
||||
withRedux: true
|
||||
})
|
||||
```
|
||||
|
||||
### `createMockChartData`
|
||||
|
||||
Helper function to generate mock chart data:
|
||||
|
||||
```typescript
|
||||
import { createMockChartData } from '../../utils/spec/testUtils'
|
||||
|
||||
// Create 10 data points (default)
|
||||
const data = createMockChartData()
|
||||
|
||||
// Create specific number of points
|
||||
const data = createMockChartData(50)
|
||||
```
|
||||
|
||||
### Global Mocks
|
||||
|
||||
The test utilities automatically set up global mocks:
|
||||
- **ResizeObserver** - Mocked for components using `react-resize-detector`
|
||||
|
||||
## Common Testing Patterns
|
||||
|
||||
### Testing Rendering
|
||||
|
||||
```typescript
|
||||
it('should render without crashing', () => {
|
||||
const { container } = renderWithProviders(<MyComponent />)
|
||||
expect(container).to.exist
|
||||
})
|
||||
|
||||
it('should render specific element', () => {
|
||||
const { container } = renderWithProviders(<MyComponent />)
|
||||
const element = container.querySelector('.my-class')
|
||||
expect(element).to.exist
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Props
|
||||
|
||||
```typescript
|
||||
it('should accept all valid props', () => {
|
||||
const props = {
|
||||
title: 'Test',
|
||||
value: 123,
|
||||
onchange: () => {},
|
||||
}
|
||||
const { container } = renderWithProviders(<MyComponent {...props} />)
|
||||
expect(container).to.exist
|
||||
})
|
||||
```
|
||||
|
||||
### Testing User Interactions
|
||||
|
||||
```typescript
|
||||
import { userEvent } from '../../utils/spec/testUtils'
|
||||
|
||||
it('should handle click events', async () => {
|
||||
const { container } = renderWithProviders(<MyComponent />)
|
||||
const button = container.querySelector('button')
|
||||
|
||||
if (button) {
|
||||
await userEvent.click(button)
|
||||
// Assert expected behavior
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Different States
|
||||
|
||||
```typescript
|
||||
it('should render empty state', () => {
|
||||
const { container } = renderWithProviders(<MyComponent data={[]} />)
|
||||
// Assert empty state
|
||||
})
|
||||
|
||||
it('should render with data', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<MyComponent data={data} />)
|
||||
// Assert data is rendered
|
||||
})
|
||||
```
|
||||
|
||||
### Testing SVG Components
|
||||
|
||||
```typescript
|
||||
it('should render SVG elements', () => {
|
||||
const { container } = renderWithProviders(<ChartComponent />)
|
||||
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
const paths = container.querySelectorAll('path')
|
||||
expect(paths.length).to.be.greaterThan(0)
|
||||
|
||||
const circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(5)
|
||||
})
|
||||
```
|
||||
|
||||
### Testing Edge Cases
|
||||
|
||||
```typescript
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle negative values', () => {
|
||||
const data = [{ x: 1, y: -10 }, { x: 2, y: -20 }]
|
||||
const { container } = renderWithProviders(<MyComponent data={data} />)
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should handle empty arrays', () => {
|
||||
const { container } = renderWithProviders(<MyComponent data={[]} />)
|
||||
expect(container).to.exist
|
||||
})
|
||||
|
||||
it('should handle very large numbers', () => {
|
||||
const data = [{ x: 1, y: 1000000 }]
|
||||
const { container } = renderWithProviders(<MyComponent data={data} />)
|
||||
expect(container).to.exist
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
### Run all tests
|
||||
```bash
|
||||
yarn test
|
||||
```
|
||||
|
||||
### Run specific test file
|
||||
```bash
|
||||
npx mocha --require tsx --require source-map-support/register "src/components/MyComponent/MyComponent.spec.tsx"
|
||||
```
|
||||
|
||||
### Run tests in watch mode
|
||||
```bash
|
||||
npx mocha --require tsx --require source-map-support/register --watch "src/**/*.spec.{ts,tsx}"
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Test Behavior, Not Implementation**
|
||||
- Focus on what the component does, not how it does it
|
||||
- Test user-facing behavior and output
|
||||
|
||||
2. **Use Descriptive Test Names**
|
||||
```typescript
|
||||
// Good
|
||||
it('should render error message when validation fails')
|
||||
|
||||
// Bad
|
||||
it('test1')
|
||||
```
|
||||
|
||||
3. **Group Related Tests**
|
||||
```typescript
|
||||
describe('MyComponent', () => {
|
||||
describe('Rendering', () => {
|
||||
it('should render correctly')
|
||||
it('should render with props')
|
||||
})
|
||||
|
||||
describe('Interactions', () => {
|
||||
it('should handle clicks')
|
||||
it('should handle keyboard input')
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
4. **Keep Tests Independent**
|
||||
- Each test should be able to run in isolation
|
||||
- Don't rely on test execution order
|
||||
- Clean up after each test if needed
|
||||
|
||||
5. **Test Edge Cases**
|
||||
- Empty data
|
||||
- Null/undefined values
|
||||
- Very large/small numbers
|
||||
- Negative values
|
||||
- Single item arrays
|
||||
|
||||
6. **Use Chai Assertions**
|
||||
```typescript
|
||||
expect(value).to.exist
|
||||
expect(value).to.be.true
|
||||
expect(value).to.equal(expected)
|
||||
expect(array).to.have.length(5)
|
||||
expect(number).to.be.greaterThan(0)
|
||||
```
|
||||
|
||||
## Example: Complete Test Suite
|
||||
|
||||
See `src/components/Chart/Chart.spec.tsx` for a comprehensive example that demonstrates:
|
||||
- Multiple test groups (Rendering, Data Visualization, Edge Cases, etc.)
|
||||
- Testing with different props and configurations
|
||||
- Testing SVG elements
|
||||
- Testing theme integration
|
||||
- Performance testing
|
||||
- Edge case coverage
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "ResizeObserver is not defined"
|
||||
This is automatically mocked by the test utilities. Make sure you're importing from `testUtils.tsx`.
|
||||
|
||||
### "Cannot find module"
|
||||
Check your import paths. Remember to use relative paths from the test file.
|
||||
|
||||
### "Window is not defined"
|
||||
Make sure `jsdom-global/register` is imported in testUtils.tsx.
|
||||
|
||||
### Tests timing out
|
||||
Increase the timeout in your test:
|
||||
```typescript
|
||||
it('should complete async operation', function() {
|
||||
this.timeout(5000) // 5 seconds
|
||||
// test code
|
||||
})
|
||||
```
|
||||
|
||||
## Adding New Test Utilities
|
||||
|
||||
To add new helper functions, update `src/utils/spec/testUtils.tsx`:
|
||||
|
||||
```typescript
|
||||
export function myNewHelper() {
|
||||
// Helper implementation
|
||||
}
|
||||
```
|
||||
|
||||
Then use it in your tests:
|
||||
```typescript
|
||||
import { myNewHelper } from '../../utils/spec/testUtils'
|
||||
```
|
||||
+69
-56
@@ -6,33 +6,40 @@
|
||||
"scripts": {
|
||||
"build": "webpack --mode production",
|
||||
"dev": "node_modules/.bin/webpack-dev-server --mode development --progress",
|
||||
"test": "cross-env TS_NODE_PROJECT=test/tsconfig.json yarn mochatest",
|
||||
"mochatest": "mocha --require ts-node/register --require source-map-support/register --recursive src/*/**/*.spec.ts"
|
||||
"test": "mocha --require tsx --require source-map-support/register --recursive 'src/*/**/*.spec.{ts,tsx}'",
|
||||
"mochatest": "mocha --require tsx --require source-map-support/register --recursive 'src/*/**/*.spec.{ts,tsx}'"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"author": "",
|
||||
"license": "CC-BY-ND-4.0",
|
||||
"license": "CC-BY-SA-4.0",
|
||||
"dependencies": {
|
||||
"@material-ui/core": "4.12",
|
||||
"@material-ui/icons": "^4",
|
||||
"@material-ui/lab": "^4.0.0-alpha",
|
||||
"@material-ui/styles": "4.11",
|
||||
"@types/react-transition-group": "^4",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@mui/icons-material": "^7.3.6",
|
||||
"@mui/lab": "^7.0.1-beta.20",
|
||||
"@mui/material": "^7.3.6",
|
||||
"@mui/styles": "^6.4.8",
|
||||
"@react-spring/web": "^9.7.5",
|
||||
"@types/react-transition-group": "^4.4.11",
|
||||
"@visx/axis": "^3.10.1",
|
||||
"@visx/grid": "^3.5.0",
|
||||
"@visx/tooltip": "^3.3.0",
|
||||
"@visx/xychart": "^3.10.2",
|
||||
"ace-builds": "^1.4.11",
|
||||
"axios": "^0.28.0",
|
||||
"compare-versions": "^3.5.0",
|
||||
"copy-text-to-clipboard": "^2.1.0",
|
||||
"d3": "^5.9.7",
|
||||
"d3-shape": "^1.3.5",
|
||||
"diff": "^4.0.1",
|
||||
"dot-prop": "^5.0.0",
|
||||
"axios": "^1.13.2",
|
||||
"compare-versions": "^6.1.1",
|
||||
"copy-text-to-clipboard": "^3.2.0",
|
||||
"d3": "^7.9.0",
|
||||
"d3-shape": "^3.2.0",
|
||||
"diff": "^7.0.0",
|
||||
"dot-prop": "^5.3.0",
|
||||
"events": "^3.3.0",
|
||||
"get-value": "^3.0.1",
|
||||
"immutable": "^4.0.0-rc.12",
|
||||
"immutable": "^4.3.7",
|
||||
"in-viewport": "^3.6.0",
|
||||
"js-base64": "^2.5.1",
|
||||
"js-base64": "^3.7.8",
|
||||
"json-to-ast": "^2.1.0",
|
||||
"lodash.debounce": "^4.0.8",
|
||||
"lodash.throttle": "^4.1.1",
|
||||
@@ -41,55 +48,61 @@
|
||||
"os-browserify": "^0.3.0",
|
||||
"parse-duration": "^0.1.1",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.15.0",
|
||||
"react": "^16.11",
|
||||
"react-ace": "^8",
|
||||
"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",
|
||||
"react-vis": "^1.11.6",
|
||||
"redux": "^4.0.1",
|
||||
"redux-batched-actions": "0.5",
|
||||
"redux-thunk": "^2.3.0",
|
||||
"prismjs": "^1.29.0",
|
||||
"react": "^19.2.3",
|
||||
"react-ace": "^14.0.1",
|
||||
"react-dom": "^19.2.3",
|
||||
"react-redux": "^9.2.0",
|
||||
"react-resize-detector": "^11.0.1",
|
||||
"react-split-pane": "^0.1.92",
|
||||
"react-transition-group": "^4.4.5",
|
||||
"redux": "^5.0.1",
|
||||
"redux-batched-actions": "^0.5.0",
|
||||
"redux-thunk": "^3.1.0",
|
||||
"sha1": "^1.1.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"url": "^0.11.4",
|
||||
"uuid": "7"
|
||||
"uuid": "^11.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/runtime": "^7.17.2",
|
||||
"@types/d3": "^5.7.2",
|
||||
"@types/diff": "^4.0.1",
|
||||
"@types/get-value": "^3.0.1",
|
||||
"@types/node": "^12.7.8",
|
||||
"@types/prismjs": "^1.9.1",
|
||||
"@types/react": "^16.9.4",
|
||||
"@types/react-dom": "^16.0.11",
|
||||
"@types/react-redux": "^7.0.9",
|
||||
"@types/react-resize-detector": "^4.0.1",
|
||||
"@babel/runtime": "^7.28.4",
|
||||
"@reduxjs/toolkit": "2.5.0",
|
||||
"@testing-library/dom": "10.4.0",
|
||||
"@testing-library/react": "16.1.0",
|
||||
"@testing-library/user-event": "14.5.2",
|
||||
"@types/d3": "^7.4.3",
|
||||
"@types/diff": "^7.0.0",
|
||||
"@types/get-value": "^3.0.5",
|
||||
"@types/lodash.debounce": "^4.0.9",
|
||||
"@types/node": "^25.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react-redux": "^7.1.34",
|
||||
"@types/react-resize-detector": "^4.0.3",
|
||||
"@types/sha1": "^1.1.1",
|
||||
"@types/socket.io-client": "^3.0.0",
|
||||
"@types/uuid": "^7.0.2",
|
||||
"@types/vis": "^4.21.9",
|
||||
"chai": "^4.2.0",
|
||||
"cross-env": "^7.0.2",
|
||||
"css-loader": "^3.0.0",
|
||||
"@types/uuid": "^11.0.0",
|
||||
"@types/vis": "^4.21.24",
|
||||
"chai": "^4.5.0",
|
||||
"cross-env": "^7.0.3",
|
||||
"css-loader": "^7.1.2",
|
||||
"file-loader": "^6.2.0",
|
||||
"html-webpack-plugin": "^5.5.0",
|
||||
"html-webpack-plugin": "^5.6.3",
|
||||
"jsdom": "25.0.1",
|
||||
"jsdom-global": "3.0.2",
|
||||
"lodash": "^4.17.21",
|
||||
"mocha": "^10.4.0",
|
||||
"moment": "^2.29.1",
|
||||
"node-loader": "^0.6.0",
|
||||
"source-map-loader": "^0.2.4",
|
||||
"style-loader": "^1",
|
||||
"mocha": "^10.8.2",
|
||||
"moment": "^2.30.1",
|
||||
"node-loader": "^2.0.0",
|
||||
"source-map-loader": "^5.0.0",
|
||||
"style-loader": "^4.0.0",
|
||||
"ts-loader": "^9.5.1",
|
||||
"typescript": "^4.5.5",
|
||||
"webpack": "^5.91.0",
|
||||
"webpack-bundle-analyzer": "^4.5.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^5.0.4"
|
||||
"typescript": "^5.9.3",
|
||||
"webpack": "^5.98.0",
|
||||
"webpack-bundle-analyzer": "^4.10.2",
|
||||
"webpack-cli": "^6.0.1",
|
||||
"webpack-dev-server": "^5.2.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"electron": "^39"
|
||||
|
||||
@@ -15,7 +15,7 @@ export const setTopic = (topic?: string): Action => {
|
||||
}
|
||||
|
||||
export const openFile =
|
||||
(encoding: 'utf8' = 'utf8') =>
|
||||
(encoding: BufferEncoding = 'utf8') =>
|
||||
async (dispatch: Dispatch<any>, getState: () => AppState) => {
|
||||
try {
|
||||
const file = await getFileContent(encoding)
|
||||
@@ -31,7 +31,7 @@ type FileParameters = {
|
||||
name: string
|
||||
data: string
|
||||
}
|
||||
async function getFileContent(encoding: string): Promise<FileParameters | undefined> {
|
||||
async function getFileContent(encoding: BufferEncoding): Promise<FileParameters | undefined> {
|
||||
const rejectReasons = {
|
||||
noFileSelected: 'No file selected',
|
||||
errorReadingFile: 'Error reading file',
|
||||
|
||||
@@ -7,7 +7,7 @@ import { batchActions } from 'redux-batched-actions'
|
||||
import { globalActions } from './'
|
||||
import { setTopic } from './Publish'
|
||||
import { TopicViewModel } from '../model/TopicViewModel'
|
||||
const debounce = require('lodash.debounce')
|
||||
import debounce from 'lodash.debounce'
|
||||
export { clearTopic } from './clearTopic'
|
||||
|
||||
export { moveSelectionUpOrDownwards, moveInward, moveOutward } from './visibleTreeTraversal'
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// Browser-specific EventBus implementation using Socket.io
|
||||
// This file contains the socket.io-client dependency which belongs in the app layer
|
||||
import io, { Socket } from 'socket.io-client'
|
||||
import { SocketIOClientEventBus } from '../../events/EventSystem/SocketIOClientEventBus'
|
||||
import { Rpc } from '../../events/EventSystem/Rpc'
|
||||
|
||||
// Get auth from sessionStorage or use empty (will show login dialog)
|
||||
let username = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('mqtt-explorer-username') || '' : ''
|
||||
let password = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem('mqtt-explorer-password') || '' : ''
|
||||
|
||||
// Connect to the server (same origin in browser mode)
|
||||
const socket: Socket = io({
|
||||
auth: {
|
||||
username,
|
||||
password,
|
||||
},
|
||||
reconnection: true,
|
||||
reconnectionDelay: 1000,
|
||||
reconnectionDelayMax: 5000,
|
||||
reconnectionAttempts: Infinity,
|
||||
transports: ['websocket', 'polling'],
|
||||
autoConnect: false, // Don't auto-connect, we'll connect manually after checking credentials
|
||||
})
|
||||
|
||||
// Handle connection errors
|
||||
socket.on('connect_error', (error) => {
|
||||
console.error('Socket connection error:', error.message)
|
||||
|
||||
// Check if it's an authentication error
|
||||
if (error.message.includes('Invalid credentials') ||
|
||||
error.message.includes('Authentication required') ||
|
||||
error.message.includes('Too many')) {
|
||||
// Clear invalid credentials from sessionStorage
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.removeItem('mqtt-explorer-username')
|
||||
sessionStorage.removeItem('mqtt-explorer-password')
|
||||
}
|
||||
|
||||
// Dispatch custom event that BrowserAuthWrapper can listen to
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('mqtt-auth-error', {
|
||||
detail: { message: error.message }
|
||||
}))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
socket.on('disconnect', (reason) => {
|
||||
console.log('Socket disconnected:', reason)
|
||||
})
|
||||
|
||||
socket.on('connect', () => {
|
||||
console.log('Socket connected successfully')
|
||||
|
||||
// Dispatch custom event that BrowserAuthWrapper can listen to
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('mqtt-auth-success', {
|
||||
detail: { message: 'Authentication successful' }
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
// Listen for auth-status from server (sent on connection)
|
||||
socket.on('auth-status', (data: { authDisabled: boolean }) => {
|
||||
console.log('Auth status received from server:', data)
|
||||
|
||||
// Dispatch custom event with auth status
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent('mqtt-auth-status', {
|
||||
detail: { authDisabled: data.authDisabled }
|
||||
}))
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Update socket authentication credentials and attempt to reconnect
|
||||
* @param newUsername New username
|
||||
* @param newPassword New password
|
||||
*/
|
||||
export function updateSocketAuth(newUsername: string, newPassword: string) {
|
||||
username = newUsername
|
||||
password = newPassword
|
||||
|
||||
// Update socket auth
|
||||
socket.auth = {
|
||||
username: newUsername,
|
||||
password: newPassword,
|
||||
}
|
||||
|
||||
// Store in sessionStorage
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.setItem('mqtt-explorer-username', newUsername)
|
||||
sessionStorage.setItem('mqtt-explorer-password', newPassword)
|
||||
}
|
||||
|
||||
// Disconnect if connected, then reconnect with new credentials
|
||||
if (socket.connected) {
|
||||
socket.disconnect()
|
||||
}
|
||||
socket.connect()
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect the socket (used on initial page load)
|
||||
*/
|
||||
export function connectSocket() {
|
||||
if (!socket.connected) {
|
||||
socket.connect()
|
||||
}
|
||||
}
|
||||
|
||||
export const rendererEvents = new SocketIOClientEventBus(socket)
|
||||
export const rendererRpc = new Rpc(rendererEvents)
|
||||
|
||||
// Export socket instance for error monitoring
|
||||
export const browserSocket = socket
|
||||
|
||||
// In browser mode, the backend is on the server
|
||||
// For compatibility, export same instances (renderer communicates with server backend via socket)
|
||||
export const backendEvents = rendererEvents
|
||||
export const backendRpc = rendererRpc
|
||||
|
||||
// Re-export all events from the events module so imports work correctly
|
||||
export * from '../../events/Events'
|
||||
export * from '../../events/EventsV2'
|
||||
export * from '../../events/EventSystem/EventDispatcher'
|
||||
export * from '../../events/EventSystem/EventBusInterface'
|
||||
@@ -1,6 +1,6 @@
|
||||
import ConfirmationDialog from './ConfirmationDialog'
|
||||
import ConnectionSetup from './ConnectionSetup/ConnectionSetup'
|
||||
import CssBaseline from '@material-ui/core/CssBaseline'
|
||||
import CssBaseline from '@mui/material/CssBaseline'
|
||||
import ErrorBoundary from './ErrorBoundary'
|
||||
import Notification from './Layout/Notification'
|
||||
import React from 'react'
|
||||
@@ -11,7 +11,8 @@ import { bindActionCreators } from 'redux'
|
||||
import { ConfirmationRequest } from '../reducers/Global'
|
||||
import { connect } from 'react-redux'
|
||||
import { globalActions, settingsActions } from '../actions'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
;(window as any).global = window
|
||||
|
||||
const Settings = React.lazy(() => import('./SettingsDrawer/Settings'))
|
||||
|
||||
@@ -1,53 +1,133 @@
|
||||
import * as React from 'react'
|
||||
import { LoginDialog } from './LoginDialog'
|
||||
import { updateSocketAuth, connectSocket } from '../browserEventBus'
|
||||
import { isBrowserMode } from '../utils/browserMode'
|
||||
import { AuthContext } from '../contexts/AuthContext'
|
||||
|
||||
interface BrowserAuthWrapperProps {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const isBrowserMode =
|
||||
typeof window !== 'undefined' && (typeof process === 'undefined' || process.env?.BROWSER_MODE === 'true')
|
||||
|
||||
export function BrowserAuthWrapper(props: BrowserAuthWrapperProps) {
|
||||
const [isAuthenticated, setIsAuthenticated] = React.useState(false)
|
||||
const [loginError, setLoginError] = React.useState<string | undefined>()
|
||||
const [showLogin, setShowLogin] = React.useState(false)
|
||||
const [waitTimeSeconds, setWaitTimeSeconds] = React.useState<number | undefined>()
|
||||
const [isConnecting, setIsConnecting] = React.useState(false)
|
||||
const [authCheckComplete, setAuthCheckComplete] = React.useState(false)
|
||||
const [authDisabled, setAuthDisabled] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!isBrowserMode) {
|
||||
// Not in browser mode, skip authentication
|
||||
setIsAuthenticated(true)
|
||||
setAuthCheckComplete(true)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if already authenticated
|
||||
const username = sessionStorage.getItem('mqtt-explorer-username')
|
||||
const password = sessionStorage.getItem('mqtt-explorer-password')
|
||||
// Listen for auth status from socket connection
|
||||
const handleAuthStatus = (event: CustomEvent) => {
|
||||
const { authDisabled } = event.detail
|
||||
setAuthDisabled(authDisabled)
|
||||
|
||||
if (authDisabled) {
|
||||
// Authentication is disabled on server
|
||||
console.log('Authentication is disabled on server, skipping login')
|
||||
setIsAuthenticated(true)
|
||||
setShowLogin(false)
|
||||
setAuthCheckComplete(true)
|
||||
} else {
|
||||
// Authentication is enabled, check if we have credentials
|
||||
setAuthCheckComplete(true)
|
||||
|
||||
const username = sessionStorage.getItem('mqtt-explorer-username')
|
||||
const password = sessionStorage.getItem('mqtt-explorer-password')
|
||||
|
||||
if (username && password) {
|
||||
// Try to use stored credentials
|
||||
setIsAuthenticated(true)
|
||||
} else {
|
||||
// Show login dialog
|
||||
setShowLogin(true)
|
||||
if (username && password) {
|
||||
// Credentials exist, connection will authenticate automatically
|
||||
setIsConnecting(true)
|
||||
} else {
|
||||
// No credentials, show login dialog
|
||||
setShowLogin(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleLogin = async (username: string, password: string) => {
|
||||
try {
|
||||
// Store credentials in session storage
|
||||
sessionStorage.setItem('mqtt-explorer-username', username)
|
||||
sessionStorage.setItem('mqtt-explorer-password', password)
|
||||
|
||||
// The socket will use these credentials on next connection
|
||||
// Listen for successful authentication from socket
|
||||
const handleAuthSuccess = (event: CustomEvent) => {
|
||||
console.log('Authentication successful')
|
||||
setIsAuthenticated(true)
|
||||
setShowLogin(false)
|
||||
setLoginError(undefined)
|
||||
setWaitTimeSeconds(undefined)
|
||||
setIsConnecting(false)
|
||||
}
|
||||
|
||||
// Reload to reinitialize socket with new auth
|
||||
window.location.reload()
|
||||
// Listen for authentication errors from socket
|
||||
const handleAuthError = (event: CustomEvent) => {
|
||||
const errorMessage = event.detail?.message || 'Authentication failed'
|
||||
console.error('Authentication error:', errorMessage)
|
||||
|
||||
// Mark auth check as complete - we now know auth is required
|
||||
setAuthCheckComplete(true)
|
||||
|
||||
// Clear authentication state
|
||||
setIsAuthenticated(false)
|
||||
setShowLogin(true)
|
||||
setIsConnecting(false)
|
||||
|
||||
// Extract wait time from error message (e.g., "Please wait 30 seconds")
|
||||
const waitTimeMatch = errorMessage.match(/(\d+)\s+seconds?/)
|
||||
if (waitTimeMatch) {
|
||||
const seconds = parseInt(waitTimeMatch[1], 10)
|
||||
// Add a few seconds margin to the countdown
|
||||
setWaitTimeSeconds(seconds + 3)
|
||||
} else {
|
||||
setWaitTimeSeconds(undefined)
|
||||
}
|
||||
|
||||
// Set user-friendly error message based on error type
|
||||
// Error messages from server already include wait times
|
||||
if (errorMessage.includes('Too many failed authentication attempts')) {
|
||||
setLoginError(errorMessage)
|
||||
} else if (errorMessage.includes('Invalid credentials')) {
|
||||
setLoginError(errorMessage)
|
||||
} else if (errorMessage.includes('Authentication required')) {
|
||||
setLoginError('Please enter your username and password.')
|
||||
setWaitTimeSeconds(undefined)
|
||||
} else {
|
||||
setLoginError('Authentication failed. Please try again.')
|
||||
setWaitTimeSeconds(undefined)
|
||||
}
|
||||
}
|
||||
|
||||
// Connect socket to trigger auth-status event
|
||||
connectSocket()
|
||||
|
||||
window.addEventListener('mqtt-auth-status', handleAuthStatus as EventListener)
|
||||
window.addEventListener('mqtt-auth-success', handleAuthSuccess as EventListener)
|
||||
window.addEventListener('mqtt-auth-error', handleAuthError as EventListener)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('mqtt-auth-status', handleAuthStatus as EventListener)
|
||||
window.removeEventListener('mqtt-auth-success', handleAuthSuccess as EventListener)
|
||||
window.removeEventListener('mqtt-auth-error', handleAuthError as EventListener)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const handleLogin = (username: string, password: string) => {
|
||||
try {
|
||||
// Clear any previous error
|
||||
setLoginError(undefined)
|
||||
setWaitTimeSeconds(undefined)
|
||||
setIsConnecting(true)
|
||||
|
||||
// Update socket auth and reconnect (no page reload needed)
|
||||
updateSocketAuth(username, password)
|
||||
} catch (error) {
|
||||
setLoginError('Login failed. Please check your credentials.')
|
||||
console.error('Failed to update socket auth:', error)
|
||||
setLoginError('Failed to connect. Please try again.')
|
||||
setIsConnecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,9 +136,14 @@ export function BrowserAuthWrapper(props: BrowserAuthWrapperProps) {
|
||||
return <>{props.children}</>
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <LoginDialog open={showLogin} onLogin={handleLogin} error={loginError} />
|
||||
// Show nothing while checking auth status to avoid flash
|
||||
if (!authCheckComplete) {
|
||||
return null
|
||||
}
|
||||
|
||||
return <>{props.children}</>
|
||||
if (!isAuthenticated) {
|
||||
return <LoginDialog open={showLogin} onLogin={handleLogin} error={loginError} waitTimeSeconds={waitTimeSeconds} />
|
||||
}
|
||||
|
||||
return <AuthContext.Provider value={{ authDisabled }}>{props.children}</AuthContext.Provider>
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { expect } from 'chai'
|
||||
import { renderWithProviders } from '../../utils/spec/testUtils'
|
||||
import Chart from './Chart'
|
||||
|
||||
describe('Chart X-Axis Domain Investigation', () => {
|
||||
it('should spread points across X-axis with sequential timestamps', () => {
|
||||
// Create 5 data points, 1 second (1000ms) apart
|
||||
const now = Date.now()
|
||||
const data = [
|
||||
{ x: now - 4000, y: 20 },
|
||||
{ x: now - 3000, y: 21 },
|
||||
{ x: now - 2000, y: 22 },
|
||||
{ x: now - 1000, y: 23 },
|
||||
{ x: now, y: 24 }
|
||||
]
|
||||
|
||||
const { container } = renderWithProviders(<Chart data={data} />)
|
||||
|
||||
// Find all circle elements (data points)
|
||||
const circles = container.querySelectorAll('svg circle')
|
||||
expect(circles).to.have.length(5)
|
||||
|
||||
// Extract cx (X-position) values
|
||||
const cxValues: number[] = []
|
||||
circles.forEach(circle => {
|
||||
const cx = circle.getAttribute('cx')
|
||||
if (cx) {
|
||||
cxValues.push(parseFloat(cx))
|
||||
}
|
||||
})
|
||||
|
||||
// Log for debugging
|
||||
console.log('\n========== X-AXIS DOMAIN INVESTIGATION ==========')
|
||||
console.log('Data X values (timestamps):')
|
||||
data.forEach((d, i) => console.log(` Point ${i}: ${d.x} (${new Date(d.x).toISOString()})`))
|
||||
console.log(`\nData X range: ${data[data.length - 1].x - data[0].x}ms (${(data[data.length - 1].x - data[0].x) / 1000}s)`)
|
||||
|
||||
console.log('\nRendered circle CX positions:')
|
||||
cxValues.forEach((cx, i) => console.log(` Circle ${i}: cx=${cx.toFixed(2)}px`))
|
||||
|
||||
const minCx = Math.min(...cxValues)
|
||||
const maxCx = Math.max(...cxValues)
|
||||
const cxRange = maxCx - minCx
|
||||
|
||||
console.log(`\nCX position range: ${cxRange.toFixed(2)}px (from ${minCx.toFixed(2)} to ${maxCx.toFixed(2)})`)
|
||||
console.log(`Points per pixel: ${(cxValues.length / cxRange).toFixed(4)}`)
|
||||
|
||||
// Calculate spacing between consecutive points
|
||||
const spacings: number[] = []
|
||||
for (let i = 1; i < cxValues.length; i++) {
|
||||
spacings.push(cxValues[i] - cxValues[i - 1])
|
||||
}
|
||||
console.log('\nSpacing between consecutive points:')
|
||||
spacings.forEach((s, i) => console.log(` ${i} to ${i+1}: ${s.toFixed(2)}px`))
|
||||
|
||||
const avgSpacing = spacings.reduce((a, b) => a + b, 0) / spacings.length
|
||||
console.log(`Average spacing: ${avgSpacing.toFixed(2)}px`)
|
||||
console.log('=================================================\n')
|
||||
|
||||
// Assertions:
|
||||
// 1. Points should be spread out (CX range should be significant, not bunched)
|
||||
expect(cxRange).to.be.greaterThan(50, 'Points should be spread across at least 50px')
|
||||
|
||||
// 2. Points should be in ascending order (left to right)
|
||||
for (let i = 1; i < cxValues.length; i++) {
|
||||
expect(cxValues[i]).to.be.greaterThan(cxValues[i - 1],
|
||||
`Point ${i} (cx=${cxValues[i]}) should be to the right of point ${i-1} (cx=${cxValues[i-1]})`)
|
||||
}
|
||||
|
||||
// 3. Spacing should be relatively uniform (since data points are equally spaced in time)
|
||||
const spacingVariance = spacings.map(s => Math.abs(s - avgSpacing))
|
||||
const maxVariance = Math.max(...spacingVariance)
|
||||
expect(maxVariance).to.be.lessThan(avgSpacing * 0.5,
|
||||
'Spacing between points should be relatively uniform')
|
||||
})
|
||||
|
||||
it('should handle points bunched at far right correctly', () => {
|
||||
// Simulate the "bunched up" scenario with very large timestamps
|
||||
const largeTimestamp = 1703347200000 // Dec 23, 2023
|
||||
const data = [
|
||||
{ x: largeTimestamp, y: 20 },
|
||||
{ x: largeTimestamp + 1000, y: 21 },
|
||||
{ x: largeTimestamp + 2000, y: 22 },
|
||||
{ x: largeTimestamp + 3000, y: 23 },
|
||||
{ x: largeTimestamp + 4000, y: 24 }
|
||||
]
|
||||
|
||||
const { container } = renderWithProviders(<Chart data={data} />)
|
||||
|
||||
const circles = container.querySelectorAll('svg circle')
|
||||
const cxValues: number[] = []
|
||||
circles.forEach(circle => {
|
||||
const cx = circle.getAttribute('cx')
|
||||
if (cx) {
|
||||
cxValues.push(parseFloat(cx))
|
||||
}
|
||||
})
|
||||
|
||||
console.log('\n========== LARGE TIMESTAMP TEST ==========')
|
||||
console.log('Data X values:', data.map(d => d.x))
|
||||
console.log('Rendered CX values:', cxValues.map(v => v.toFixed(2)))
|
||||
|
||||
const minCx = Math.min(...cxValues)
|
||||
const maxCx = Math.max(...cxValues)
|
||||
console.log(`CX range: ${(maxCx - minCx).toFixed(2)}px`)
|
||||
console.log('==========================================\n')
|
||||
|
||||
// Points should still be spread out even with large timestamps
|
||||
expect(maxCx - minCx).to.be.greaterThan(50,
|
||||
'Points with large timestamps should still be spread across the chart')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,514 @@
|
||||
/**
|
||||
* Chart Component Tests
|
||||
*
|
||||
* These tests verify the Chart component functionality including:
|
||||
* - Rendering with various data configurations
|
||||
* - Theme integration
|
||||
* - Interactive features (tooltips, hover states)
|
||||
* - Different curve interpolation types
|
||||
* - Custom domains and ranges
|
||||
* - Responsive behavior
|
||||
*/
|
||||
|
||||
import React from 'react'
|
||||
import { expect } from 'chai'
|
||||
import { describe, it } from 'mocha'
|
||||
import Chart, { Props as ChartProps } from './Chart'
|
||||
import { renderWithProviders, createMockChartData, screen } from '../../utils/spec/testUtils'
|
||||
import { PlotCurveTypes } from '../../reducers/Charts'
|
||||
|
||||
describe('Chart Component', () => {
|
||||
describe('Basic Rendering', () => {
|
||||
it('should render without crashing with valid data', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container).to.exist
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should render NoData component when data is empty', () => {
|
||||
const { container } = renderWithProviders(<Chart data={[]} />, { withTheme: true })
|
||||
|
||||
expect(container).to.exist
|
||||
// NoData component should be rendered
|
||||
const noDataElement = container.querySelector('div')
|
||||
expect(noDataElement).to.exist
|
||||
})
|
||||
|
||||
it('should render chart with correct height', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
const chartContainer = container.querySelector('[style*="height"]') as HTMLElement
|
||||
expect(chartContainer).to.exist
|
||||
expect(chartContainer.style.height).to.equal('150px')
|
||||
})
|
||||
|
||||
it('should render SVG chart elements', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Check for SVG element
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
// Check for chart elements (paths for line series)
|
||||
const paths = container.querySelectorAll('path')
|
||||
expect(paths.length).to.be.greaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Data Visualization', () => {
|
||||
it('should render data points as glyphs', () => {
|
||||
const data = createMockChartData(3)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Check for circles (glyphs representing data points)
|
||||
const circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.be.greaterThan(0)
|
||||
})
|
||||
|
||||
it('should render exact number of data points matching data length', () => {
|
||||
const dataLength = 5
|
||||
const data = createMockChartData(dataLength)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Each data point should render as a circle
|
||||
const circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(dataLength, `Expected ${dataLength} circles for ${dataLength} data points`)
|
||||
|
||||
// Verify each circle has proper attributes
|
||||
circles.forEach((circle, index) => {
|
||||
expect(circle.getAttribute('cx')).to.exist
|
||||
expect(circle.getAttribute('cy')).to.exist
|
||||
expect(circle.getAttribute('r')).to.equal('3')
|
||||
expect(circle.getAttribute('fill')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
it('should position data points with valid coordinates', () => {
|
||||
const data = createMockChartData(3)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
const circles = container.querySelectorAll('circle')
|
||||
circles.forEach((circle) => {
|
||||
const cx = parseFloat(circle.getAttribute('cx') || '0')
|
||||
const cy = parseFloat(circle.getAttribute('cy') || '0')
|
||||
|
||||
// Coordinates should be valid numbers
|
||||
expect(cx).to.be.a('number')
|
||||
expect(cy).to.be.a('number')
|
||||
expect(isNaN(cx)).to.be.false
|
||||
expect(isNaN(cy)).to.be.false
|
||||
|
||||
// Coordinates should be within chart bounds (positive values)
|
||||
expect(cx).to.be.greaterThan(0)
|
||||
expect(cy).to.be.greaterThan(0)
|
||||
})
|
||||
})
|
||||
|
||||
it('should render line connecting data points', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Line series should create a path element
|
||||
const paths = container.querySelectorAll('path')
|
||||
expect(paths.length).to.be.greaterThan(0)
|
||||
})
|
||||
|
||||
it('should handle single data point', () => {
|
||||
const data = [{ x: Date.now(), y: 50 }]
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
const circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(1, 'Single data point should render as one circle')
|
||||
})
|
||||
|
||||
it('should handle large datasets', () => {
|
||||
const data = createMockChartData(100)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
const circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(100, '100 data points should render as 100 circles')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Curve Interpolation', () => {
|
||||
const curveTypes: PlotCurveTypes[] = ['curve', 'linear', 'cubic_basis_spline', 'step_after', 'step_before']
|
||||
|
||||
curveTypes.forEach((interpolation) => {
|
||||
it(`should render with ${interpolation} interpolation`, () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} interpolation={interpolation} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
const paths = container.querySelectorAll('path')
|
||||
expect(paths.length).to.be.greaterThan(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('Custom Styling', () => {
|
||||
it('should apply custom color', () => {
|
||||
const data = createMockChartData(5)
|
||||
const customColor = '#ff0000'
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} color={customColor} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
// Check if custom color is applied to line or glyphs
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
})
|
||||
|
||||
it('should use theme colors when no custom color provided', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Custom Domains and Ranges', () => {
|
||||
it('should render with custom Y range', () => {
|
||||
const data = createMockChartData(5)
|
||||
const range: [number, number] = [0, 100]
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} range={range} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should render with custom time range', () => {
|
||||
const data = createMockChartData(5)
|
||||
const timeRangeStart = 60000 // 1 minute
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} timeRangeStart={timeRangeStart} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should render with partial Y range (only min)', () => {
|
||||
const data = createMockChartData(5)
|
||||
const range: [number?, number?] = [0, undefined]
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} range={range} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should render with partial Y range (only max)', () => {
|
||||
const data = createMockChartData(5)
|
||||
const range: [number?, number?] = [undefined, 100]
|
||||
const { container } = renderWithProviders(
|
||||
<Chart data={data} range={range} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Chart Components', () => {
|
||||
it('should render Y-axis', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Y-axis should be present (look for axis group or tick marks)
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
// Axis typically contains text elements for labels
|
||||
const texts = container.querySelectorAll('text')
|
||||
expect(texts.length).to.be.greaterThan(0)
|
||||
})
|
||||
|
||||
it('should render X-axis with time labels', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// X-axis should be present with text labels
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
// X-axis has text labels for timestamps
|
||||
const texts = container.querySelectorAll('text')
|
||||
expect(texts.length).to.be.greaterThan(0, 'X-axis and Y-axis should have text labels')
|
||||
|
||||
// At least one text element should contain time format (e.g., contains ":")
|
||||
let hasTimeFormat = false
|
||||
texts.forEach((text) => {
|
||||
if (text.textContent && text.textContent.includes(':')) {
|
||||
hasTimeFormat = true
|
||||
}
|
||||
})
|
||||
expect(hasTimeFormat).to.be.true
|
||||
})
|
||||
|
||||
it('should render both X and Y axes', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
// Both axes should render tick marks (lines)
|
||||
const lines = container.querySelectorAll('line')
|
||||
expect(lines.length).to.be.greaterThan(0, 'Axes should render tick marks')
|
||||
|
||||
// Both axes should have labels (text)
|
||||
const texts = container.querySelectorAll('text')
|
||||
expect(texts.length).to.be.greaterThan(2, 'Both axes should have multiple labels')
|
||||
})
|
||||
|
||||
it('should render grid lines', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Grid lines are rendered as line elements
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
})
|
||||
|
||||
it('should have proper chart margins', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
const svg = container.querySelector('svg')
|
||||
expect(svg).to.exist
|
||||
|
||||
// SVG should have proper dimensions
|
||||
expect(svg?.getAttribute('width')).to.exist
|
||||
expect(svg?.getAttribute('height')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle negative values', () => {
|
||||
const data = [
|
||||
{ x: Date.now() - 2000, y: -50 },
|
||||
{ x: Date.now() - 1000, y: -25 },
|
||||
{ x: Date.now(), y: -75 },
|
||||
]
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should handle zero values', () => {
|
||||
const data = [
|
||||
{ x: Date.now() - 2000, y: 0 },
|
||||
{ x: Date.now() - 1000, y: 0 },
|
||||
{ x: Date.now(), y: 0 },
|
||||
]
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should handle very large numbers', () => {
|
||||
const data = [
|
||||
{ x: Date.now() - 2000, y: 1000000 },
|
||||
{ x: Date.now() - 1000, y: 2000000 },
|
||||
{ x: Date.now(), y: 3000000 },
|
||||
]
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
// Y-axis should abbreviate large numbers
|
||||
const texts = container.querySelectorAll('text')
|
||||
expect(texts.length).to.be.greaterThan(0)
|
||||
})
|
||||
|
||||
it('should handle identical values', () => {
|
||||
const data = [
|
||||
{ x: Date.now() - 2000, y: 50 },
|
||||
{ x: Date.now() - 1000, y: 50 },
|
||||
{ x: Date.now(), y: 50 },
|
||||
]
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Component Props', () => {
|
||||
it('should accept all valid props without errors', () => {
|
||||
const data = createMockChartData(5)
|
||||
const props: ChartProps = {
|
||||
data,
|
||||
interpolation: 'curve',
|
||||
range: [0, 100],
|
||||
timeRangeStart: 60000,
|
||||
color: '#00ff00',
|
||||
}
|
||||
|
||||
const { container } = renderWithProviders(<Chart {...props} />, { withTheme: true })
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
it('should work with minimal props', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Theme Integration', () => {
|
||||
it('should render in light theme', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { container } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
|
||||
// Note: Testing dark theme would require a custom theme provider
|
||||
// This demonstrates how the test structure supports theme variations
|
||||
})
|
||||
|
||||
describe('Performance', () => {
|
||||
it('should memoize component with same props', () => {
|
||||
const data = createMockChartData(5)
|
||||
const { rerender } = renderWithProviders(<Chart data={data} />, { withTheme: true })
|
||||
|
||||
// Component should not re-render with same props due to React.memo
|
||||
expect(() => {
|
||||
rerender(<Chart data={data} />)
|
||||
}).to.not.throw()
|
||||
})
|
||||
|
||||
it('should handle rapid data updates', () => {
|
||||
const { rerender, container } = renderWithProviders(
|
||||
<Chart data={createMockChartData(5)} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
// Simulate rapid updates
|
||||
for (let i = 0; i < 10; i++) {
|
||||
rerender(<Chart data={createMockChartData(5)} />)
|
||||
}
|
||||
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
})
|
||||
})
|
||||
|
||||
describe('Interactive Data Updates', () => {
|
||||
it('should dynamically update when data points are added', () => {
|
||||
// Start with 3 data points
|
||||
const initialData = createMockChartData(3)
|
||||
const { rerender, container } = renderWithProviders(
|
||||
<Chart data={initialData} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
// Verify initial state: should have 3 data points
|
||||
const initialCircles = container.querySelectorAll('circle')
|
||||
expect(initialCircles.length).to.equal(3, 'Should initially render 3 data points')
|
||||
|
||||
// Verify each initial circle has valid attributes
|
||||
initialCircles.forEach((circle, index) => {
|
||||
const cx = circle.getAttribute('cx')
|
||||
const cy = circle.getAttribute('cy')
|
||||
const r = circle.getAttribute('r')
|
||||
|
||||
expect(cx).to.exist
|
||||
expect(cy).to.exist
|
||||
expect(r).to.equal('3')
|
||||
expect(parseFloat(cx!)).to.be.a('number').and.not.NaN
|
||||
expect(parseFloat(cy!)).to.be.a('number').and.not.NaN
|
||||
})
|
||||
|
||||
// Update state: add 2 more data points (total 5)
|
||||
const updatedData = createMockChartData(5)
|
||||
rerender(<Chart data={updatedData} />)
|
||||
|
||||
// Verify updated state: should now have 5 data points
|
||||
const updatedCircles = container.querySelectorAll('circle')
|
||||
expect(updatedCircles.length).to.equal(5, 'Should render 5 data points after update')
|
||||
|
||||
// Verify each updated circle has valid attributes
|
||||
updatedCircles.forEach((circle, index) => {
|
||||
const cx = circle.getAttribute('cx')
|
||||
const cy = circle.getAttribute('cy')
|
||||
const r = circle.getAttribute('r')
|
||||
const fill = circle.getAttribute('fill')
|
||||
|
||||
expect(cx).to.exist
|
||||
expect(cy).to.exist
|
||||
expect(r).to.equal('3')
|
||||
expect(fill).to.exist
|
||||
expect(parseFloat(cx!)).to.be.a('number').and.not.NaN
|
||||
expect(parseFloat(cy!)).to.be.a('number').and.not.NaN
|
||||
expect(parseFloat(cy!)).to.be.greaterThan(0, 'Y coordinate should be positive')
|
||||
})
|
||||
|
||||
// Verify the line path is updated to connect all 5 points
|
||||
const linePath = container.querySelector('path[stroke]')
|
||||
expect(linePath).to.exist
|
||||
expect(linePath!.getAttribute('d')).to.exist
|
||||
|
||||
// The path should start with MoveTo (M) command and contain curve/line commands
|
||||
const pathData = linePath!.getAttribute('d')
|
||||
expect(pathData).to.include('M') // MoveTo command for first point
|
||||
// Path may contain 'L' (line) or 'C' (curve) commands depending on interpolation
|
||||
expect(pathData!.length).to.be.greaterThan(10, 'Path should have substantial data for 5 points')
|
||||
})
|
||||
|
||||
it('should handle data point removal', () => {
|
||||
// Start with 5 data points
|
||||
const initialData = createMockChartData(5)
|
||||
const { rerender, container } = renderWithProviders(
|
||||
<Chart data={initialData} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
// Verify initial state
|
||||
let circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(5, 'Should initially render 5 data points')
|
||||
|
||||
// Remove 2 data points (now 3)
|
||||
const reducedData = createMockChartData(3)
|
||||
rerender(<Chart data={reducedData} />)
|
||||
|
||||
// Verify reduced state
|
||||
circles = container.querySelectorAll('circle')
|
||||
expect(circles.length).to.equal(3, 'Should render 3 data points after removal')
|
||||
})
|
||||
|
||||
it('should maintain chart structure during data updates', () => {
|
||||
const initialData = createMockChartData(3)
|
||||
const { rerender, container } = renderWithProviders(
|
||||
<Chart data={initialData} />,
|
||||
{ withTheme: true }
|
||||
)
|
||||
|
||||
// Verify chart structure exists initially
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
expect(container.querySelectorAll('line').length).to.be.greaterThan(0, 'Should have axis/grid lines')
|
||||
expect(container.querySelectorAll('text').length).to.be.greaterThan(0, 'Should have axis labels')
|
||||
|
||||
// Update data
|
||||
const updatedData = createMockChartData(5)
|
||||
rerender(<Chart data={updatedData} />)
|
||||
|
||||
// Verify chart structure is maintained after update
|
||||
expect(container.querySelector('svg')).to.exist
|
||||
expect(container.querySelectorAll('line').length).to.be.greaterThan(0, 'Should still have axis/grid lines')
|
||||
expect(container.querySelectorAll('text').length).to.be.greaterThan(0, 'Should still have axis labels')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,105 +1,166 @@
|
||||
import DateFormatter from '../helper/DateFormatter'
|
||||
import NoData from './NoData'
|
||||
import NumberFormatter from '../helper/NumberFormatter'
|
||||
import React, { memo, useCallback } from 'react'
|
||||
import React, { memo, useCallback, useMemo } from 'react'
|
||||
import TooltipComponent from './TooltipComponent'
|
||||
import { default as ReactResizeDetector } from 'react-resize-detector'
|
||||
import { emphasize } from '@material-ui/core/styles'
|
||||
import { useResizeDetector } from 'react-resize-detector'
|
||||
import { emphasize, useTheme } from '@mui/material/styles'
|
||||
import { mapCurveType } from './mapCurveType'
|
||||
import { PlotCurveTypes } from '../../reducers/Charts'
|
||||
import { Point, Tooltip } from './Model'
|
||||
import { Theme, withTheme } from '@material-ui/core'
|
||||
import { useCustomXDomain } from './effects/useCustomXDomain'
|
||||
import { useCustomYDomain } from './effects/useCustomYDomain'
|
||||
import 'react-vis/dist/style.css'
|
||||
const { XYPlot, LineMarkSeries, YAxis, HorizontalGridLines, Hint } = require('react-vis')
|
||||
import { XYChart, Axis, Grid, LineSeries, GlyphSeries } from '@visx/xychart'
|
||||
const abbreviate = require('number-abbreviate')
|
||||
|
||||
export interface Props {
|
||||
data: Array<{ x: number; y: number }>
|
||||
theme: Theme
|
||||
interpolation?: PlotCurveTypes
|
||||
range?: [number?, number?]
|
||||
timeRangeStart?: number
|
||||
color?: string
|
||||
}
|
||||
|
||||
export default withTheme(
|
||||
memo((props: Props) => {
|
||||
const [width, setWidth] = React.useState(300)
|
||||
const [tooltip, setTooltip] = React.useState<Tooltip | undefined>()
|
||||
const detectResize = React.useCallback(newWidth => setWidth(newWidth), [])
|
||||
const CHART_HEIGHT = 150
|
||||
|
||||
const hintFormatter = React.useCallback(
|
||||
(point: any) => [
|
||||
{ title: <b>Time</b>, value: <DateFormatter timeFirst={true} date={new Date(point.x)} /> },
|
||||
{ title: <b>Value</b>, value: <NumberFormatter value={point.y} /> },
|
||||
{ title: <b>Raw</b>, value: <span>{point.y}</span> },
|
||||
],
|
||||
[]
|
||||
)
|
||||
export default memo((props: Props) => {
|
||||
const theme = useTheme()
|
||||
const [tooltip, setTooltip] = React.useState<Tooltip | undefined>()
|
||||
const [hoveredPoint, setHoveredPoint] = React.useState<Point | undefined>()
|
||||
const { width = 300, ref } = useResizeDetector()
|
||||
const chartContainerRef = React.useRef<HTMLDivElement>(null)
|
||||
|
||||
const onMouseLeave = React.useCallback(() => {
|
||||
setTooltip(undefined)
|
||||
}, [])
|
||||
const hintFormatter = React.useCallback(
|
||||
(point: any) => [
|
||||
{ title: <b>Time</b>, value: <DateFormatter timeFirst={true} date={new Date(point.x)} /> },
|
||||
{ title: <b>Value</b>, value: <NumberFormatter value={point.y} /> },
|
||||
{ title: <b>Raw</b>, value: <span>{point.y}</span> },
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const showTooltip = React.useCallback((point: Point, something: { event: MouseEvent }) => {
|
||||
if (!something) {
|
||||
const onMouseLeave = React.useCallback(() => {
|
||||
setTooltip(undefined)
|
||||
setHoveredPoint(undefined)
|
||||
}, [])
|
||||
|
||||
const showTooltip = React.useCallback(
|
||||
(point: Point) => {
|
||||
if (!chartContainerRef.current) {
|
||||
return
|
||||
}
|
||||
setTooltip({ point, value: hintFormatter(point), element: something.event.target as any })
|
||||
}, [])
|
||||
setHoveredPoint(point)
|
||||
setTooltip({ point, value: hintFormatter(point), element: chartContainerRef.current })
|
||||
},
|
||||
[hintFormatter]
|
||||
)
|
||||
|
||||
const paletteColor =
|
||||
props.theme.palette.type === 'light' ? props.theme.palette.secondary.dark : props.theme.palette.primary.light
|
||||
const color = props.color ? props.color : paletteColor
|
||||
const paletteColor =
|
||||
theme.palette.mode === 'light' ? theme.palette.secondary.dark : theme.palette.primary.light
|
||||
const color = props.color ? props.color : paletteColor
|
||||
|
||||
const highlightSelectedPoint = useCallback(
|
||||
(point: Point) => {
|
||||
const highlight = tooltip && tooltip.point.x === point.x && tooltip.point.y === point.y
|
||||
return highlight ? emphasize(color, 0.8) : color
|
||||
},
|
||||
[tooltip, color]
|
||||
)
|
||||
const highlightSelectedPoint = useCallback(
|
||||
(point: Point) => {
|
||||
const highlight = hoveredPoint && hoveredPoint.x === point.x && hoveredPoint.y === point.y
|
||||
return highlight ? emphasize(color, 0.8) : color
|
||||
},
|
||||
[hoveredPoint, color]
|
||||
)
|
||||
|
||||
const formatYAxis = useCallback((num: number) => abbreviate(num), [])
|
||||
const formatYAxis = useCallback((num: number) => abbreviate(num), [])
|
||||
|
||||
const formatXAxis = useCallback((timestamp: number) => {
|
||||
const date = new Date(timestamp)
|
||||
const hours = date.getHours().toString().padStart(2, '0')
|
||||
const minutes = date.getMinutes().toString().padStart(2, '0')
|
||||
const seconds = date.getSeconds().toString().padStart(2, '0')
|
||||
return `${hours}:${minutes}:${seconds}`
|
||||
}, [])
|
||||
|
||||
const xDomain = useCustomXDomain(props)
|
||||
const yDomain = useCustomYDomain(props)
|
||||
const xDomain = useCustomXDomain(props)
|
||||
const yDomain = useCustomYDomain(props)
|
||||
|
||||
const data = props.data
|
||||
const hasData = data.length > 0
|
||||
const dummyDomain = [-1, 1]
|
||||
const dummyData = [{ x: -2, y: -2 }]
|
||||
return (
|
||||
<div>
|
||||
<div style={{ height: '150px', width: '100%', position: 'relative' }}>
|
||||
{data.length === 0 ? <NoData /> : null}
|
||||
<XYPlot
|
||||
width={width}
|
||||
height={180}
|
||||
yDomain={hasData ? yDomain : dummyDomain}
|
||||
xDomain={hasData ? xDomain : dummyDomain}
|
||||
onMouseLeave={onMouseLeave}
|
||||
const data = props.data
|
||||
const hasData = data.length > 0
|
||||
const dummyDomain: [number, number] = [-1, 1]
|
||||
const dummyData = [{ x: -2, y: -2 }]
|
||||
|
||||
const accessors = useMemo(
|
||||
() => ({
|
||||
xAccessor: (d: Point) => d.x,
|
||||
yAccessor: (d: Point) => d.y,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div ref={ref} style={{ height: `${CHART_HEIGHT}px`, width: '100%', position: 'relative' }}>
|
||||
{data.length === 0 ? <NoData /> : null}
|
||||
<div ref={chartContainerRef}>
|
||||
<XYChart
|
||||
width={width || 300}
|
||||
height={CHART_HEIGHT}
|
||||
margin={{ top: 10, right: 10, bottom: 30, left: 50 }}
|
||||
xScale={{ type: 'time', domain: xDomain || dummyDomain }}
|
||||
yScale={{ type: 'linear', domain: hasData ? yDomain : dummyDomain }}
|
||||
onPointerOut={onMouseLeave}
|
||||
>
|
||||
<HorizontalGridLines />
|
||||
<YAxis width={45} tickFormat={formatYAxis} />
|
||||
<LineMarkSeries
|
||||
color={color}
|
||||
colorType="literal"
|
||||
getColor={highlightSelectedPoint}
|
||||
onValueMouseOver={showTooltip}
|
||||
size={3}
|
||||
data={hasData ? data : dummyData}
|
||||
curve={mapCurveType(props.interpolation)}
|
||||
<Grid rows={true} columns={false} stroke={theme.palette.divider} strokeOpacity={0.3} />
|
||||
<Axis
|
||||
orientation="left"
|
||||
numTicks={5}
|
||||
tickFormat={formatYAxis}
|
||||
stroke={theme.palette.text.secondary}
|
||||
tickStroke={theme.palette.text.secondary}
|
||||
tickLabelProps={() => ({ fontSize: 11, fill: theme.palette.text.secondary })}
|
||||
/>
|
||||
<Hint value={{ x: 0, y: 0 }} style={{ pointerEvents: 'none' }}>
|
||||
<TooltipComponent tooltip={tooltip} theme={props.theme} />
|
||||
</Hint>
|
||||
</XYPlot>
|
||||
<ReactResizeDetector handleWidth={true} onResize={detectResize} />
|
||||
<Axis
|
||||
orientation="bottom"
|
||||
numTicks={4}
|
||||
tickFormat={formatXAxis}
|
||||
stroke={theme.palette.text.secondary}
|
||||
tickStroke={theme.palette.text.secondary}
|
||||
tickLabelProps={() => ({ fontSize: 10, fill: theme.palette.text.secondary, textAnchor: 'middle' })}
|
||||
/>
|
||||
<LineSeries
|
||||
dataKey="line"
|
||||
data={hasData ? data : dummyData}
|
||||
xAccessor={accessors.xAccessor}
|
||||
yAccessor={accessors.yAccessor}
|
||||
stroke={color}
|
||||
strokeWidth={2}
|
||||
curve={mapCurveType(props.interpolation)}
|
||||
onPointerMove={(datum) => {
|
||||
if (datum && datum.datum) {
|
||||
const point = datum.datum as Point
|
||||
showTooltip(point)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<GlyphSeries
|
||||
dataKey="points"
|
||||
data={hasData ? data : dummyData}
|
||||
xAccessor={accessors.xAccessor}
|
||||
yAccessor={accessors.yAccessor}
|
||||
renderGlyph={(glyphProps) => {
|
||||
const point = glyphProps.datum as Point
|
||||
const pointColor = highlightSelectedPoint(point)
|
||||
return (
|
||||
<circle
|
||||
cx={glyphProps.x}
|
||||
cy={glyphProps.y}
|
||||
r={3}
|
||||
fill={pointColor}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</XYChart>
|
||||
</div>
|
||||
{/* Custom tooltip outside of visx to maintain exact same appearance */}
|
||||
<TooltipComponent tooltip={tooltip} />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { memo } from 'react'
|
||||
import { Typography } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
|
||||
function NoData() {
|
||||
return (
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import React, { memo } from 'react'
|
||||
import { fade } from '@material-ui/core/styles'
|
||||
import { Fade, Grow, Paper, Popper, Theme, Typography, withTheme } from '@material-ui/core'
|
||||
import { alpha as fade, useTheme } from '@mui/material/styles'
|
||||
import { Fade, Grow, Paper, Popper, Typography } from '@mui/material'
|
||||
import { Tooltip } from './Model'
|
||||
|
||||
function TooltipComponent(props: { tooltip?: Tooltip; theme: Theme }) {
|
||||
function TooltipComponent(props: { tooltip?: Tooltip }) {
|
||||
const theme = useTheme()
|
||||
const { tooltip } = props
|
||||
return (
|
||||
<Popper
|
||||
@@ -26,9 +27,9 @@ function TooltipComponent(props: { tooltip?: Tooltip; theme: Theme }) {
|
||||
padding: '4px',
|
||||
marginTop: '-12px',
|
||||
backgroundColor: fade(
|
||||
props.theme.palette.type === 'light'
|
||||
? props.theme.palette.background.paper
|
||||
: props.theme.palette.background.default,
|
||||
theme.palette.mode === 'light'
|
||||
? theme.palette.background.paper
|
||||
: theme.palette.background.default,
|
||||
0.7
|
||||
),
|
||||
}}
|
||||
@@ -56,4 +57,4 @@ function TooltipComponent(props: { tooltip?: Tooltip; theme: Theme }) {
|
||||
)
|
||||
}
|
||||
|
||||
export default withTheme(memo(TooltipComponent))
|
||||
export default memo(TooltipComponent)
|
||||
|
||||
@@ -3,8 +3,22 @@ import { Props } from '../Chart'
|
||||
|
||||
export function useCustomXDomain(props: Props): [number, number] | undefined {
|
||||
return useMemo(() => {
|
||||
if (props.data.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const lastDataPoint = [...props.data].sort((a, b) => b.x - a.x)[0]
|
||||
const lastDataDate = lastDataPoint ? lastDataPoint.x : Date.now()
|
||||
return props.timeRangeStart ? [Date.now() - props.timeRangeStart, lastDataDate] : undefined
|
||||
|
||||
if (props.timeRangeStart) {
|
||||
// Custom time range mode
|
||||
return [Date.now() - props.timeRangeStart, lastDataDate]
|
||||
} else {
|
||||
// Auto-calculate from data (like react-vis did)
|
||||
const xValues = props.data.map(d => d.x)
|
||||
const minX = Math.min(...xValues)
|
||||
const maxX = Math.max(...xValues)
|
||||
return [minX, maxX]
|
||||
}
|
||||
}, [props.data, props.timeRangeStart])
|
||||
}
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import { PlotCurveTypes } from '../../reducers/Charts'
|
||||
import * as d3Shape from 'd3-shape'
|
||||
|
||||
export function mapCurveType(type: PlotCurveTypes | undefined) {
|
||||
switch (type) {
|
||||
case 'curve':
|
||||
return 'curveMonotoneX'
|
||||
return d3Shape.curveMonotoneX
|
||||
case 'linear':
|
||||
return 'curveLinear'
|
||||
return d3Shape.curveLinear
|
||||
case 'cubic_basis_spline':
|
||||
return 'curveBasis'
|
||||
return d3Shape.curveBasis
|
||||
case 'step_after':
|
||||
return 'curveStepAfter'
|
||||
return d3Shape.curveStepAfter
|
||||
case 'step_before':
|
||||
return 'curveStepBefore'
|
||||
return d3Shape.curveStepBefore
|
||||
default:
|
||||
return 'curveMonotoneX'
|
||||
return d3Shape.curveMonotoneX
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useRef } from 'react'
|
||||
import Play from '@material-ui/icons/PlayArrow'
|
||||
import Pause from '@material-ui/icons/PauseCircleFilled'
|
||||
import Clear from '@material-ui/icons/Clear'
|
||||
import Play from '@mui/icons-material/PlayArrow'
|
||||
import Pause from '@mui/icons-material/PauseCircleFilled'
|
||||
import Clear from '@mui/icons-material/Clear'
|
||||
import CustomIconButton from '../helper/CustomIconButton'
|
||||
import { ChartParameters } from '../../reducers/Charts'
|
||||
import { SettingsButton } from './ChartSettings/SettingsButton'
|
||||
|
||||
@@ -3,7 +3,7 @@ import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../../actions'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { connect } from 'react-redux'
|
||||
import { Menu, MenuItem } from '@material-ui/core'
|
||||
import { Menu, MenuItem } from '@mui/material'
|
||||
import { colors as createColors } from './colors'
|
||||
|
||||
function chartParametersForColor(chart: ChartParameters, color?: string) {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../../actions'
|
||||
import { ChartParameters, PlotCurveTypes } from '../../../reducers/Charts'
|
||||
import { connect } from 'react-redux'
|
||||
import { Menu, MenuItem, Typography } from '@material-ui/core'
|
||||
import { Menu, MenuItem, Typography } from '@mui/material'
|
||||
|
||||
function chartParametersForAction(chart: ChartParameters, action: string) {
|
||||
return {
|
||||
@@ -39,7 +39,12 @@ function InterpolationSettings(props: {
|
||||
|
||||
const menuItems = React.useMemo(() => {
|
||||
return curves.map(curve => (
|
||||
<MenuItem key={curve} onClick={callbacks[curve]} selected={props.chart.interpolation === curve}>
|
||||
<MenuItem
|
||||
key={curve}
|
||||
onClick={callbacks[curve]}
|
||||
selected={props.chart.interpolation === curve}
|
||||
data-menu-item={curve.replace(/_/g, ' ')}
|
||||
>
|
||||
<Typography variant="inherit">{curve.replace(/_/g, ' ')}</Typography>
|
||||
</MenuItem>
|
||||
))
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import * as React from 'react'
|
||||
import ArrowUpward from '@material-ui/icons/ArrowUpward'
|
||||
import ArrowUpward from '@mui/icons-material/ArrowUpward'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../../actions'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { connect } from 'react-redux'
|
||||
import { MenuItem, Typography, ListItemIcon } from '@material-ui/core'
|
||||
import { MenuItem, Typography, ListItemIcon } from '@mui/material'
|
||||
|
||||
function MoveUp(props: { actions: { chart: typeof chartActions }; chart: ChartParameters; close: () => void }) {
|
||||
const moveUp = React.useCallback(() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useCallback, useState, ChangeEvent, MouseEvent, useRef, useEffect, useMemo } from 'react'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { Menu, TextField, Typography } from '@material-ui/core'
|
||||
import { Menu, TextField, Typography } from '@mui/material'
|
||||
import { connect } from 'react-redux'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../../actions'
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as React from 'react'
|
||||
import ChartSettings from '.'
|
||||
import CustomIconButton from '../../helper/CustomIconButton'
|
||||
import MoreVertIcon from '@material-ui/icons/Settings'
|
||||
import MoreVertIcon from '@mui/icons-material/Settings'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
|
||||
export function SettingsButton(props: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { memo } from 'react'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { Menu, MenuItem, TextField, Typography } from '@material-ui/core'
|
||||
import { Menu, MenuItem, TextField, Typography } from '@mui/material'
|
||||
import { connect } from 'react-redux'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../../actions'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { ChangeEvent, MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Menu, TextField, Typography } from '@material-ui/core'
|
||||
import { Button, Menu, TextField, Typography } from '@mui/material'
|
||||
import { chartActions } from '../../../actions'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { connect } from 'react-redux'
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
yellow,
|
||||
brown,
|
||||
blueGrey,
|
||||
} from '@material-ui/core/colors'
|
||||
} from '@mui/material/colors'
|
||||
|
||||
export function colors() {
|
||||
function colorToInt(color: string): [number, number, number] {
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import BarChart from '@material-ui/icons/BarChart'
|
||||
import Clear from '@material-ui/icons/Refresh'
|
||||
import ColorLens from '@material-ui/icons/ColorLens'
|
||||
import BarChart from '@mui/icons-material/BarChart'
|
||||
import Clear from '@mui/icons-material/Refresh'
|
||||
import ColorLens from '@mui/icons-material/ColorLens'
|
||||
import ColorSettings from './ColorSettings'
|
||||
import InterpolationSettings from './InterpolationSettings'
|
||||
import MoveUp from './MoveUp'
|
||||
import MultilineChart from '@material-ui/icons/MultilineChart'
|
||||
import MultilineChart from '@mui/icons-material/MultilineChart'
|
||||
import RangeSettings from './RangeSettings'
|
||||
import React, { memo } from 'react'
|
||||
import Size from './Size'
|
||||
import Sort from '@material-ui/icons/Sort'
|
||||
import Sort from '@mui/icons-material/Sort'
|
||||
import TimeRangeSettings from './TimeRangeSettings'
|
||||
import { ChartParameters } from '../../../reducers/Charts'
|
||||
import { Menu, MenuItem, ListItemIcon, Typography } from '@material-ui/core'
|
||||
import { Menu, MenuItem, ListItemIcon, Typography } from '@mui/material'
|
||||
|
||||
function ChartSettings(props: {
|
||||
open: boolean
|
||||
@@ -65,37 +65,37 @@ function ChartSettings(props: {
|
||||
return (
|
||||
<span>
|
||||
<Menu id="long-menu" anchorEl={props.anchorEl.current} open={props.open} onClose={props.close}>
|
||||
<MenuItem key="range" onClick={toggleRange}>
|
||||
<MenuItem key="range" onClick={toggleRange} data-menu-item="Y-Axis range (Values)">
|
||||
<ListItemIcon>
|
||||
<BarChart />
|
||||
</ListItemIcon>
|
||||
<Typography variant="inherit">Y-Axis range (Values)</Typography>
|
||||
</MenuItem>
|
||||
<MenuItem key="timeRange" onClick={toggleTimeRange}>
|
||||
<MenuItem key="timeRange" onClick={toggleTimeRange} data-menu-item="X-Axis range (Time)">
|
||||
<ListItemIcon>
|
||||
<BarChart />
|
||||
</ListItemIcon>
|
||||
<Typography variant="inherit">X-Axis range (Time)</Typography>
|
||||
</MenuItem>
|
||||
<MenuItem key="interpolation" onClick={toggleInterpolation}>
|
||||
<MenuItem key="interpolation" onClick={toggleInterpolation} data-menu-item="Curve interpolation">
|
||||
<ListItemIcon>
|
||||
<MultilineChart />
|
||||
</ListItemIcon>
|
||||
<Typography variant="inherit">Curve interpolation</Typography>
|
||||
</MenuItem>
|
||||
<MenuItem key="size" onClick={toggleSize}>
|
||||
<MenuItem key="size" onClick={toggleSize} data-menu-item="Size">
|
||||
<ListItemIcon>
|
||||
<Sort />
|
||||
</ListItemIcon>
|
||||
<Typography variant="inherit">Size</Typography>
|
||||
</MenuItem>
|
||||
<MenuItem key="color" onClick={toggleColor}>
|
||||
<MenuItem key="color" onClick={toggleColor} data-menu-item="Color">
|
||||
<ListItemIcon>
|
||||
<ColorLens />
|
||||
</ListItemIcon>
|
||||
<Typography variant="inherit">Color</Typography>
|
||||
</MenuItem>
|
||||
<MenuItem key="clear" onClick={props.resetDataAction}>
|
||||
<MenuItem key="clear" onClick={props.resetDataAction} data-menu-item="Clear data">
|
||||
<ListItemIcon>
|
||||
<Clear />
|
||||
</ListItemIcon>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as React from 'react'
|
||||
import { ChartParameters } from '../../reducers/Charts'
|
||||
import { Typography, Theme, withStyles } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
|
||||
function ChartTitle(props: { parameters: ChartParameters; classes: any }) {
|
||||
const { classes, parameters } = props
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ChartActions } from './ChartActions'
|
||||
import { chartActions } from '../../actions'
|
||||
import { ChartParameters } from '../../reducers/Charts'
|
||||
import { connect } from 'react-redux'
|
||||
import { Paper } from '@material-ui/core'
|
||||
import { Paper } from '@mui/material'
|
||||
const throttle = require('lodash.throttle')
|
||||
|
||||
class ClearableMessageBuffer extends q.RingBuffer<q.Message> {
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import * as q from '../../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import ShowChart from '@material-ui/icons/ShowChart'
|
||||
import ShowChart from '@mui/icons-material/ShowChart'
|
||||
import { AppState } from '../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { chartActions } from '../../actions'
|
||||
import { ChartParameters } from '../../reducers/Charts'
|
||||
import { ChartWithTreeNode } from './ChartWithTreeNode'
|
||||
import { connect } from 'react-redux'
|
||||
import { Grid, Theme, Typography, withStyles } from '@material-ui/core'
|
||||
import { Grid, Typography } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { List } from 'immutable'
|
||||
const { TransitionGroup, CSSTransition } = require('react-transition-group/esm')
|
||||
|
||||
@@ -44,10 +46,15 @@ function mapWidth(width: 'big' | 'medium' | 'small' | undefined, calculatedSpaci
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Helper function to generate unique keys for charts
|
||||
const getChartKey = (chart: ChartParameters) => `${chart.topic}-${chart.dotPath || ''}`
|
||||
|
||||
function ChartPanel(props: Props) {
|
||||
const chartsInView = props.charts.count()
|
||||
|
||||
const [spacing, setSpacing] = React.useState(spacingForChartCount(chartsInView))
|
||||
const nodeRefsMap = React.useRef<Map<string, React.RefObject<HTMLDivElement>>>(new Map())
|
||||
|
||||
React.useEffect(() => {
|
||||
props.actions.chart.loadCharts()
|
||||
@@ -63,17 +70,42 @@ function ChartPanel(props: Props) {
|
||||
}
|
||||
}, [chartsInView])
|
||||
|
||||
const charts = props.charts.map(chartParameters => (
|
||||
<CSSTransition
|
||||
key={`${chartParameters.topic}-${chartParameters.dotPath || ''}`}
|
||||
timeout={{ enter: 500, exit: 500 }}
|
||||
classNames="example"
|
||||
>
|
||||
<Grid item xs={mapWidth(chartParameters.width, spacing)}>
|
||||
<ChartWithTreeNode tree={props.tree} parameters={chartParameters} />
|
||||
</Grid>
|
||||
</CSSTransition>
|
||||
))
|
||||
// Clean up refs for removed charts
|
||||
React.useEffect(() => {
|
||||
const currentKeys = new Set(props.charts.map(getChartKey).toArray())
|
||||
const refsToDelete: string[] = []
|
||||
|
||||
nodeRefsMap.current.forEach((_, key) => {
|
||||
if (!currentKeys.has(key)) {
|
||||
refsToDelete.push(key)
|
||||
}
|
||||
})
|
||||
|
||||
refsToDelete.forEach(key => nodeRefsMap.current.delete(key))
|
||||
}, [props.charts])
|
||||
|
||||
const charts = props.charts.map(chartParameters => {
|
||||
const key = getChartKey(chartParameters)
|
||||
|
||||
// Get or create a ref for this specific chart
|
||||
if (!nodeRefsMap.current.has(key)) {
|
||||
nodeRefsMap.current.set(key, React.createRef<HTMLDivElement>())
|
||||
}
|
||||
const nodeRef = nodeRefsMap.current.get(key)!
|
||||
|
||||
return (
|
||||
<CSSTransition
|
||||
key={key}
|
||||
timeout={{ enter: 500, exit: 500 }}
|
||||
classNames="example"
|
||||
nodeRef={nodeRef}
|
||||
>
|
||||
<Grid item xs={mapWidth(chartParameters.width, spacing)} ref={nodeRef}>
|
||||
<ChartWithTreeNode tree={props.tree} parameters={chartParameters} />
|
||||
</Grid>
|
||||
</CSSTransition>
|
||||
)
|
||||
})
|
||||
|
||||
return (
|
||||
<div className={props.classes.container}>
|
||||
@@ -126,4 +158,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ChartPanel))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ChartPanel) as any)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useRef, useCallback, memo } from 'react'
|
||||
import { ConfirmationRequest } from '../reducers/Global'
|
||||
import { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions, Button } from '@material-ui/core'
|
||||
import { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions, Button } from '@mui/material'
|
||||
import { KeyCodes } from '../utils/KeyCodes'
|
||||
|
||||
function ConfirmationDialog(props: { confirmationRequests: Array<ConfirmationRequest> }) {
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import * as React from 'react'
|
||||
import { useState, useCallback, memo } from 'react'
|
||||
import Add from '@material-ui/icons/Add'
|
||||
import Lock from '@material-ui/icons/Lock'
|
||||
import Undo from '@material-ui/icons/Undo'
|
||||
import Add from '@mui/icons-material/Add'
|
||||
import Lock from '@mui/icons-material/Lock'
|
||||
import Undo from '@mui/icons-material/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, TextField, Tooltip } from '@material-ui/core'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Button, Grid, TextField, Tooltip } from '@mui/material'
|
||||
import { QosSelect } from '../QosSelect'
|
||||
import { QoS } from '../../../../backend/src/DataSource/MqttSource'
|
||||
import Subscriptions from './Subscriptions'
|
||||
const SubscriptionsAny = Subscriptions as any
|
||||
|
||||
interface Props {
|
||||
connection: ConnectionOptions
|
||||
@@ -63,12 +65,13 @@ const ConnectionSettings = memo(function ConnectionSettings(props: Props) {
|
||||
color="secondary"
|
||||
onClick={() => props.managerActions.addSubscription({ topic, qos }, props.connection.id)}
|
||||
variant="contained"
|
||||
data-testid="add-subscription-button"
|
||||
>
|
||||
<Add /> Add
|
||||
</Button>
|
||||
</Grid>
|
||||
<Grid item={true} xs={12} style={{ padding: 0 }}>
|
||||
<Subscriptions connection={props.connection} />
|
||||
<SubscriptionsAny connection={props.connection} />
|
||||
</Grid>
|
||||
<Grid item={true} xs={7} className={classes.gridPadding}>
|
||||
<TextField
|
||||
@@ -97,6 +100,7 @@ const ConnectionSettings = memo(function ConnectionSettings(props: Props) {
|
||||
variant="contained"
|
||||
className={classes.button}
|
||||
onClick={props.managerActions.toggleAdvancedSettings}
|
||||
data-testid="back-button"
|
||||
>
|
||||
<Undo /> Back
|
||||
</Button>
|
||||
@@ -129,4 +133,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(ConnectionSettings))
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(ConnectionSettings) as any)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import * as React from 'react'
|
||||
import ClearAdornment from '../helper/ClearAdornment'
|
||||
import Lock from '@material-ui/icons/Lock'
|
||||
import Lock from '@mui/icons-material/Lock'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Theme, Tooltip, Typography } from '@material-ui/core'
|
||||
import { Button, Theme, Tooltip, Typography } from '@mui/material'
|
||||
import { CertificateParameters, ConnectionOptions } from '../../model/ConnectionOptions'
|
||||
import { CertificateTypes } from '../../actions/ConnectionManager'
|
||||
import { connect } from 'react-redux'
|
||||
import { connectionManagerActions } from '../../actions'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { rendererRpc } from '../../../../events'
|
||||
import { RpcEvents } from '../../../../events/EventsV2'
|
||||
|
||||
@@ -129,7 +129,7 @@ const styles = (theme: Theme) => ({
|
||||
overflow: 'hidden' as 'hidden',
|
||||
whiteSpace: 'nowrap' as 'nowrap',
|
||||
textOverflow: 'ellipsis' as 'ellipsis',
|
||||
color: theme.palette.text.hint,
|
||||
color: theme.palette.text.secondary,
|
||||
},
|
||||
button: {
|
||||
marginTop: theme.spacing(3),
|
||||
@@ -137,4 +137,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(BrowserCertificateFileSelection))
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(BrowserCertificateFileSelection) as any)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import * as React from 'react'
|
||||
import ClearAdornment from '../helper/ClearAdornment'
|
||||
import Lock from '@material-ui/icons/Lock'
|
||||
import Lock from '@mui/icons-material/Lock'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Theme, Tooltip, Typography } from '@material-ui/core'
|
||||
import { Button, Theme, Tooltip, Typography } from '@mui/material'
|
||||
import { CertificateParameters, ConnectionOptions } from '../../model/ConnectionOptions'
|
||||
import { CertificateTypes } from '../../actions/ConnectionManager'
|
||||
import { connect } from 'react-redux'
|
||||
import { connectionManagerActions } from '../../actions'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
function CertificateFileSelection(props: {
|
||||
certificateType: CertificateTypes
|
||||
@@ -71,7 +71,7 @@ const styles = (theme: Theme) => ({
|
||||
overflow: 'hidden' as 'hidden',
|
||||
whiteSpace: 'nowrap' as 'nowrap',
|
||||
textOverflow: 'ellipsis' as 'ellipsis',
|
||||
color: theme.palette.text.hint,
|
||||
color: theme.palette.text.secondary,
|
||||
},
|
||||
button: {
|
||||
marginTop: theme.spacing(3),
|
||||
@@ -79,4 +79,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(CertificateFileSelection))
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(CertificateFileSelection) as any)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import * as React from 'react'
|
||||
import CertificateFileSelection from './CertificateFileSelection'
|
||||
import BrowserCertificateFileSelection from './BrowserCertificateFileSelection'
|
||||
import Undo from '@material-ui/icons/Undo'
|
||||
import Undo from '@mui/icons-material/Undo'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Grid } from '@material-ui/core'
|
||||
import { Button, Grid } from '@mui/material'
|
||||
import { connect } from 'react-redux'
|
||||
import { connectionManagerActions } from '../../actions'
|
||||
import { ConnectionOptions } from '../../model/ConnectionOptions'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { isBrowserMode } from '../../utils/browserMode'
|
||||
|
||||
// Check if we're in browser mode
|
||||
const isBrowserMode =
|
||||
typeof window !== 'undefined' && (typeof process === 'undefined' || process.env?.BROWSER_MODE === 'true')
|
||||
const CertSelector = isBrowserMode ? BrowserCertificateFileSelection : CertificateFileSelection
|
||||
// Use browser or desktop file selection based on mode
|
||||
const CertSelector: any = isBrowserMode ? BrowserCertificateFileSelection : CertificateFileSelection
|
||||
|
||||
interface Props {
|
||||
connection: ConnectionOptions
|
||||
@@ -110,4 +110,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(Certificates))
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(Certificates) as any)
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import ConnectionHealthIndicator from '../helper/ConnectionHealthIndicator'
|
||||
import PowerSettingsNew from '@material-ui/icons/PowerSettingsNew'
|
||||
import PowerSettingsNew from '@mui/icons-material/PowerSettingsNew'
|
||||
import React from 'react'
|
||||
import { Button } from '@material-ui/core'
|
||||
import { Button } from '@mui/material'
|
||||
|
||||
function ConnectButton(props: { connecting: boolean; classes: any; toggle: () => void }) {
|
||||
const { classes, toggle, connecting } = props
|
||||
|
||||
if (connecting) {
|
||||
return (
|
||||
<Button variant="contained" color="primary" className={classes.button} onClick={toggle}>
|
||||
<Button variant="contained" color="primary" className={classes.button} onClick={toggle} data-testid="abort-button">
|
||||
<ConnectionHealthIndicator />
|
||||
Abort
|
||||
</Button>
|
||||
@@ -16,7 +16,7 @@ function ConnectButton(props: { connecting: boolean; classes: any; toggle: () =>
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="contained" color="primary" className={classes.button} onClick={toggle}>
|
||||
<Button variant="contained" color="primary" className={classes.button} onClick={toggle} data-testid="connect-button">
|
||||
<PowerSettingsNew /> Connect
|
||||
</Button>
|
||||
)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import ConnectButton from './ConnectButton'
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import Save from '@material-ui/icons/Save'
|
||||
import Delete from '@material-ui/icons/Delete'
|
||||
import Settings from '@material-ui/icons/Settings'
|
||||
import Visibility from '@material-ui/icons/Visibility'
|
||||
import VisibilityOff from '@material-ui/icons/VisibilityOff'
|
||||
import Save from '@mui/icons-material/Save'
|
||||
import Delete from '@mui/icons-material/Delete'
|
||||
import Settings from '@mui/icons-material/Settings'
|
||||
import Visibility from '@mui/icons-material/Visibility'
|
||||
import VisibilityOff from '@mui/icons-material/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 { KeyCodes } from '../../utils/KeyCodes'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { ToggleSwitch } from './ToggleSwitch'
|
||||
import { useGlobalKeyEventHandler } from '../../effects/useGlobalKeyEventHandler'
|
||||
import {
|
||||
@@ -24,7 +25,7 @@ import {
|
||||
InputLabel,
|
||||
MenuItem,
|
||||
TextField,
|
||||
} from '@material-ui/core'
|
||||
} from '@mui/material'
|
||||
|
||||
interface Props {
|
||||
connection: ConnectionOptions
|
||||
@@ -235,6 +236,7 @@ function ConnectionSettings(props: Props) {
|
||||
variant="contained"
|
||||
className={classes.button}
|
||||
onClick={props.managerActions.toggleAdvancedSettings}
|
||||
data-testid="advanced-button"
|
||||
>
|
||||
<Settings /> Advanced
|
||||
</Button>
|
||||
@@ -285,4 +287,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ConnectionSettings))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ConnectionSettings) as any)
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import * as React from 'react'
|
||||
import ConnectionSettings from './ConnectionSettings'
|
||||
const ConnectionSettingsAny = ConnectionSettings as any
|
||||
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 { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Modal, Paper, Toolbar, Typography, Collapse } from '@mui/material'
|
||||
import AdvancedConnectionSettings from './AdvancedConnectionSettings'
|
||||
const AdvancedConnectionSettingsAny = AdvancedConnectionSettings as any
|
||||
import Certificates from './Certificates'
|
||||
const CertificatesAny = Certificates as any
|
||||
|
||||
interface Props {
|
||||
actions: any
|
||||
@@ -34,13 +38,13 @@ class ConnectionSetup extends React.PureComponent<Props, {}> {
|
||||
return (
|
||||
<div>
|
||||
<Collapse in={!showAdvancedSettings && !showCertificateSettings}>
|
||||
<ConnectionSettings connection={connection} />
|
||||
<ConnectionSettingsAny connection={connection} />
|
||||
</Collapse>
|
||||
<Collapse in={showAdvancedSettings && !showCertificateSettings}>
|
||||
<AdvancedConnectionSettings connection={connection} />
|
||||
<AdvancedConnectionSettingsAny connection={connection} />
|
||||
</Collapse>
|
||||
<Collapse in={showCertificateSettings}>
|
||||
<Certificates connection={connection} />
|
||||
<CertificatesAny connection={connection} />
|
||||
</Collapse>
|
||||
</div>
|
||||
)
|
||||
@@ -111,7 +115,7 @@ const styles = (theme: Theme) => ({
|
||||
textOverflow: 'ellipsis' as 'ellipsis',
|
||||
whiteSpace: 'nowrap' as 'nowrap',
|
||||
overflow: 'hidden' as 'hidden',
|
||||
color: theme.palette.text.hint,
|
||||
color: theme.palette.text.secondary,
|
||||
fontSize: '0.9em',
|
||||
marginLeft: theme.spacing(4),
|
||||
},
|
||||
@@ -134,4 +138,4 @@ const mapDispatchToProps = (dispatch: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ConnectionSetup))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ConnectionSetup) as any)
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
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'
|
||||
import Add from '@mui/icons-material/Add'
|
||||
import { Fab } from '@mui/material'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
const styles = (theme: Theme) => ({
|
||||
addButton: {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import { connect } from 'react-redux'
|
||||
import { ListItem, Typography } from '@material-ui/core'
|
||||
import { ListItem, Typography } from '@mui/material'
|
||||
import { toMqttConnection, ConnectionOptions } from '../../../model/ConnectionOptions'
|
||||
import { withStyles, Theme } from '@material-ui/core/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connectionActions, connectionManagerActions } from '../../../actions'
|
||||
|
||||
@@ -62,9 +63,9 @@ export const connectionItemStyle = (theme: Theme) => ({
|
||||
textOverflow: 'ellipsis' as 'ellipsis',
|
||||
whiteSpace: 'nowrap' as 'nowrap',
|
||||
overflow: 'hidden' as 'hidden',
|
||||
color: theme.palette.text.hint,
|
||||
color: theme.palette.text.secondary,
|
||||
fontSize: '0.7em',
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(null, mapDispatchToProps)(withStyles(connectionItemStyle)(ConnectionItem))
|
||||
export default connect(null, mapDispatchToProps)(withStyles(connectionItemStyle)(ConnectionItem) as any)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import ConnectionItem from './ConnectionItem'
|
||||
const ConnectionItemAny = ConnectionItem as any
|
||||
import React from 'react'
|
||||
import { AddButton } from './AddButton'
|
||||
import { AppState } from '../../../reducers'
|
||||
@@ -7,8 +8,9 @@ import { connect } from 'react-redux'
|
||||
import { connectionManagerActions } from '../../../actions'
|
||||
import { ConnectionOptions } from '../../../model/ConnectionOptions'
|
||||
import { KeyCodes } from '../../../utils/KeyCodes'
|
||||
import { List } from '@material-ui/core'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { List } from '@mui/material'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { useGlobalKeyEventHandler } from '../../../effects/useGlobalKeyEventHandler'
|
||||
|
||||
interface Props {
|
||||
@@ -49,7 +51,7 @@ function ProfileList(props: Props) {
|
||||
<List style={{ height: '100%' }} component="nav" subheader={createConnectionButton}>
|
||||
<div className={classes.list}>
|
||||
{Object.values(connections).map(connection => (
|
||||
<ConnectionItem connection={connection} key={connection.id} selected={selected === connection.id} />
|
||||
<ConnectionItemAny connection={connection} key={connection.id} selected={selected === connection.id} />
|
||||
))}
|
||||
</div>
|
||||
</List>
|
||||
@@ -77,4 +79,4 @@ const mapStateToProps = (state: AppState) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ProfileList))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ProfileList) as any)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useCallback, useState } from 'react'
|
||||
import Delete from '@material-ui/icons/Delete'
|
||||
import Delete from '@mui/icons-material/Delete'
|
||||
import { connectionManagerActions } from '../../actions'
|
||||
import { ConnectionOptions } from '../../model/ConnectionOptions'
|
||||
import {
|
||||
@@ -12,9 +12,9 @@ import {
|
||||
TableBody,
|
||||
Paper,
|
||||
Theme,
|
||||
} from '@material-ui/core'
|
||||
} from '@mui/material'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { connect } from 'react-redux'
|
||||
|
||||
function Subscriptions(props: {
|
||||
@@ -87,4 +87,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(Subscriptions))
|
||||
export default connect(undefined, mapDispatchToProps)(withStyles(styles)(Subscriptions) as any)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React from 'react'
|
||||
import { FormControlLabel, Switch } from '@material-ui/core'
|
||||
import { FormControlLabel, Switch } from '@mui/material'
|
||||
|
||||
export function ToggleSwitch(props: { value: boolean; classes: any; toggle: () => void; label: string }) {
|
||||
const { classes, value, toggle, label } = props
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { Theme, withStyles } from '@material-ui/core'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
interface Props {
|
||||
keyboardKey: string
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { Theme, withStyles } from '@material-ui/core'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
const cursor = require('./cursor.png')
|
||||
|
||||
interface State {
|
||||
@@ -74,7 +75,7 @@ const style = (theme: Theme) => ({
|
||||
height: '32px',
|
||||
position: 'fixed' as 'fixed',
|
||||
zIndex: 1000000,
|
||||
filter: theme.palette.type === 'light' ? undefined : 'invert(100%)',
|
||||
filter: theme.palette.mode === 'light' ? undefined : 'invert(100%)',
|
||||
pointerEvents: 'none' as 'none',
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { Theme, withStyles } from '@material-ui/core'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import Key from './Key'
|
||||
|
||||
interface State {
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
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 { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Button, Modal, Paper, Toolbar, Typography } from '@material-ui/core'
|
||||
import SentimentDissatisfied from '@mui/icons-material/SentimentDissatisfied'
|
||||
import Warning from '@mui/icons-material/Warning'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Button, Modal, Paper, Toolbar, Typography } from '@mui/material'
|
||||
|
||||
interface State {
|
||||
error?: Error
|
||||
@@ -11,6 +12,7 @@ interface State {
|
||||
|
||||
interface Props {
|
||||
classes: any
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
class ErrorBoundary extends React.PureComponent<Props, State> {
|
||||
@@ -23,12 +25,12 @@ class ErrorBoundary extends React.PureComponent<Props, State> {
|
||||
}
|
||||
|
||||
private restart = () => {
|
||||
window.location = window.location
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
private clearStorage = () => {
|
||||
PersistentStorage.clear()
|
||||
window.location = window.location
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
public componentDidCatch(error: Error, errorInfo: any) {
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import * as React from 'react'
|
||||
import ChartPanel from '../ChartPanel'
|
||||
import ReactSplitPane from 'react-split-pane'
|
||||
import ReactSplitPaneImport from 'react-split-pane'
|
||||
import Tree from '../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'
|
||||
import { useResizeDetector } from 'react-resize-detector'
|
||||
|
||||
// Type cast to any to work around React 18 compatibility issues with react-split-pane 0.1.x
|
||||
const ReactSplitPane = ReactSplitPaneImport as any
|
||||
|
||||
interface Props {
|
||||
heightProperty: any
|
||||
@@ -21,11 +24,23 @@ function ContentView(props: Props) {
|
||||
const [sidebarWidth, setSidebarWidth] = React.useState<string | number>('40%')
|
||||
const [detectedHeight, setDetectedHeight] = React.useState(0)
|
||||
const [detectedSidebarWidth, setDetectedSidebarWidth] = React.useState(0)
|
||||
const detectSize = React.useCallback((width, newHeight) => {
|
||||
|
||||
const { height: resizeHeight, ref: heightRef } = useResizeDetector()
|
||||
const { width: resizeWidth, ref: widthRef } = useResizeDetector()
|
||||
|
||||
React.useEffect(() => {
|
||||
if (resizeHeight) setDetectedHeight(resizeHeight)
|
||||
}, [resizeHeight])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (resizeWidth) setDetectedSidebarWidth(resizeWidth)
|
||||
}, [resizeWidth])
|
||||
|
||||
const detectSize = React.useCallback((width: any, newHeight: any) => {
|
||||
setDetectedHeight(newHeight)
|
||||
}, [])
|
||||
|
||||
const detectSidebarSize = React.useCallback(width => {
|
||||
const detectSidebarSize = React.useCallback((width: any) => {
|
||||
setDetectedSidebarWidth(width)
|
||||
}, [])
|
||||
|
||||
@@ -63,7 +78,7 @@ function ContentView(props: Props) {
|
||||
split="vertical"
|
||||
minSize={0}
|
||||
size={sidebarWidth}
|
||||
onChange={setSidebarWidth}
|
||||
onChange={(size: number) => setSidebarWidth(size)}
|
||||
onDragFinished={closeSidebarCompletelyIfItSitsOnTheEdge}
|
||||
allowResize={true}
|
||||
style={{ height: '100%' }}
|
||||
@@ -80,20 +95,18 @@ function ContentView(props: Props) {
|
||||
style={{ height: 'calc(100vh - 64px)' }}
|
||||
pane1Style={{ maxHeight: '100%' }}
|
||||
pane2Style={{ borderTop: '1px solid #999', display: 'flex' }}
|
||||
onChange={setHeight}
|
||||
onChange={(size: number) => setHeight(size)}
|
||||
onDragFinished={closeDrawerCompletelyIfItSitsOnTheEdge}
|
||||
>
|
||||
<Tree />
|
||||
{/** Passing height constraints via flex options down */}
|
||||
<div style={{ flex: 1, display: 'flex', height: '100%', width: '100%' }}>
|
||||
<div ref={heightRef} style={{ flex: 1, display: 'flex', height: '100%', width: '100%' }}>
|
||||
{/** Resize detector must not be in the scroll zone, it needs to detect actual available size */}
|
||||
<ReactResizeDetector handleHeight={true} onResize={detectSize} />
|
||||
<ChartPanel />
|
||||
</div>
|
||||
</ReactSplitPane>
|
||||
</span>
|
||||
<div style={{ height: '100%' }}>
|
||||
<ReactResizeDetector handleWidth={true} onResize={detectSidebarSize} />
|
||||
<div ref={widthRef} style={{ height: '100%' }}>
|
||||
<div
|
||||
className={props.paneDefaults}
|
||||
style={{ minWidth: '250px', height: '100%', overflowY: 'auto', overflowX: 'hidden' }}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
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'
|
||||
import { Snackbar, SnackbarContent } from '@mui/material'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { green, red } from '@mui/material/colors'
|
||||
|
||||
interface Props {
|
||||
message?: string
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
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/PlayArrow'
|
||||
import Pause from '@mui/icons-material/PauseCircleFilled'
|
||||
import Resume from '@mui/icons-material/PlayArrow'
|
||||
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'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
|
||||
const styles = (theme: Theme) => ({
|
||||
icon: {
|
||||
@@ -102,4 +103,4 @@ const mapDispatchToProps = (dispatch: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(PauseButton))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(PauseButton) as any)
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import React, { useCallback, useState, useRef } from 'react'
|
||||
import ClearAdornment from '../helper/ClearAdornment'
|
||||
import Search from '@material-ui/icons/Search'
|
||||
import Search from '@mui/icons-material/Search'
|
||||
import { AppState } from '../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { InputBase } from '@material-ui/core'
|
||||
import { InputBase } from '@mui/material'
|
||||
import { settingsActions } from '../../actions'
|
||||
import { fade, Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { alpha as fade, Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { useGlobalKeyEventHandler } from '../../effects/useGlobalKeyEventHandler'
|
||||
import { KeyCodes } from '../../utils/KeyCodes'
|
||||
|
||||
@@ -142,4 +143,4 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
})
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(SearchBar))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(SearchBar) as any)
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
import * as React from 'react'
|
||||
import CloudOff from '@material-ui/icons/CloudOff'
|
||||
import CloudOff from '@mui/icons-material/CloudOff'
|
||||
import Logout from '@mui/icons-material/Logout'
|
||||
import ConnectionHealthIndicator from '../helper/ConnectionHealthIndicator'
|
||||
import Menu from '@material-ui/icons/Menu'
|
||||
const ConnectionHealthIndicatorAny = ConnectionHealthIndicator as any
|
||||
import Menu from '@mui/icons-material/Menu'
|
||||
import PauseButton from './PauseButton'
|
||||
import SearchBar from './SearchBar'
|
||||
import { AppBar, Button, IconButton, Toolbar, Typography } from '@material-ui/core'
|
||||
import { AppBar, Button, IconButton, Toolbar, Typography } from '@mui/material'
|
||||
import { AppState } from '../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { connectionActions, globalActions, settingsActions } from '../../actions'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { isBrowserMode } from '../../utils/browserMode'
|
||||
import { useAuth } from '../../contexts/AuthContext'
|
||||
|
||||
const styles = (theme: Theme) => ({
|
||||
title: {
|
||||
@@ -33,6 +38,9 @@ const styles = (theme: Theme) => ({
|
||||
disconnect: {
|
||||
margin: 'auto 8px auto auto',
|
||||
},
|
||||
logout: {
|
||||
margin: 'auto 0 auto 8px',
|
||||
},
|
||||
disconnectLabel: {
|
||||
color: theme.palette.primary.contrastText,
|
||||
},
|
||||
@@ -54,6 +62,22 @@ class TitleBar extends React.PureComponent<Props, {}> {
|
||||
this.state = {}
|
||||
}
|
||||
|
||||
private handleLogout = async () => {
|
||||
// Disconnect first
|
||||
this.props.actions.connection.disconnect()
|
||||
|
||||
// Clear credentials from sessionStorage
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.removeItem('mqtt-explorer-username')
|
||||
sessionStorage.removeItem('mqtt-explorer-password')
|
||||
}
|
||||
|
||||
// Reload page to reset all state and show login dialog
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.reload()
|
||||
}
|
||||
}
|
||||
|
||||
public render() {
|
||||
const { actions, classes } = this.props
|
||||
|
||||
@@ -75,18 +99,39 @@ class TitleBar extends React.PureComponent<Props, {}> {
|
||||
<PauseButton />
|
||||
<Button
|
||||
className={classes.disconnect}
|
||||
classes={{ label: classes.disconnectLabel }}
|
||||
sx={{ color: 'primary.contrastText' }}
|
||||
onClick={actions.connection.disconnect}
|
||||
data-testid="disconnect-button"
|
||||
>
|
||||
Disconnect <CloudOff className={classes.disconnectIcon} />
|
||||
</Button>
|
||||
<ConnectionHealthIndicator withBackground={true} />
|
||||
<LogoutButton classes={classes} onLogout={this.handleLogout} />
|
||||
<ConnectionHealthIndicatorAny withBackground={true} />
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Separate component to use hooks
|
||||
function LogoutButton({ classes, onLogout }: { classes: any; onLogout: () => void }) {
|
||||
const { authDisabled } = useAuth()
|
||||
|
||||
if (!isBrowserMode || authDisabled) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
className={classes.logout}
|
||||
sx={{ color: 'primary.contrastText' }}
|
||||
onClick={onLogout}
|
||||
>
|
||||
Logout <Logout className={classes.disconnectIcon} />
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
const mapStateToProps = (state: AppState) => {
|
||||
return {
|
||||
topicFilter: state.settings.get('topicFilter'),
|
||||
|
||||
@@ -1,57 +1,106 @@
|
||||
import * as React from 'react'
|
||||
import { Dialog, DialogTitle, DialogContent, DialogActions, TextField, Button, Typography } from '@material-ui/core'
|
||||
import { Dialog, DialogTitle, DialogContent, DialogActions, TextField, Button, Typography } from '@mui/material'
|
||||
|
||||
interface LoginDialogProps {
|
||||
open: boolean
|
||||
onLogin: (username: string, password: string) => void
|
||||
error?: string
|
||||
waitTimeSeconds?: number
|
||||
}
|
||||
|
||||
export function LoginDialog(props: LoginDialogProps) {
|
||||
const [username, setUsername] = React.useState('')
|
||||
const [password, setPassword] = React.useState('')
|
||||
const [countdown, setCountdown] = React.useState<number | undefined>(props.waitTimeSeconds)
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
// Update countdown when waitTimeSeconds prop changes
|
||||
React.useEffect(() => {
|
||||
setCountdown(props.waitTimeSeconds)
|
||||
}, [props.waitTimeSeconds])
|
||||
|
||||
// Countdown timer
|
||||
React.useEffect(() => {
|
||||
if (countdown === undefined || countdown <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const timer = setInterval(() => {
|
||||
setCountdown(prev => {
|
||||
if (prev === undefined || prev <= 1) {
|
||||
return undefined
|
||||
}
|
||||
return prev - 1
|
||||
})
|
||||
}, 1000)
|
||||
|
||||
return () => clearInterval(timer)
|
||||
}, [countdown])
|
||||
|
||||
const handleLogin = () => {
|
||||
if (countdown !== undefined && countdown > 0) {
|
||||
// Don't allow login during countdown
|
||||
return
|
||||
}
|
||||
if (!username || !password) {
|
||||
// Don't allow empty credentials
|
||||
return
|
||||
}
|
||||
props.onLogin(username, password)
|
||||
}
|
||||
|
||||
const handleKeyPress = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleLogin()
|
||||
}
|
||||
}
|
||||
|
||||
const isDisabled = countdown !== undefined && countdown > 0
|
||||
|
||||
return (
|
||||
<Dialog open={props.open} disableEscapeKeyDown disableBackdropClick>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<DialogTitle>Login to MQTT Explorer</DialogTitle>
|
||||
<DialogContent>
|
||||
{props.error && (
|
||||
<Typography color="error" style={{ marginBottom: 16 }}>
|
||||
{props.error}
|
||||
</Typography>
|
||||
)}
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
label="Username"
|
||||
type="text"
|
||||
fullWidth
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
label="Password"
|
||||
type="password"
|
||||
fullWidth
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button type="submit" color="primary" variant="contained">
|
||||
Login
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</form>
|
||||
<Dialog open={props.open} disableEscapeKeyDown onClose={(event, reason) => { if (reason !== 'backdropClick') { /* Allow closing only via escape if needed */ } }}>
|
||||
<DialogTitle>Login to MQTT Explorer</DialogTitle>
|
||||
<DialogContent>
|
||||
{props.error && (
|
||||
<Typography color="error" style={{ marginBottom: 16 }}>
|
||||
{props.error}
|
||||
</Typography>
|
||||
)}
|
||||
{countdown !== undefined && countdown > 0 && (
|
||||
<Typography color="warning" style={{ marginBottom: 16, fontWeight: 'bold' }}>
|
||||
Please wait {countdown} seconds before trying again...
|
||||
</Typography>
|
||||
)}
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
label="Username"
|
||||
type="text"
|
||||
fullWidth
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
disabled={isDisabled}
|
||||
required
|
||||
data-testid="username-input"
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
label="Password"
|
||||
type="password"
|
||||
fullWidth
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
disabled={isDisabled}
|
||||
required
|
||||
data-testid="password-input"
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleLogin} color="primary" variant="contained" disabled={isDisabled}>
|
||||
{isDisabled ? `Wait ${countdown}s` : 'Login'}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as React from 'react'
|
||||
import { TextField, MenuItem, Tooltip } from '@material-ui/core'
|
||||
import { TextField, MenuItem, Tooltip } from '@mui/material'
|
||||
import { QoS } from '../../../backend/src/DataSource/MqttSource'
|
||||
|
||||
export function QosSelect(props: { selected: QoS; onChange: (value: QoS) => void; label?: string }) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import * as React from 'react'
|
||||
import { InputLabel, Switch, Theme, Tooltip } from '@material-ui/core'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { InputLabel, Switch, Theme, Tooltip } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
const sha1 = require('sha1')
|
||||
|
||||
function BooleanSwitch(props: { title: string; value: boolean; tooltip: string; action: () => void; classes: any }) {
|
||||
function BooleanSwitch(props: { title: string; value: boolean; tooltip: string; action: () => void; classes: any; 'data-testid'?: string }) {
|
||||
const { tooltip, value, action, title, classes } = props
|
||||
|
||||
const clickHandler = (e: React.MouseEvent) => {
|
||||
@@ -20,7 +20,13 @@ function BooleanSwitch(props: { title: string; value: boolean; tooltip: string;
|
||||
</InputLabel>
|
||||
</Tooltip>
|
||||
<Tooltip title={tooltip}>
|
||||
<Switch name={`toggle-${sha1(title)}`} checked={value} onChange={action} color="primary" />
|
||||
<Switch
|
||||
name={`toggle-${sha1(title)}`}
|
||||
checked={value}
|
||||
onChange={action}
|
||||
color="primary"
|
||||
data-testid={props['data-testid']}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -3,9 +3,10 @@ import React, { useMemo } from 'react'
|
||||
import { AppState } from '../../reducers'
|
||||
import { Base64Message } from '../../../../backend/src/Model/Base64Message'
|
||||
import { connect } from 'react-redux'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { TopicViewModel } from '../../model/TopicViewModel'
|
||||
import { Typography } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
import { usePollingToFetchTreeNode } from '../helper/usePollingToFetchTreeNode'
|
||||
import { useUpdateComponentWhenNodeUpdates } from '../helper/useUpdateComponentWhenNodeUpdates'
|
||||
const abbreviate = require('number-abbreviate')
|
||||
@@ -19,7 +20,7 @@ const styles = (theme: Theme) => ({
|
||||
container: {
|
||||
width: '100%',
|
||||
height: '224px',
|
||||
backgroundColor: theme.palette.type === 'dark' ? 'rebeccapurple' : '#ebebeb',
|
||||
backgroundColor: theme.palette.mode === 'dark' ? 'rebeccapurple' : '#ebebeb',
|
||||
marginBottom: 0,
|
||||
padding: '8px',
|
||||
},
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import * as React from 'react'
|
||||
import BooleanSwitch from './BooleanSwitch'
|
||||
import BrokerStatistics from './BrokerStatistics'
|
||||
import ChevronRight from '@material-ui/icons/ChevronRight'
|
||||
import ChevronRight from '@mui/icons-material/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 { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { TopicOrder } from '../../reducers/Settings'
|
||||
|
||||
import {
|
||||
@@ -19,9 +20,10 @@ import {
|
||||
InputLabel,
|
||||
MenuItem,
|
||||
Select,
|
||||
SelectChangeEvent,
|
||||
Typography,
|
||||
Tooltip,
|
||||
} from '@material-ui/core'
|
||||
} from '@mui/material'
|
||||
|
||||
export const autoExpandLimitSet = [
|
||||
{
|
||||
@@ -70,7 +72,7 @@ const styles = (theme: Theme) => ({
|
||||
},
|
||||
author: {
|
||||
margin: 'auto 8px 8px auto',
|
||||
color: theme.palette.text.hint,
|
||||
color: theme.palette.text.secondary,
|
||||
cursor: 'pointer' as 'pointer',
|
||||
},
|
||||
})
|
||||
@@ -136,6 +138,7 @@ class Settings extends React.PureComponent<Props, {}> {
|
||||
tooltip="Enable dark theme"
|
||||
value={theme === 'dark'}
|
||||
action={actions.settings.toggleTheme}
|
||||
data-testid="dark-mode-toggle"
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -167,7 +170,7 @@ class Settings extends React.PureComponent<Props, {}> {
|
||||
)
|
||||
}
|
||||
|
||||
private onChangeAutoExpand = (e: React.ChangeEvent<{ value: unknown }>) => {
|
||||
private onChangeAutoExpand = (e: SelectChangeEvent<number>) => {
|
||||
this.props.actions.settings.setAutoExpandLimit(parseInt(String(e.target.value), 10))
|
||||
}
|
||||
|
||||
@@ -199,7 +202,7 @@ class Settings extends React.PureComponent<Props, {}> {
|
||||
)
|
||||
}
|
||||
|
||||
private onChangeSorting = (e: React.ChangeEvent<{ value: unknown }>) => {
|
||||
private onChangeSorting = (e: SelectChangeEvent<TopicOrder>) => {
|
||||
this.props.actions.settings.setTopicOrder(e.target.value as TopicOrder)
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ import DateFormatter from '../helper/DateFormatter'
|
||||
import { AppState } from '../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { Input, InputLabel, MenuItem, Select, Theme } from '@material-ui/core'
|
||||
import { Input, InputLabel, MenuItem, Select, Theme } from '@mui/material'
|
||||
import { settingsActions } from '../../actions'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
function importAll(r: any) {
|
||||
r.keys().forEach(r)
|
||||
@@ -38,7 +38,7 @@ function TimeLocaleSettings(props: Props) {
|
||||
</MenuItem>
|
||||
))
|
||||
|
||||
function updateLocale(e: React.ChangeEvent<{ value: unknown }>) {
|
||||
function updateLocale(e: any) {
|
||||
const locale = e.target.value ? String(e.target.value) : ''
|
||||
actions.settings.setTimeLocale(locale)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import ShowChart from '@material-ui/icons/ShowChart'
|
||||
import ShowChart from '@mui/icons-material/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 { Fade, Paper, Popper, Tooltip } from '@mui/material'
|
||||
import { JsonPropertyLocation } from '../../../../../backend/src/JsonAstParser'
|
||||
|
||||
interface Props {
|
||||
@@ -41,31 +41,29 @@ function ChartPreview(props: Props) {
|
||||
|
||||
const addChartToPanelButton = hasEnoughDataToDisplayDiagrams ? (
|
||||
<Tooltip title="Add to chart panel">
|
||||
<ShowChart
|
||||
<span
|
||||
ref={chartIconRef}
|
||||
className={props.classes.icon}
|
||||
onMouseEnter={mouseOver}
|
||||
onMouseLeave={mouseOut}
|
||||
onClick={onClick}
|
||||
data-test-type="ShowChart"
|
||||
data-test={props.literal.path}
|
||||
/>
|
||||
style={{ cursor: 'pointer', display: 'inline-flex' }}
|
||||
>
|
||||
<ShowChart className={props.classes.icon} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip title="Add to chart panel, not enough data for preview">
|
||||
<ShowChart
|
||||
onClick={onClick}
|
||||
className={props.classes.icon}
|
||||
style={{ color: '#aaa' }}
|
||||
data-test-type="ShowChart"
|
||||
data-test={props.literal.path}
|
||||
/>
|
||||
<span onClick={onClick} style={{ cursor: 'pointer', display: 'inline-flex' }}>
|
||||
<ShowChart className={props.classes.icon} style={{ color: '#aaa' }} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
|
||||
return (
|
||||
<span>
|
||||
{addChartToPanelButton}
|
||||
<div style={{ display: 'inline' }}>
|
||||
<span data-test-type="ShowChart" data-test={props.literal.path} style={{ display: 'inline-block' }}>
|
||||
{addChartToPanelButton}
|
||||
</span>
|
||||
<Popper open={open} anchorEl={chartIconRef.current} placement="left-end">
|
||||
<Fade in={open} timeout={300}>
|
||||
<Paper style={{ width: '300px' }}>
|
||||
@@ -77,7 +75,7 @@ function ChartPreview(props: Props) {
|
||||
</Paper>
|
||||
</Fade>
|
||||
</Popper>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { Theme } from '@material-ui/core'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { Theme } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
interface Props {
|
||||
changes: Array<Diff.Change>
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
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 Add from '@mui/icons-material/Add'
|
||||
import ChartPreview from './ChartPreview'
|
||||
import Remove from '@material-ui/icons/Remove'
|
||||
import Remove from '@mui/icons-material/Remove'
|
||||
import { JsonPropertyLocation } from '../../../../../backend/src/JsonAstParser'
|
||||
import { lineChangeStyle, trimNewlineRight } from './util'
|
||||
import { Theme } from '@material-ui/core'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import { Theme } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
interface Props {
|
||||
changes: Array<diff.Change>
|
||||
|
||||
@@ -8,7 +8,8 @@ import { isPlottable, lineChangeStyle, trimNewlineRight } from './util'
|
||||
import { JsonPropertyLocation, literalsMappedByLines } from '../../../../../backend/src/JsonAstParser'
|
||||
import { selectTextWithCtrlA } from '../../../utils/handleTextSelectWithCtrlA'
|
||||
import { style } from './style'
|
||||
import { withStyles, Typography } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import 'prismjs/components/prism-json'
|
||||
|
||||
interface Props {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { CodeBlockColors, CodeBlockColorsBraceMonokai } from '../CodeBlockColors'
|
||||
import { Theme } from '@material-ui/core'
|
||||
import { Theme } from '@mui/material'
|
||||
|
||||
export const style = (theme: Theme) => {
|
||||
const codeBlockColors = theme.palette.type === 'light' ? CodeBlockColors : CodeBlockColorsBraceMonokai
|
||||
const codeBlockColors = theme.palette.mode === 'light' ? CodeBlockColors : CodeBlockColorsBraceMonokai
|
||||
const codeBaseStyle = {
|
||||
font: "12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace",
|
||||
display: 'inline-grid' as 'inline-grid',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useCallback, useState, useEffect, memo } from 'react'
|
||||
import { Badge, Typography } from '@material-ui/core'
|
||||
import { Badge, Typography } from '@mui/material'
|
||||
import { selectTextWithCtrlA } from '../../utils/handleTextSelectWithCtrlA'
|
||||
import { Theme, withStyles, emphasize } from '@material-ui/core/styles'
|
||||
import { Theme, emphasize } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
interface HistoryItem {
|
||||
key: string
|
||||
@@ -87,6 +88,7 @@ function HistoryDrawer(props: Props) {
|
||||
invisible={!visible}
|
||||
badgeContent={props.items.length}
|
||||
color="primary"
|
||||
data-testid="message-history"
|
||||
>
|
||||
{expanded ? '▼ History' : '▶ History'}
|
||||
</Badge>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { memo } from 'react'
|
||||
import { Message } from '../../../../backend/src/Model'
|
||||
import { Tooltip } from '@material-ui/core'
|
||||
import { Tooltip } from '@mui/material'
|
||||
|
||||
export const MessageId = memo(function MessageId(props: { message: Message; addComma?: boolean }) {
|
||||
const { message, addComma } = props
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as q from '../../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import { TopicViewModel } from '../../model/TopicViewModel'
|
||||
import { Typography } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
|
||||
interface Props {
|
||||
node?: q.TreeNode<TopicViewModel>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react'
|
||||
import ExpandMore from '@material-ui/icons/ExpandMore'
|
||||
import { ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography, Theme } from '@material-ui/core'
|
||||
import { withStyles } from '@material-ui/styles'
|
||||
import ExpandMore from '@mui/icons-material/ExpandMore'
|
||||
import { Accordion, AccordionDetails, AccordionSummary, Typography, Theme } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
|
||||
const styles = (theme: Theme) => ({
|
||||
summary: { minHeight: '0' },
|
||||
@@ -19,14 +19,14 @@ const Panel = (props: {
|
||||
detailsHidden?: boolean
|
||||
}) => {
|
||||
return (
|
||||
<ExpansionPanel defaultExpanded={true} disabled={props.disabled}>
|
||||
<ExpansionPanelSummary expandIcon={<ExpandMore />} className={props.classes.summary}>
|
||||
<Accordion defaultExpanded={true} disabled={props.disabled}>
|
||||
<AccordionSummary expandIcon={<ExpandMore />} className={props.classes.summary}>
|
||||
<Typography className={props.classes.heading}>{props.children[0]}</Typography>
|
||||
</ExpansionPanelSummary>
|
||||
</AccordionSummary>
|
||||
{props.detailsHidden ? null : (
|
||||
<ExpansionPanelDetails className={props.classes.detail}>{props.children[1]}</ExpansionPanelDetails>
|
||||
<AccordionDetails className={props.classes.detail}>{props.children[1]}</AccordionDetails>
|
||||
)}
|
||||
</ExpansionPanel>
|
||||
</Accordion>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as React from 'react'
|
||||
import { default as AceEditor } from 'react-ace'
|
||||
import { Theme, withTheme } from '@material-ui/core'
|
||||
import { useTheme } from '@mui/material/styles'
|
||||
import 'ace-builds'
|
||||
import 'ace-builds/webpack-resolver'
|
||||
import 'ace-builds/src-noconflict/mode-json'
|
||||
@@ -13,11 +13,11 @@ import 'react-ace'
|
||||
|
||||
function Editor(props: {
|
||||
editorMode: string
|
||||
theme: Theme
|
||||
value: string | undefined
|
||||
onChange: (value: string) => void
|
||||
editorRef: React.Ref<AceEditor>
|
||||
}) {
|
||||
const theme = useTheme()
|
||||
const editorOptions = {
|
||||
showLineNumbers: false,
|
||||
tabSize: 2,
|
||||
@@ -28,7 +28,7 @@ function Editor(props: {
|
||||
ref={props.editorRef}
|
||||
style={{}}
|
||||
mode={props.editorMode}
|
||||
theme={props.theme.palette.type === 'dark' ? 'monokai' : 'dawn'}
|
||||
theme={theme.palette.mode === 'dark' ? 'monokai' : 'dawn'}
|
||||
name="UNIQUE_ID_OF_DIV"
|
||||
width="100%"
|
||||
height="200px"
|
||||
@@ -45,4 +45,4 @@ function Editor(props: {
|
||||
)
|
||||
}
|
||||
|
||||
export default withTheme(Editor)
|
||||
export default Editor
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as React from 'react'
|
||||
import { FormControlLabel, Radio, RadioGroup } from '@material-ui/core'
|
||||
import { FormControlLabel, Radio, RadioGroup } from '@mui/material'
|
||||
|
||||
interface Props {
|
||||
value: string
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import Editor from './Editor'
|
||||
import { AttachFileOutlined, FormatAlignLeft } from '@material-ui/icons'
|
||||
import { AttachFileOutlined, FormatAlignLeft } from '@mui/icons-material'
|
||||
import Message from './Model/Message'
|
||||
import Navigation from '@material-ui/icons/Navigation'
|
||||
import Navigation from '@mui/icons-material/Navigation'
|
||||
import PublishHistory from './PublishHistory'
|
||||
import React, { useCallback, useMemo, useState, useRef, memo } from 'react'
|
||||
import RetainSwitch from './RetainSwitch'
|
||||
import TopicInput from './TopicInput'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Fab, Theme, Tooltip, withTheme } from '@material-ui/core'
|
||||
import { Button, Fab, Tooltip } from '@mui/material'
|
||||
import { connect } from 'react-redux'
|
||||
import { EditorModeSelect } from './EditorModeSelect'
|
||||
import { globalActions, publishActions } from '../../../actions'
|
||||
@@ -23,7 +23,6 @@ interface Props {
|
||||
globalActions: typeof globalActions
|
||||
retain: boolean
|
||||
editorMode: string
|
||||
theme: Theme
|
||||
}
|
||||
|
||||
function useHistory(): [Array<Message>, (topic: string, payload?: string) => void] {
|
||||
@@ -221,4 +220,4 @@ const mapStateToProps = (state: AppState) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withTheme(Publish))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(Publish)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import QosSelect from './QosPublishOption'
|
||||
import React from 'react'
|
||||
import { Checkbox, FormControlLabel, Tooltip } from '@material-ui/core'
|
||||
import { Checkbox, FormControlLabel, Tooltip } from '@mui/material'
|
||||
import { publishActions } from '../../../actions'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { AppState } from '../../../reducers'
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ClearAdornment from '../../helper/ClearAdornment'
|
||||
import React, { useCallback, useMemo, useRef } from 'react'
|
||||
import { FormControl, Input, InputLabel } from '@material-ui/core'
|
||||
import { FormControl, Input, InputLabel } from '@mui/material'
|
||||
import { publishActions } from '../../../actions'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { AppState } from '../../../reducers'
|
||||
|
||||
@@ -2,12 +2,14 @@ import * as q from '../../../../backend/src/Model'
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import NodeStats from './NodeStats'
|
||||
import ValuePanel from './ValueRenderer/ValuePanel'
|
||||
const ValuePanelAny = ValuePanel as any
|
||||
import { AppState } from '../../reducers'
|
||||
import { ExpansionPanelDetails } from '@material-ui/core'
|
||||
import { AccordionDetails } from '@mui/material'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { settingsActions, sidebarActions } from '../../actions'
|
||||
import { Theme, withStyles } from '@material-ui/core/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { TopicViewModel } from '../../model/TopicViewModel'
|
||||
import TopicPanel from './TopicPanel/TopicPanel'
|
||||
import Panel from './Panel'
|
||||
@@ -56,16 +58,16 @@ function Sidebar(props: Props) {
|
||||
<div id="Sidebar" className={classes.drawer}>
|
||||
<div>
|
||||
<TopicPanel node={node} />
|
||||
<ValuePanel lastUpdate={node ? node.lastUpdate : 0} />
|
||||
<ValuePanelAny lastUpdate={node ? node.lastUpdate : 0} />
|
||||
<Panel>
|
||||
<span>Publish</span>
|
||||
<Publish connectionId={props.connectionId} />
|
||||
</Panel>
|
||||
<Panel detailsHidden={!node}>
|
||||
<span>Stats</span>
|
||||
<ExpansionPanelDetails className={classes.details}>
|
||||
<AccordionDetails className={classes.details}>
|
||||
<NodeStats node={node} />
|
||||
</ExpansionPanelDetails>
|
||||
</AccordionDetails>
|
||||
</Panel>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import CustomIconButton from '../../helper/CustomIconButton'
|
||||
import Delete from '@material-ui/icons/Delete'
|
||||
import Delete from '@mui/icons-material/Delete'
|
||||
import React, { useCallback } from 'react'
|
||||
import { Badge } from '@material-ui/core'
|
||||
import { Badge } from '@mui/material'
|
||||
|
||||
export const RecursiveTopicDeleteButton = (props: {
|
||||
node?: q.TreeNode<any>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import 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 Button from '@mui/material/Button'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { treeActions } from '../../../actions'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
@@ -39,8 +40,8 @@ class Topic extends React.PureComponent<Props, {}> {
|
||||
<Button
|
||||
onClick={() => this.props.actions.selectTopic(edge!.target)}
|
||||
size="small"
|
||||
variant={theme.palette.type === 'light' ? 'contained' : undefined}
|
||||
color={theme.palette.type === 'light' ? 'primary' : 'secondary'}
|
||||
variant={theme.palette.mode === 'light' ? 'contained' : undefined}
|
||||
color={theme.palette.mode === 'light' ? 'primary' : 'secondary'}
|
||||
className={this.props.classes.button}
|
||||
key={edge!.hash()}
|
||||
>
|
||||
@@ -66,4 +67,4 @@ const mapDispatchToProps = (dispatch: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(null, mapDispatchToProps)(withStyles(styles, { withTheme: true })(Topic))
|
||||
export default connect(null, mapDispatchToProps)(withStyles(styles, { withTheme: true })(Topic) as any)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import CustomIconButton from '../../helper/CustomIconButton'
|
||||
import Delete from '@material-ui/icons/Delete'
|
||||
import Delete from '@mui/icons-material/Delete'
|
||||
import React from 'react'
|
||||
|
||||
export const TopicDeleteButton = (props: {
|
||||
|
||||
@@ -3,6 +3,7 @@ import Copy from '../../helper/Copy'
|
||||
import Panel from '../Panel'
|
||||
import React, { useMemo, useCallback } from 'react'
|
||||
import Topic from './Topic'
|
||||
const TopicAny = Topic as any
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { connect } from 'react-redux'
|
||||
import { RecursiveTopicDeleteButton } from './RecursiveTopicDeleteButton'
|
||||
@@ -31,7 +32,7 @@ const TopicPanel = (props: { node?: q.TreeNode<any>; actions: typeof sidebarActi
|
||||
<RecursiveTopicDeleteButton node={node} deleteTopicAction={deleteTopic} />
|
||||
<TopicTypeButton node={node} />
|
||||
</span>
|
||||
<Topic node={node} />
|
||||
<TopicAny node={node} />
|
||||
</Panel>
|
||||
),
|
||||
[node, node?.childTopicCount()]
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import React, { useCallback, useMemo } from 'react'
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import ClickAwayListener from '@material-ui/core/ClickAwayListener'
|
||||
import Grow from '@material-ui/core/Grow'
|
||||
import Button from '@material-ui/core/Button'
|
||||
import Paper from '@material-ui/core/Paper'
|
||||
import Popper from '@material-ui/core/Popper'
|
||||
import MenuItem from '@material-ui/core/MenuItem'
|
||||
import MenuList from '@material-ui/core/MenuList'
|
||||
import WarningRounded from '@material-ui/icons/WarningRounded'
|
||||
import ClickAwayListener from '@mui/material/ClickAwayListener'
|
||||
import Grow from '@mui/material/Grow'
|
||||
import Button from '@mui/material/Button'
|
||||
import Paper from '@mui/material/Paper'
|
||||
import Popper from '@mui/material/Popper'
|
||||
import MenuItem from '@mui/material/MenuItem'
|
||||
import MenuList from '@mui/material/MenuList'
|
||||
import WarningRounded from '@mui/icons-material/WarningRounded'
|
||||
import { MessageDecoder, decoders } from '../../../decoders'
|
||||
import { Tooltip } from '@material-ui/core'
|
||||
import { Tooltip } from '@mui/material'
|
||||
|
||||
export const TopicTypeButton = (props: { node?: q.TreeNode<any> }) => {
|
||||
const { node } = props
|
||||
@@ -46,7 +46,7 @@ export const TopicTypeButton = (props: { node?: q.TreeNode<any> }) => {
|
||||
[open]
|
||||
)
|
||||
|
||||
const handleClose = useCallback((event: React.MouseEvent<Document, MouseEvent>) => {
|
||||
const handleClose = useCallback((event: any) => {
|
||||
if (anchorEl && anchorEl.contains(event.target as HTMLElement)) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import Code from '@material-ui/icons/Code'
|
||||
import Reorder from '@material-ui/icons/Reorder'
|
||||
import ToggleButton from '@material-ui/lab/ToggleButton'
|
||||
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup'
|
||||
import Code from '@mui/icons-material/Code'
|
||||
import Reorder from '@mui/icons-material/Reorder'
|
||||
import ToggleButton from '@mui/material/ToggleButton'
|
||||
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup'
|
||||
import { settingsActions } from '../../../actions'
|
||||
import { Tooltip, withStyles, Theme } from '@material-ui/core'
|
||||
import { Tooltip } from '@mui/material'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { connect } from 'react-redux'
|
||||
@@ -73,4 +75,4 @@ const mapStateToProps = (state: AppState) => {
|
||||
}
|
||||
}
|
||||
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ActionButtons))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ActionButtons) as any)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import Clear from '@material-ui/icons/Clear'
|
||||
import Clear from '@mui/icons-material/Clear'
|
||||
import React, { useMemo } from 'react'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Button, Tooltip } from '@material-ui/core'
|
||||
import { Button, Tooltip } from '@mui/material'
|
||||
import { connect } from 'react-redux'
|
||||
import { sidebarActions } from '../../../actions'
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as q from '../../../../../backend/src/Model'
|
||||
import * as React from 'react'
|
||||
import ShowChart from '@material-ui/icons/ShowChart'
|
||||
import ShowChart from '@mui/icons-material/ShowChart'
|
||||
import Copy from '../../helper/Copy'
|
||||
import DateFormatter from '../../helper/DateFormatter'
|
||||
import History from '../HistoryDrawer'
|
||||
|
||||
@@ -9,7 +9,9 @@ import React, { useCallback } from 'react'
|
||||
import ValueRenderer from './ValueRenderer'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { bindActionCreators } from 'redux'
|
||||
import { Theme, Typography, withStyles } from '@material-ui/core'
|
||||
import { Typography } from '@mui/material'
|
||||
import { Theme } from '@mui/material/styles'
|
||||
import { withStyles } from '@mui/styles'
|
||||
import { connect } from 'react-redux'
|
||||
import { sidebarActions } from '../../../actions'
|
||||
import DeleteSelectedTopicButton from './DeleteSelectedTopicButton'
|
||||
@@ -143,4 +145,4 @@ const styles = (theme: Theme) => ({
|
||||
})
|
||||
|
||||
// @ts-ignore
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ValuePanel))
|
||||
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(ValuePanel) as any)
|
||||
|
||||
@@ -4,7 +4,7 @@ import CodeDiff from '../CodeDiff'
|
||||
import { AppState } from '../../../reducers'
|
||||
import { connect } from 'react-redux'
|
||||
import { ValueRendererDisplayMode } from '../../../reducers/Settings'
|
||||
import { Fade } from '@material-ui/core'
|
||||
import { Fade } from '@mui/material'
|
||||
import { Decoder } from '../../../../../backend/src/Model/Decoder'
|
||||
import { useDecoder } from '../../hooks/useDecoder'
|
||||
import { TopicViewModel } from '../../../model/TopicViewModel'
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user