Browse Source
# Conflicts: # application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.javapull/16844/head
92 changed files with 1210 additions and 977 deletions
@ -0,0 +1,108 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.config; |
|||
|
|||
import org.junit.jupiter.api.BeforeAll; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.io.TempDir; |
|||
import org.springframework.beans.factory.annotation.Autowired; |
|||
import org.springframework.boot.autoconfigure.ImportAutoConfiguration; |
|||
import org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration; |
|||
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration; |
|||
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; |
|||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; |
|||
import org.springframework.boot.test.context.SpringBootTest; |
|||
import org.springframework.test.context.DynamicPropertyRegistry; |
|||
import org.springframework.test.context.DynamicPropertySource; |
|||
import org.springframework.test.web.servlet.MockMvc; |
|||
|
|||
import java.io.ByteArrayOutputStream; |
|||
import java.io.IOException; |
|||
import java.io.UncheckedIOException; |
|||
import java.nio.charset.StandardCharsets; |
|||
import java.nio.file.Files; |
|||
import java.nio.file.Path; |
|||
import java.util.zip.GZIPOutputStream; |
|||
|
|||
import static org.hamcrest.Matchers.containsString; |
|||
import static org.springframework.http.HttpHeaders.ACCEPT_ENCODING; |
|||
import static org.springframework.http.HttpHeaders.CONTENT_ENCODING; |
|||
import static org.springframework.http.HttpHeaders.VARY; |
|||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; |
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; |
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; |
|||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; |
|||
|
|||
/** |
|||
* Loads the real thingsboard.yml, so the test fails if its static resource chain keys stop binding again. |
|||
*/ |
|||
@SpringBootTest(classes = StaticResourceCompressionTest.WebMvcConfig.class, properties = "spring.config.name=thingsboard") |
|||
@AutoConfigureMockMvc(addFilters = false) |
|||
public class StaticResourceCompressionTest { |
|||
|
|||
private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8); |
|||
private static final byte[] JS_GZ = gzip(JS); |
|||
private static final byte[] CSS = "@font-face { src: url(font.woff2); }\n".getBytes(StandardCharsets.UTF_8); |
|||
|
|||
@TempDir |
|||
static Path webRoot; |
|||
|
|||
@Autowired |
|||
private MockMvc mvc; |
|||
|
|||
@DynamicPropertySource |
|||
static void staticLocations(DynamicPropertyRegistry registry) { |
|||
registry.add("spring.web.resources.static-locations", () -> webRoot.toUri().toString()); |
|||
} |
|||
|
|||
@BeforeAll |
|||
static void createStaticFiles() throws IOException { |
|||
Files.write(webRoot.resolve("main.js"), JS); |
|||
Files.write(webRoot.resolve("main.js.gz"), JS_GZ); |
|||
Files.write(webRoot.resolve("styles.css"), CSS); |
|||
Files.write(webRoot.resolve("font.woff2"), new byte[]{1, 2, 3}); |
|||
} |
|||
|
|||
@Test |
|||
public void servesPrebuiltGzipWhenClientAcceptsIt() throws Exception { |
|||
mvc.perform(get("/main.js").header(ACCEPT_ENCODING, "gzip, deflate, br")) |
|||
.andExpect(status().isOk()) |
|||
.andExpect(header().string(CONTENT_ENCODING, "gzip")) |
|||
.andExpect(header().string(VARY, containsString(ACCEPT_ENCODING))) |
|||
.andExpect(content().contentTypeCompatibleWith("text/javascript")) |
|||
.andExpect(content().bytes(JS_GZ)); |
|||
} |
|||
|
|||
@Test |
|||
public void servesRawFileWhenClientDoesNotAcceptGzip() throws Exception { |
|||
mvc.perform(get("/main.js")) |
|||
.andExpect(status().isOk()) |
|||
.andExpect(header().doesNotExist(CONTENT_ENCODING)) |
|||
.andExpect(content().bytes(JS)); |
|||
} |
|||
|
|||
@Test |
|||
public void servesStylesheetUnchanged() throws Exception { |
|||
// the content version strategy would rewrite url(font.woff2) to url(font-<md5>.woff2)
|
|||
mvc.perform(get("/styles.css").header(ACCEPT_ENCODING, "gzip")) |
|||
.andExpect(status().isOk()) |
|||
.andExpect(header().doesNotExist(CONTENT_ENCODING)) |
|||
.andExpect(content().bytes(CSS)); |
|||
} |
|||
|
|||
// not @Configuration: @ComponentScan("org.thingsboard.server") in other tests would pick it up
|
|||
@ImportAutoConfiguration({DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class}) |
|||
static class WebMvcConfig { |
|||
} |
|||
|
|||
private static byte[] gzip(byte[] data) { |
|||
ByteArrayOutputStream out = new ByteArrayOutputStream(); |
|||
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) { |
|||
gzip.write(data); |
|||
} catch (IOException e) { |
|||
throw new UncheckedIOException(e); |
|||
} |
|||
return out.toByteArray(); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,36 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
|
|||
// The Chromium builds shipped with the packages. They must be the Chromium release that playwright-core is released with,
|
|||
// which install.js checks, so a Playwright upgrade needs new builds here. The Docker image has the chromium package of
|
|||
// Debian instead: see docker/Dockerfile.
|
|||
//
|
|||
// The Chromium project publishes builds of the main branch only, so these are the builds from where the release was
|
|||
// branched off, without the fixes made on the release branch later. The Debian package of the image has those fixes.
|
|||
//
|
|||
// To update after a Playwright upgrade, for the version that the error of install.js names:
|
|||
// 1. Find where the release was branched off: chromium_main_branch_position in
|
|||
// https://chromiumdash.appspot.com/fetch_version?version=<version>
|
|||
// 2. For Linux_x64 and for Win_x64, take the highest snapshot build that is not above that position. Builds are listed by
|
|||
// the start of their number, so shorten the start until one appears:
|
|||
// https://www.googleapis.com/storage/v1/b/chromium-browser-snapshots/o?delimiter=/&fields=prefixes&prefix=Linux_x64/<start of the position>
|
|||
// 3. Set the version (the release from the error, ending in .0) and the two paths, and build the module. It fails with
|
|||
// the SHA-256 of an archive: put it in the sha256 of that platform and build again, until both pass.
|
|||
// install.js also fails if an unpacked build is not the version set here.
|
|||
module.exports = { |
|||
// The packages: snapshot builds of the open source code, published by the Chromium project.
|
|||
// exclude: glob patterns of the files that are not packaged
|
|||
// strip: glob patterns of the executables to strip of their symbols, when GNU strip is installed
|
|||
snapshot: { |
|||
version: '156.0.8078.0', |
|||
baseUrl: 'https://commondatastorage.googleapis.com/chromium-browser-snapshots', |
|||
// The .pak.info files, 70 MB, are left from the build of the translations; the browser does not read them
|
|||
linux: { path: 'Linux_x64/1706520/chrome-linux.zip', sha256: '6b62846a868ea3ee675f77600790877a428dfb2428c940f8eff99db1038f9815', |
|||
exclude: ['locales/*.pak.info'], |
|||
// The Linux builds come with their symbols, 180 MB
|
|||
strip: ['chrome', 'chrome_crashpad_handler', 'chrome_sandbox', '*.so*'] }, |
|||
// interactive_ui_tests.exe is a test program of 348 MB that the service does not need
|
|||
windows: { path: 'Win_x64/1706509/chrome-win.zip', sha256: '6bdfecb33dbfa7159e5666798bdc28c76347bef913573e899cb43930b78d26cc', |
|||
exclude: ['interactive_ui_tests.exe'] } |
|||
} |
|||
}; |
|||
@ -0,0 +1,12 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
|
|||
// negotiator 1.x ships no types, and @types/negotiator (0.6) lacks the `preferred` option
|
|||
declare module 'negotiator' { |
|||
import { IncomingMessage } from 'http'; |
|||
|
|||
export default class Negotiator { |
|||
constructor(request: IncomingMessage); |
|||
encoding(available: string[], options?: { preferred?: string[] }): string | undefined; |
|||
} |
|||
} |
|||
@ -0,0 +1,82 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
|
|||
// Writes .br and .gz copies of the production build's files, served as-is by the monolith and msa/web-ui.
|
|||
// Not an esbuild plugin: Angular gives custom plugins only the browser code bundle, not polyfills,
|
|||
// global styles/scripts or copied assets.
|
|||
|
|||
const os = require('node:os'); |
|||
|
|||
// zlib runs on the libuv thread pool (4 threads by default), which must be sized before its first use.
|
|||
// More than 8 threads gains nothing: the largest chunk alone takes ~5 s.
|
|||
const concurrency = Math.min(os.availableParallelism(), 8); |
|||
process.env.UV_THREADPOOL_SIZE = String(concurrency); |
|||
|
|||
const fs = require('node:fs'); |
|||
const path = require('node:path'); |
|||
const { promisify } = require('node:util'); |
|||
const zlib = require('node:zlib'); |
|||
|
|||
const gzip = promisify(zlib.gzip); |
|||
const brotliCompress = promisify(zlib.brotliCompress); |
|||
|
|||
const buildDir = path.join(__dirname, 'target', 'generated-resources', 'public'); |
|||
// already-compressed formats (png, webp, woff2, ...) are left out
|
|||
const compressibleExtensions = new Set(['.js', '.mjs', '.css', '.html', '.json', '.svg', '.txt', '.md', '.ttf', '.otf', '.eot']); |
|||
const minSize = 10240; |
|||
|
|||
// brotli quality 11 is only ~2% smaller than 10 but 3x slower; must match precompressedEncodings in msa/web-ui
|
|||
const encoders = [ |
|||
{ |
|||
ext: '.br', |
|||
encode: content => brotliCompress(content, { |
|||
params: { |
|||
[zlib.constants.BROTLI_PARAM_QUALITY]: 10, |
|||
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: content.length |
|||
} |
|||
}) |
|||
}, |
|||
{ |
|||
ext: '.gz', |
|||
encode: content => gzip(content, { level: zlib.constants.Z_BEST_COMPRESSION }) |
|||
} |
|||
]; |
|||
|
|||
function listFiles(dir) { |
|||
return fs.readdirSync(dir, { recursive: true, withFileTypes: true }) |
|||
.filter(entry => entry.isFile()) |
|||
.map(entry => path.join(entry.parentPath, entry.name)); |
|||
} |
|||
|
|||
async function compress(file, { ext, encode }) { |
|||
const content = await fs.promises.readFile(file); |
|||
const compressed = await encode(content); |
|||
if (compressed.length < content.length) { |
|||
await fs.promises.writeFile(file + ext, compressed); |
|||
} |
|||
} |
|||
|
|||
async function main() { |
|||
// largest first, so the main chunk does not start last
|
|||
const files = listFiles(buildDir) |
|||
.map(file => ({ file, size: fs.statSync(file).size })) |
|||
.filter(({ file, size }) => compressibleExtensions.has(path.extname(file).toLowerCase()) && size >= minSize) |
|||
.sort((a, b) => b.size - a.size) |
|||
.map(({ file }) => file); |
|||
const jobs = files.flatMap(file => encoders.map(encoder => () => compress(file, encoder))); |
|||
let next = 0; |
|||
const worker = async () => { |
|||
while (next < jobs.length) { |
|||
await jobs[next++](); |
|||
} |
|||
}; |
|||
const start = Date.now(); |
|||
await Promise.all(Array.from({ length: concurrency }, worker)); |
|||
console.log(`Compressed ${files.length} files (${encoders.map(e => e.ext).join(', ')}) in ${path.relative(__dirname, buildDir)} ` + |
|||
`in ${((Date.now() - start) / 1000).toFixed(1)} s on ${concurrency} threads`); |
|||
} |
|||
|
|||
main().catch(error => { |
|||
console.error(error); |
|||
process.exit(1); |
|||
}); |
|||
@ -1,95 +1,30 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
SPDX-License-Identifier: Apache-2.0 |
|||
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
|
|||
--> |
|||
@if (panelMode) { |
|||
<ng-container *ngTemplateOutlet="deviceFilterPanel"></ng-container> |
|||
} @else { |
|||
@if (buttonMode) { |
|||
<button color="primary" |
|||
matTooltip="{{buttonDisplayValue}}" |
|||
matTooltipPosition="above" |
|||
mat-stroked-button |
|||
(click)="toggleDeviceFilterPanel($event)"> |
|||
<mat-icon>filter_list</mat-icon>{{buttonDisplayValue}} |
|||
</button> |
|||
} @else { |
|||
<div class="tb-device-filter-config-component tb-form-panel no-padding no-border" [formGroup]="deviceInfoFilterForm"> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>device-profile.device-profile</div> |
|||
<tb-device-profile-autocomplete |
|||
class="flex-1" |
|||
formControlName="deviceProfileId" |
|||
[inlineField]="true" |
|||
[displayAllOnEmpty]="true" |
|||
(deviceProfileChanged)="deviceProfileChanged($event)" |
|||
[editProfileEnabled]="false" |
|||
[addNewProfile]="false"> |
|||
</tb-device-profile-autocomplete> |
|||
</div> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>device.device-state</div> |
|||
<mat-form-field class="flex-1" appearance="outline" subscriptSizing="dynamic"> |
|||
<mat-select formControlName="active" placeholder="{{ 'device.any' | translate }}"> |
|||
<mat-option>{{ 'device.any' | translate }}</mat-option> |
|||
<mat-option [value]="true">{{ 'device.active' | translate }}</mat-option> |
|||
<mat-option [value]="false">{{ 'device.inactive' | translate }}</mat-option> |
|||
</mat-select> |
|||
</mat-form-field> |
|||
</div> |
|||
</div> |
|||
} |
|||
} |
|||
<ng-template #deviceFilterPanel> |
|||
<form class="mat-content mat-padding flex flex-col" (ngSubmit)="update()"> |
|||
<ng-container *ngTemplateOutlet="deviceFilter"></ng-container> |
|||
<div class="tb-panel-actions flex flex-row items-center justify-end"> |
|||
<button type="button" |
|||
mat-button |
|||
color="primary" |
|||
(click)="reset()"> |
|||
{{ 'action.reset' | translate }} |
|||
</button> |
|||
<span class="flex-1"></span> |
|||
<button type="button" |
|||
mat-button |
|||
(click)="cancel()"> |
|||
{{ 'action.cancel' | translate }} |
|||
</button> |
|||
<button type="submit" |
|||
mat-raised-button |
|||
color="primary" |
|||
[disabled]="deviceInfoFilterForm.invalid || !deviceInfoFilterForm.dirty"> |
|||
{{ 'action.update' | translate }} |
|||
</button> |
|||
</div> |
|||
</form> |
|||
</ng-template> |
|||
<ng-template #deviceFilter> |
|||
<div class="tb-device-filter-config-component tb-form-panel no-padding no-border" [formGroup]="deviceInfoFilterForm"> |
|||
<ng-container [formGroup]="deviceInfoFilterForm"> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>device-profile.device-profile</div> |
|||
<tb-device-profile-autocomplete |
|||
class="flex-1" |
|||
class="min-w-0 flex-1" |
|||
formControlName="deviceProfileId" |
|||
[inlineField]="true" |
|||
[displayAllOnEmpty]="true" |
|||
(deviceProfileChanged)="deviceProfileChanged($event)" |
|||
[editProfileEnabled]="false" |
|||
[addNewProfile]="false"> |
|||
</tb-device-profile-autocomplete> |
|||
</div> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>device.device-state</div> |
|||
<mat-form-field class="flex-1" appearance="outline" subscriptSizing="dynamic"> |
|||
<mat-select formControlName="active" placeholder="{{ 'device.any' | translate }}"> |
|||
<mat-form-field class="min-w-0 flex-1" appearance="outline" subscriptSizing="dynamic"> |
|||
<mat-select formControlName="active" placeholder="{{ 'device.any' | translate }}" [aria-label]="'device.device-state' | translate"> |
|||
<mat-option>{{ 'device.any' | translate }}</mat-option> |
|||
<mat-option [value]="true">{{ 'device.active' | translate }}</mat-option> |
|||
<mat-option [value]="false">{{ 'device.inactive' | translate }}</mat-option> |
|||
</mat-select> |
|||
</mat-form-field> |
|||
</div> |
|||
</div> |
|||
</ng-template> |
|||
</ng-container> |
|||
|
|||
@ -1,21 +1,28 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
SPDX-License-Identifier: Apache-2.0 |
|||
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
|
|||
--> |
|||
<mat-form-field class="mat-block" subscriptSizing="dynamic"> |
|||
<mat-label translate>javascript.script-type</mat-label> |
|||
<mat-select [ngModel]="entitiesTableConfig.componentsData.resourceSubType" |
|||
(ngModelChange)="jsResourceSubTypeChanged($event)" |
|||
placeholder="{{ 'javascript.javascript-type' | translate }}"> |
|||
<mat-option value=""> |
|||
{{ "javascript.all-types" | translate }} |
|||
</mat-option> |
|||
@for (jsResourceSubType of jsResourceSubTypes; track jsResourceSubType) { |
|||
<mat-option [value]="jsResourceSubType"> |
|||
{{ resourceSubTypesTranslationMap.get(jsResourceSubType) | translate }} |
|||
</mat-option> |
|||
} |
|||
</mat-select> |
|||
</mat-form-field> |
|||
<tb-filter-button emptyLabel="javascript.script-filter-title" |
|||
emptyValue="" |
|||
[valueLabel]="jsResourceSubTypeLabel" |
|||
[ngModel]="entitiesTableConfig.componentsData.resourceSubType" |
|||
(ngModelChange)="jsResourceSubTypeChanged($event)"> |
|||
<ng-template let-control> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>javascript.script-type</div> |
|||
<mat-form-field class="min-w-0 flex-1" appearance="outline" subscriptSizing="dynamic"> |
|||
<mat-select [formControl]="control" [aria-label]="'javascript.script-type' | translate"> |
|||
<mat-option value="">{{ 'javascript.all-types' | translate }}</mat-option> |
|||
@for (jsResourceSubType of jsResourceSubTypes; track jsResourceSubType) { |
|||
<mat-option [value]="jsResourceSubType"> |
|||
{{ resourceSubTypesTranslationMap.get(jsResourceSubType) | translate }} |
|||
</mat-option> |
|||
} |
|||
</mat-select> |
|||
</mat-form-field> |
|||
</div> |
|||
</ng-template> |
|||
</tb-filter-button> |
|||
|
|||
@ -1,21 +1,28 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
SPDX-License-Identifier: Apache-2.0 |
|||
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
|
|||
--> |
|||
<mat-form-field class="mat-block" subscriptSizing="dynamic"> |
|||
<mat-label translate>resource.resource-type</mat-label> |
|||
<mat-select [ngModel]="entitiesTableConfig.componentsData.resourceType" |
|||
(ngModelChange)="resourceTypeChanged($event)" |
|||
placeholder="{{ 'resource.resource-type' | translate }}"> |
|||
<mat-option value=""> |
|||
{{ "resource.all-types" | translate }} |
|||
</mat-option> |
|||
@for (resourceType of resourceTypes; track resourceType) { |
|||
<mat-option [value]="resourceType"> |
|||
{{ resourceTypesTranslationMap.get(resourceType) | translate }} |
|||
</mat-option> |
|||
} |
|||
</mat-select> |
|||
</mat-form-field> |
|||
<tb-filter-button emptyLabel="resource.resource-filter-title" |
|||
emptyValue="" |
|||
[valueLabel]="resourceTypeLabel" |
|||
[ngModel]="entitiesTableConfig.componentsData.resourceType" |
|||
(ngModelChange)="resourceTypeChanged($event)"> |
|||
<ng-template let-control> |
|||
<div class="tb-form-row column-xs"> |
|||
<div class="fixed-title-width" translate>resource.resource-type</div> |
|||
<mat-form-field class="min-w-0 flex-1" appearance="outline" subscriptSizing="dynamic"> |
|||
<mat-select [formControl]="control" [aria-label]="'resource.resource-type' | translate"> |
|||
<mat-option value="">{{ 'resource.all-types' | translate }}</mat-option> |
|||
@for (resourceType of resourceTypes; track resourceType) { |
|||
<mat-option [value]="resourceType"> |
|||
{{ resourceTypesTranslationMap.get(resourceType) | translate }} |
|||
</mat-option> |
|||
} |
|||
</mat-select> |
|||
</mat-form-field> |
|||
</div> |
|||
</ng-template> |
|||
</tb-filter-button> |
|||
|
|||
@ -1,6 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
:host ::ng-deep .mat-mdc-slide-toggle .mdc-label { |
|||
white-space: normal; |
|||
} |
|||
@ -1,50 +0,0 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
|
|||
--> |
|||
<form [formGroup]="uploadFileFormGroup" (ngSubmit)="save()" style="width: 800px;"> |
|||
<mat-toolbar color="tb-primary" class="tb-bottom-border"> |
|||
<h2>{{ 'dashboard.update-new-version' | translate }}</h2> |
|||
<span class="flex-1"></span> |
|||
<button mat-icon-button |
|||
(click)="cancel()" |
|||
type="button"> |
|||
<mat-icon class="material-icons">close</mat-icon> |
|||
</button> |
|||
</mat-toolbar> |
|||
@if (isLoading$ | async) { |
|||
<mat-progress-bar color="warn" mode="indeterminate"> |
|||
</mat-progress-bar> |
|||
} @else { |
|||
<div style="height: 4px;"></div> |
|||
} |
|||
<div mat-dialog-content> |
|||
<tb-file-input [contentConvertFunction]="loadDataFromJsonContent" |
|||
[existingFileName]="currentFileName" |
|||
(fileNameChanged)="currentFileName = $event" |
|||
label="{{'dashboard.upload-file-to-update' | translate}}" |
|||
formControlName="file" |
|||
dropLabel="{{ 'import.drop-json-file-or' | translate }}" |
|||
accept=".json,application/json" |
|||
allowedExtensions="json"> |
|||
</tb-file-input> |
|||
</div> |
|||
|
|||
<div mat-dialog-actions class="flex flex-row items-center justify-end"> |
|||
<button mat-button color="primary" |
|||
type="button" |
|||
[disabled]="(isLoading$ | async)" |
|||
(click)="cancel()" cdkFocusInitial> |
|||
{{ 'action.cancel' | translate }} |
|||
</button> |
|||
<button mat-raised-button color="primary" |
|||
type="submit" |
|||
[disabled]="(isLoading$ | async) || uploadFileFormGroup.invalid |
|||
|| !uploadFileFormGroup.dirty"> |
|||
{{ 'action.save' | translate }} |
|||
</button> |
|||
</div> |
|||
</form> |
|||
@ -1,77 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
|
|||
import { Component, Inject, OnInit } from '@angular/core'; |
|||
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; |
|||
import { Store } from '@ngrx/store'; |
|||
import { AppState } from '@core/core.state'; |
|||
import { FormBuilder, FormGroup } from '@angular/forms'; |
|||
import { DashboardService } from '@core/http/dashboard.service'; |
|||
import { DashboardInfo } from '@app/shared/models/dashboard.models'; |
|||
import { ActionNotificationShow } from '@core/notification/notification.actions'; |
|||
import { DialogComponent } from '@shared/components/dialog.component'; |
|||
import { Router } from '@angular/router'; |
|||
|
|||
export interface DashboardInfoDialogData { |
|||
dashboard: DashboardInfo; |
|||
} |
|||
|
|||
@Component({ |
|||
selector: 'tb-import-dashboard-file-dialog', |
|||
templateUrl: './import-dashboard-file-dialog.component.html', |
|||
styleUrls: [], |
|||
standalone: false |
|||
}) |
|||
export class ImportDashboardFileDialogComponent extends DialogComponent<ImportDashboardFileDialogComponent> implements OnInit { |
|||
|
|||
private dashboard: DashboardInfo; |
|||
currentFileName: string = ''; |
|||
uploadFileFormGroup: FormGroup; |
|||
|
|||
constructor(protected store: Store<AppState>, |
|||
protected router: Router, |
|||
@Inject(MAT_DIALOG_DATA) public data: DashboardInfoDialogData, |
|||
private dashboardService: DashboardService, |
|||
protected dialogRef: MatDialogRef<ImportDashboardFileDialogComponent>, |
|||
private fb: FormBuilder) { |
|||
super(store, router, dialogRef); |
|||
this.dashboard = data.dashboard; |
|||
} |
|||
|
|||
ngOnInit(): void { |
|||
this.uploadFileFormGroup = this.fb.group({ |
|||
file: [null] |
|||
}); |
|||
} |
|||
|
|||
cancel(): void { |
|||
this.dialogRef.close(); |
|||
} |
|||
|
|||
save() { |
|||
const fileControl = this.uploadFileFormGroup.get('file'); |
|||
if (!fileControl || !fileControl.value) { |
|||
return; |
|||
} |
|||
|
|||
const dashboardContent = { |
|||
...fileControl.value, |
|||
description: this.dashboard.configuration.description |
|||
}; |
|||
this.dashboard.configuration = dashboardContent; |
|||
|
|||
this.dashboardService.saveDashboard(this.dashboard).subscribe(() => { |
|||
this.dialogRef.close(true); |
|||
}) |
|||
} |
|||
|
|||
loadDataFromJsonContent(content: string): any { |
|||
try { |
|||
const importData = JSON.parse(content); |
|||
return importData ? importData['configuration'] : importData; |
|||
} catch (err) { |
|||
this.store.dispatch(new ActionNotificationShow({message: err.message, type: 'error'})); |
|||
return null; |
|||
} |
|||
} |
|||
} |
|||
@ -1,6 +0,0 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors |
|||
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. |
|||
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 |
|||
:host ::ng-deep .mat-mdc-slide-toggle .mdc-label { |
|||
white-space: normal; |
|||
} |
|||
@ -0,0 +1,41 @@ |
|||
<!-- |
|||
|
|||
SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. |
|||
SPDX-License-Identifier: BUSL-1.1 |
|||
|
|||
--> |
|||
<button color="primary" |
|||
matTooltip="{{ buttonDisplayValue() }}" |
|||
matTooltipPosition="above" |
|||
mat-stroked-button |
|||
[disabled]="disabled()" |
|||
(click)="openPanel($event)"> |
|||
<mat-icon>filter_list</mat-icon>{{ buttonDisplayValue() }} |
|||
</button> |
|||
<ng-template #filterPanel> |
|||
<form class="mat-content mat-padding flex flex-col" cdkTrapFocus cdkTrapFocusAutoCapture (ngSubmit)="update()"> |
|||
<div class="tb-filter-button-panel-content tb-form-panel no-padding no-border outline-none" tabindex="-1" cdkFocusInitial> |
|||
<ng-container *ngTemplateOutlet="panelContent(); context: {$implicit: filterControl}"></ng-container> |
|||
</div> |
|||
<div class="tb-panel-actions flex flex-row items-center justify-end"> |
|||
<button type="button" |
|||
mat-button |
|||
color="primary" |
|||
(click)="reset()"> |
|||
{{ 'action.reset' | translate }} |
|||
</button> |
|||
<span class="flex-1"></span> |
|||
<button type="button" |
|||
mat-button |
|||
(click)="cancel()"> |
|||
{{ 'action.cancel' | translate }} |
|||
</button> |
|||
<button type="submit" |
|||
mat-raised-button |
|||
color="primary" |
|||
[disabled]="filterControl.invalid || !isChanged()"> |
|||
{{ 'action.update' | translate }} |
|||
</button> |
|||
</div> |
|||
</form> |
|||
</ng-template> |
|||
@ -0,0 +1,204 @@ |
|||
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
|
|||
// SPDX-License-Identifier: BUSL-1.1
|
|||
import { |
|||
ChangeDetectionStrategy, |
|||
Component, |
|||
computed, |
|||
contentChild, |
|||
DestroyRef, |
|||
ElementRef, |
|||
forwardRef, |
|||
inject, |
|||
input, |
|||
signal, |
|||
TemplateRef, |
|||
viewChild, |
|||
ViewContainerRef |
|||
} from '@angular/core'; |
|||
import { ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR } from '@angular/forms'; |
|||
import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; |
|||
import { TemplatePortal } from '@angular/cdk/portal'; |
|||
import { FocusMonitor, InputModalityDetector } from '@angular/cdk/a11y'; |
|||
import { ESCAPE, hasModifierKey } from '@angular/cdk/keycodes'; |
|||
import { MatButton } from '@angular/material/button'; |
|||
import { toObservable, toSignal } from '@angular/core/rxjs-interop'; |
|||
import { TranslateService } from '@ngx-translate/core'; |
|||
import { fromEvent, isObservable, Observable, of, Subscription } from 'rxjs'; |
|||
import { catchError, filter, switchMap } from 'rxjs/operators'; |
|||
import { POSITION_MAP } from '@shared/models/overlay.models'; |
|||
import { isDefinedAndNotNull, isEqual, isObject } from '@core/utils'; |
|||
|
|||
export type FilterButtonValueLabelFn<T> = (value: T) => string | Observable<string>; |
|||
|
|||
export interface FilterButtonPanelContext<T> { |
|||
$implicit: FormControl<T>; |
|||
} |
|||
|
|||
/** |
|||
* Filter button for entity table headers. Shows the current filter value on the button and |
|||
* opens an overlay panel with Reset/Cancel/Update actions. The panel control is supplied |
|||
* by the host as an <ng-template let-control> bound to the provided FormControl. |
|||
*/ |
|||
@Component({ |
|||
selector: 'tb-filter-button', |
|||
templateUrl: './filter-button.component.html', |
|||
styleUrls: ['../../../../scss/filter-button.scss'], |
|||
changeDetection: ChangeDetectionStrategy.OnPush, |
|||
providers: [ |
|||
{ |
|||
provide: NG_VALUE_ACCESSOR, |
|||
useExisting: forwardRef(() => FilterButtonComponent), |
|||
multi: true |
|||
} |
|||
], |
|||
standalone: false |
|||
}) |
|||
export class FilterButtonComponent<T = any> implements ControlValueAccessor { |
|||
|
|||
private translate = inject(TranslateService); |
|||
private overlay = inject(Overlay); |
|||
private elementRef = inject(ElementRef); |
|||
private viewContainerRef = inject(ViewContainerRef); |
|||
private destroyRef = inject(DestroyRef); |
|||
private focusMonitor = inject(FocusMonitor); |
|||
private inputModality = inject(InputModalityDetector); |
|||
|
|||
emptyLabel = input.required<string>(); |
|||
valueLabel = input<FilterButtonValueLabelFn<T>>(value => String(value)); |
|||
emptyValue = input<T>(null); |
|||
|
|||
panelContent = contentChild.required<TemplateRef<FilterButtonPanelContext<T>>>(TemplateRef); |
|||
private panelTemplate = viewChild.required<TemplateRef<any>>('filterPanel'); |
|||
private filterButton = viewChild.required(MatButton, {read: ElementRef}); |
|||
|
|||
disabled = signal(false); |
|||
|
|||
filterControl = new FormControl<T>(null); |
|||
|
|||
private value = signal<T>(null); |
|||
|
|||
private valueText = toSignal( |
|||
toObservable(computed(() => ({value: this.value(), labelFn: this.valueLabel()}))).pipe( |
|||
switchMap(({value, labelFn}) => { |
|||
if (this.isEmpty(value)) { |
|||
return of(null); |
|||
} |
|||
const label = labelFn(value); |
|||
return (isObservable(label) ? label : of(label)).pipe(catchError(() => of(null))); |
|||
}) |
|||
), |
|||
{initialValue: null} |
|||
); |
|||
|
|||
buttonDisplayValue = computed(() => { |
|||
if (this.isEmpty(this.value())) { |
|||
return this.translate.instant(this.emptyLabel()); |
|||
} |
|||
const filterTitle = this.translate.instant('filter.filter'); |
|||
const valueText = this.valueText(); |
|||
return valueText ? `${filterTitle}: ${valueText}` : filterTitle; |
|||
}); |
|||
|
|||
private overlayRef: OverlayRef; |
|||
private resizeWindows: Subscription; |
|||
|
|||
private propagateChange = (_: any) => {}; |
|||
|
|||
constructor() { |
|||
this.destroyRef.onDestroy(() => this.closePanel(false)); |
|||
} |
|||
|
|||
registerOnChange(fn: any): void { |
|||
this.propagateChange = fn; |
|||
} |
|||
|
|||
registerOnTouched(_fn: any): void { |
|||
} |
|||
|
|||
setDisabledState(isDisabled: boolean): void { |
|||
this.disabled.set(isDisabled); |
|||
if (isDisabled) { |
|||
this.filterControl.disable({emitEvent: false}); |
|||
} else { |
|||
this.filterControl.enable({emitEvent: false}); |
|||
} |
|||
} |
|||
|
|||
writeValue(value?: T): void { |
|||
this.value.set(this.normalize(value)); |
|||
this.filterControl.setValue(this.value(), {emitEvent: false}); |
|||
} |
|||
|
|||
openPanel($event: Event) { |
|||
$event?.stopPropagation(); |
|||
const config = new OverlayConfig({ |
|||
panelClass: 'tb-filter-panel', |
|||
backdropClass: 'cdk-overlay-transparent-backdrop', |
|||
hasBackdrop: true, |
|||
maxHeight: '80vh', |
|||
height: 'min-content', |
|||
minWidth: '' |
|||
}); |
|||
config.positionStrategy = this.overlay.position() |
|||
.flexibleConnectedTo(this.elementRef) |
|||
.withPositions([POSITION_MAP.bottomLeft]); |
|||
|
|||
this.overlayRef = this.overlay.create(config); |
|||
this.overlayRef.backdropClick().subscribe(() => this.cancel()); |
|||
this.overlayRef.keydownEvents() |
|||
.pipe(filter(event => event.keyCode === ESCAPE && !hasModifierKey(event))) |
|||
.subscribe(event => { |
|||
event.preventDefault(); |
|||
this.cancel(); |
|||
}); |
|||
this.overlayRef.attach(new TemplatePortal(this.panelTemplate(), this.viewContainerRef)); |
|||
this.resizeWindows = fromEvent(window, 'resize').subscribe(() => this.overlayRef.updatePosition()); |
|||
} |
|||
|
|||
cancel() { |
|||
this.filterControl.setValue(this.value(), {emitEvent: false}); |
|||
this.filterControl.markAsPristine(); |
|||
this.closePanel(); |
|||
} |
|||
|
|||
update() { |
|||
this.value.set(this.normalize(this.filterControl.value)); |
|||
this.propagateChange(this.value()); |
|||
this.filterControl.markAsPristine(); |
|||
this.closePanel(); |
|||
} |
|||
|
|||
reset() { |
|||
if (!this.isEmpty(this.filterControl.value)) { |
|||
this.filterControl.setValue(this.emptyValue(), {emitEvent: false}); |
|||
this.filterControl.markAsDirty(); |
|||
} |
|||
} |
|||
|
|||
isChanged(): boolean { |
|||
return this.filterControl.dirty && !isEqual(this.normalize(this.filterControl.value), this.value()); |
|||
} |
|||
|
|||
private closePanel(restoreFocus = true) { |
|||
this.resizeWindows?.unsubscribe(); |
|||
this.resizeWindows = null; |
|||
if (this.overlayRef) { |
|||
this.overlayRef.dispose(); |
|||
this.overlayRef = null; |
|||
if (restoreFocus) { |
|||
this.focusMonitor.focusVia(this.filterButton(), this.inputModality.mostRecentModality ?? 'program'); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private normalize(value: T): T { |
|||
return this.isEmpty(value) ? this.emptyValue() : value; |
|||
} |
|||
|
|||
private isEmpty(value: T): boolean { |
|||
if (!isDefinedAndNotNull(value) || value === '') { |
|||
return true; |
|||
} |
|||
return isObject(value) && Object.values(value).every(v => !isDefinedAndNotNull(v) || v === ''); |
|||
} |
|||
} |
|||
Loading…
Reference in new issue