creates <mde-mining-dashboard> custom html element, for miner control and stats display.

This commit is contained in:
Snider 2025-11-09 04:41:07 +00:00
parent a043a09d22
commit dc0eae0888
20 changed files with 10296 additions and 0 deletions

View file

@ -95,6 +95,10 @@ func (s *Service) setupRoutes() {
}
}
// New route to serve the custom HTML element bundle
// This path now points to the output of the Angular project within the 'ui' directory
s.Router.StaticFile("/component/mining-dashboard.js", "./ui/dist/ui/main.js")
// Register Swagger UI route under a distinct sub-path to avoid conflicts
swaggerURL := ginSwagger.URL(fmt.Sprintf("http://%s%s/doc.json", s.DisplayAddr, s.SwaggerUIPath))
s.Router.GET(s.SwaggerUIPath+"/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, swaggerURL, ginSwagger.InstanceName(s.SwaggerInstanceName)))

17
ui/.editorconfig Normal file
View file

@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false
[*.md]
max_line_length = off
trim_trailing_whitespace = false

43
ui/.gitignore vendored Normal file
View file

@ -0,0 +1,43 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
__screenshots__/
# System files
.DS_Store
Thumbs.db

59
ui/README.md Normal file
View file

@ -0,0 +1,59 @@
# Ui
This project was generated using [Angular CLI](https://github.com/angular/angular-cli) version 20.3.6.
## Development server
To start a local development server, run:
```bash
ng serve
```
Once the server is running, open your browser and navigate to `http://localhost:4200/`. The application will automatically reload whenever you modify any of the source files.
## Code scaffolding
Angular CLI includes powerful code scaffolding tools. To generate a new component, run:
```bash
ng generate component component-name
```
For a complete list of available schematics (such as `components`, `directives`, or `pipes`), run:
```bash
ng generate --help
```
## Building
To build the project run:
```bash
ng build
```
This will compile your project and store the build artifacts in the `dist/` directory. By default, the production build optimizes your application for performance and speed.
## Running unit tests
To execute unit tests with the [Karma](https://karma-runner.github.io) test runner, use the following command:
```bash
ng test
```
## Running end-to-end tests
For end-to-end (e2e) testing, run:
```bash
ng e2e
```
Angular CLI does not come with an end-to-end testing framework by default. You can choose one that suits your needs.
## Additional Resources
For more information on using the Angular CLI, including detailed command references, visit the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.

97
ui/angular.json Normal file
View file

@ -0,0 +1,97 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"ui": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.css",
"node_modules/@shoelace-style/shoelace/dist/themes/light.css"
],
"scripts": [
"node_modules/@shoelace-style/shoelace/dist/shoelace.js"
],
"outputHashing": "none",
"namedChunks": false,
"optimization": true
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
]
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "ui:build:production"
},
"development": {
"buildTarget": "ui:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/styles.css"
]
}
}
}
}
}
}

9676
ui/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

48
ui/package.json Normal file
View file

@ -0,0 +1,48 @@
{
"name": "ui",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"prettier": {
"printWidth": 100,
"singleQuote": true,
"overrides": [
{
"files": "*.html",
"options": {
"parser": "angular"
}
}
]
},
"private": true,
"dependencies": {
"@angular/common": "^20.3.0",
"@angular/compiler": "^20.3.0",
"@angular/core": "^20.3.0",
"@angular/forms": "^20.3.0",
"@angular/platform-browser": "^20.3.0",
"@angular/router": "^20.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.15.0"
},
"devDependencies": {
"@angular/build": "^20.3.6",
"@angular/cli": "^20.3.6",
"@angular/compiler-cli": "^20.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.9.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.9.2"
}
}

BIN
ui/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

12
ui/src/app/app.config.ts Normal file
View file

@ -0,0 +1,12 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes)
]
};

0
ui/src/app/app.css Normal file
View file

0
ui/src/app/app.html Normal file
View file

3
ui/src/app/app.routes.ts Normal file
View file

@ -0,0 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];

23
ui/src/app/app.spec.ts Normal file
View file

@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { App } from './app';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [App],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(App);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render title', () => {
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, ui');
});
});

213
ui/src/app/app.ts Normal file
View file

@ -0,0 +1,213 @@
import { Component, OnInit, Input, OnDestroy, ElementRef, ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
import { interval, Subscription } from 'rxjs';
import { switchMap, startWith } from 'rxjs/operators';
// Import Shoelace components
import '@shoelace-style/shoelace/dist/components/card/card.js';
import '@shoelace-style/shoelace/dist/components/button/button.js';
import '@shoelace-style/shoelace/dist/components/icon/icon.js';
// Add other Shoelace components as needed for your UI
interface HashratePoint {
timestamp: string; // ISO string
hashrate: number;
}
@Component({
selector: 'mde-mining-dashboard', // This will be your custom element tag
standalone: true,
imports: [CommonModule, HttpClientModule], // HttpClientModule is needed for HttpClient
template: `
<sl-card class="mining-dashboard-card">
<div slot="header" class="card-header">
<sl-icon name="cpu"></sl-icon>
<h3>Mining Dashboard: {{ minerName }}</h3>
</div>
<p *ngIf="loading">Loading hashrate data...</p>
<p *ngIf="error" class="error-message">Error: {{ error }}</p>
<div *ngIf="!loading && !error">
<p>Current Hashrate: <strong>{{ currentHashrate }} H/s</strong></p>
<p>Last Updated: {{ lastUpdated | date:'mediumTime' }}</p>
<h4>Hashrate History ({{ hashrateHistory.length }} points)</h4>
<ul class="history-list">
<li *ngFor="let point of hashrateHistory | slice:0:5">
{{ point.timestamp | date:'mediumTime' }}: {{ point.hashrate }} H/s
</li>
<li *ngIf="hashrateHistory.length > 5">...</li>
</ul>
<!-- Here you would integrate a charting library -->
<!-- <canvas #hashrateChart></canvas> -->
</div>
<div slot="footer" class="card-footer">
<sl-button variant="primary" (click)="fetchHashrate()">Refresh</sl-button>
<sl-button variant="text" (click)="toggleDetails()">{{ showDetails ? 'Hide Details' : 'Show Details' }}</sl-button>
</div>
<div *ngIf="showDetails" class="details-section">
<h5>Raw History Data:</h5>
<pre>{{ hashrateHistory | json }}</pre>
</div>
</sl-card>
`,
styles: [`
.mining-dashboard-card {
width: 100%;
max-width: 500px;
margin: 20px auto;
border: 1px solid var(--sl-color-neutral-300);
border-radius: var(--sl-border-radius-medium);
box-shadow: var(--sl-shadow-medium);
}
.card-header {
display: flex;
align-items: center;
gap: 10px;
padding: var(--sl-spacing-medium);
border-bottom: 1px solid var(--sl-color-neutral-200);
}
.card-header h3 {
margin: 0;
font-size: var(--sl-font-size-large);
}
.card-header sl-icon {
font-size: var(--sl-font-size-x-large);
color: var(--sl-color-primary-500);
}
.error-message {
color: var(--sl-color-danger-500);
font-weight: bold;
}
.history-list {
list-style-type: none;
padding: 0;
max-height: 150px;
overflow-y: auto;
border: 1px solid var(--sl-color-neutral-100);
border-radius: var(--sl-border-radius-small);
padding: var(--sl-spacing-x-small);
background-color: var(--sl-color-neutral-50);
}
.history-list li {
padding: var(--sl-spacing-2x-small) 0;
border-bottom: 1px dotted var(--sl-color-neutral-100);
}
.history-list li:last-child {
border-bottom: none;
}
.card-footer {
display: flex;
justify-content: flex-end;
gap: var(--sl-spacing-small);
padding-top: var(--sl-spacing-medium);
border-top: 1px solid var(--sl-color-neutral-200);
}
.details-section {
margin-top: var(--sl-spacing-medium);
padding: var(--sl-spacing-small);
background-color: var(--sl-color-neutral-50);
border: 1px solid var(--sl-color-neutral-200);
border-radius: var(--sl-border-radius-small);
}
.details-section pre {
white-space: pre-wrap;
word-break: break-all;
font-size: var(--sl-font-size-x-small);
max-height: 200px;
overflow-y: auto;
}
`],
encapsulation: ViewEncapsulation.ShadowDom // Crucial for isolation
})
export class MiningDashboardElementComponent implements OnInit, OnDestroy {
@Input() minerName: string = 'xmrig'; // Default miner name
@Input() apiBaseUrl: string = 'http://127.0.0.1:9090/api/v1/mining'; // Default API base URL
hashrateHistory: HashratePoint[] = [];
currentHashrate: number = 0;
lastUpdated: Date | null = null;
loading: boolean = true;
error: string | null = null;
showDetails: boolean = false;
private refreshSubscription: Subscription | undefined;
constructor(private http: HttpClient, private elementRef: ElementRef) {}
ngOnInit(): void {
this.startAutoRefresh();
}
ngOnDestroy(): void {
this.stopAutoRefresh();
}
startAutoRefresh(): void {
this.stopAutoRefresh(); // Stop any existing refresh
this.refreshSubscription = interval(10000) // Refresh every 10 seconds
.pipe(startWith(0), switchMap(() => this.fetchHashrateObservable()))
.subscribe({
next: (history) => {
this.hashrateHistory = history;
if (history.length > 0) {
this.currentHashrate = history[history.length - 1].hashrate;
this.lastUpdated = new Date(history[history.length - 1].timestamp);
} else {
this.currentHashrate = 0;
this.lastUpdated = null;
}
this.loading = false;
this.error = null;
},
error: (err) => {
console.error('Failed to fetch hashrate history:', err);
this.error = 'Failed to fetch hashrate history.';
this.loading = false;
}
});
}
stopAutoRefresh(): void {
if (this.refreshSubscription) {
this.refreshSubscription.unsubscribe();
this.refreshSubscription = undefined;
}
}
fetchHashrate(): void {
this.loading = true;
this.error = null;
this.fetchHashrateObservable().subscribe({
next: (history) => {
this.hashrateHistory = history;
if (history.length > 0) {
this.currentHashrate = history[history.length - 1].hashrate;
this.lastUpdated = new Date(history[history.length - 1].timestamp);
} else {
this.currentHashrate = 0;
this.lastUpdated = null;
}
this.loading = false;
},
error: (err) => {
console.error('Failed to fetch hashrate history:', err);
this.error = 'Failed to fetch hashrate history.';
this.loading = false;
}
});
}
private fetchHashrateObservable() {
const url = `${this.apiBaseUrl}/miners/${this.minerName}/hashrate-history`;
return this.http.get<HashratePoint[]>(url);
}
toggleDetails(): void {
this.showDetails = !this.showDetails;
}
}

13
ui/src/index.html Normal file
View file

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ui</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

24
ui/src/main.ts Normal file
View file

@ -0,0 +1,24 @@
import { createApplication } from '@angular/platform-browser';
import { createCustomElement } from '@angular/elements';
import { MiningDashboardElementComponent } from './app/app'; // Renamed App to MiningDashboardElementComponent
import { importProvidersFrom } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { CommonModule } from '@angular/common';
(async () => {
// Bootstrap a minimal Angular application to provide
// necessary services like HttpClient to the custom element.
const app = await createApplication({
providers: [
importProvidersFrom(HttpClientModule, CommonModule)
]
});
// Define your custom element
const MiningDashboardElement = createCustomElement(MiningDashboardElementComponent, { injector: app.injector });
// Register the custom element with the browser
customElements.define('mde-mining-dashboard', MiningDashboardElement);
console.log('mde-mining-dashboard custom element registered!');
})();

1
ui/src/styles.css Normal file
View file

@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

15
ui/tsconfig.app.json Normal file
View file

@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"include": [
"src/**/*.ts"
],
"exclude": [
"src/**/*.spec.ts"
]
}

34
ui/tsconfig.json Normal file
View file

@ -0,0 +1,34 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"compileOnSave": false,
"compilerOptions": {
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "ES2022",
"module": "preserve"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"typeCheckHostBindings": true,
"strictTemplates": true
},
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.spec.json"
}
]
}

14
ui/tsconfig.spec.json Normal file
View file

@ -0,0 +1,14 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.ts"
]
}